text:
Q: How to restore Bitbucket Backup using SCM Backup? I recently tried to take a backup of my BitBucket repositories using SCM Backup. Here is what I did:
Installed dot net on my MacOS
Installed SCM Backup
I created an App Password for SCM Backup in BitBucket.
I made the following changes in the settings.yml file:
# all backups go here
localFolder: 'c:\scm-backup'

# when an error occurs, wait that many seconds before exiting the application
waitSecondsOnError: 5

# uncomment this to send SCM Backup's console output via email
#email:
#  from: from@example.com
#  to: to@example.com
#  server: smtp.example.com
#  port: 0
#  useSsl: false
#  userName: testuser
#  password: not-the-real-password

sources:

  - title:  bitbucket_bkp
    hoster: bitbucket
    type: org
    name: my_username
    authName: my_username
    password: App Password that I created

Now when I run -
dotnet ScmBackup.dll

It gives the output -
SCM Backup 1.2.1.552abf5
https://scm-backup.org/
Backing up config files
Getting repositories for source 'bitbucket_bkp' from hoster 'bitbucket'
Trying to find SCMs on this machine...
Backing up source: bitbucket_bkp
Backup finished!
The backups are in this directory: c:\scm-backup

How do I restore the repositories from this c:\scm-backup file?
I am clueless about it.
Also as per the documentation bitbucket-scm-backup when I give the team name in the name field in the setting field it gives the below error:
SCM Backup 1.2.1.552abf5
https://scm-backup.org/
Backing up config files
Getting repositories for source 'bitbucket_bkp' from hoster 'bitbucket'
User my_team_name not found!
Backup failed!
The application will close in 5 seconds!

I want to take the backup of all the repositories of my team in BitBucket and restore it ?
What should I do ?
As per Chris suggestion I made the following changes in the settings.yml file -
# all backups go here
localFolder: '/Users/rahman/Desktop/'

Now when I take the backup I get a folder called bitbucket_bkp in my Desktop. But it is empty. How do I restore it?
Also how can I take the backup of the entire team by specifying the team name? It is not working for me.
To take the backup of my team I have made changes to the settings file like this -
# all backups go here
localFolder: '/Users/rahman/Desktop/riz_bkp/'

# when an error occurs, wait that many seconds before exiting the application
waitSecondsOnError: 5

# uncomment this to send SCM Backup's console output via email
#email:
#  from: from@example.com
#  to: to@example.com
#  server: smtp.example.com
#  port: 0
#  useSsl: false
#  userName: testuser
#  password: not-the-real-password

sources:

  - title:  bitbucket_bkp
    hoster: bitbucket
    type: org
    name: team_name

Now I get the error-
SCM Backup 1.2.1.552abf5
https://scm-backup.org/
bitbucket_bkp: AuthName and Password are empty. Without authentication, SCM Backup will backup public repositories only!
Backing up config files
Getting repositories for source 'bitbucket_bkp' from hoster 'bitbucket'
User team_name not found!
Backup failed!
The application will close in 5 seconds!

What to do ?

A: Question 1: "How do I restore the repositories from this c:\scm-backup file?"
Glad to hear that SCM Backup works on MacOS, but please note this in the System Requirements:

So far, SCM Backup has been written and tested on Windows only. Technically, it should run on Linux and MacOS as well, but this has not been tested yet.

I'm on Windows, and c:\scm-backup is a valid folder/directory on Windows, but will probably not work on a Mac.
(c: is the system drive on Windows)
I don't have access to a Mac, so I can't test anything...but according to what I just googled, you should use a path like /Users/your_user/Documents/scm-backup.
The path should already exist, and the user which is running SCM Backup should have write access to it.
If you can confirm that this works, I'll add it to the docs.
Concerning restores:
You probably read the documentation about restoring. The technical steps how to do the actual restore are described there, but what's missing right now is the description how the content of the local folder.
I'll add that to the documentation, but here's the short version:
After changing localFolder from c:\scm-backup to whatever works on MacOS, run SCM Backup and the folder should contain one subfolder per source defined in the config. So in your case, it should be named bitbucket_bkp.
Inside, there's one subfolder for each repository, and inside that, there's at least one subfolder repo (and maybe another named wiki, if that repo has a wiki).
This repo folder contains a full clone of your repository from Bitbucket, and this is the "local repository" that the documentation about restoring refers to.

Question 2: The backup gives an error when you try to backup a team
Please see the docs about sources in the configuration:

Each source must have at least those four properties:
[...]
type
Either user or org, depending if you want to backup an user or a organization.
name
The name of the user/organization you want to backup.

So it's either:
type: user
name: my_username

or:
type: org
name: my_team_name

In the example config you posted, it's a mixture of both.

A: SCM-Backup and Docker Desktop on MacOS
(I used Rori Stumpf's comment from: https://community.atlassian.com/t5/Bitbucket-questions/How-to-backup-the-Bitbucket-on-cloud/qaq-p/428076 and added the DOTNET_SKIP_FIRST_TIME_EXPERIENCE and updated the versions)
Dockerfile

content:
#   1. Install Docker
#
#   2. Copy the contents of this file to a file called 'Dockerfile'
#
#   3. Create settings.yml -- see https://docs.scm-backup.org/en/latest/config-bitbucket/#authentication
#
#   4. Build Docker Image:
#
#       docker build -t scm-backup .
#
#   5. Run the backup with output to ./bitbucket-backups:
#
#       docker run -t --mount src=`pwd`/bitbucket-backups,target=/scm-backup-out,type=bind scm-backup
#

FROM ubuntu:18.04

ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true

WORKDIR /scm-backup

# Install .NET core and SCM Backup
RUN apt-get update && apt-get -y install software-properties-common && \
    add-apt-repository universe && apt-get update && \
    apt-get -y install sudo wget unzip apt-transport-https git && \
    wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb && \
    dpkg -i packages-microsoft-prod.deb && rm packages-microsoft-prod.deb && \
    apt-get update && \
    apt-get -y install dotnet-sdk-3.1 && \
    wget https://github.com/christianspecht/scm-backup/releases/download/1.4.0/scm-backup-1.4.0.ae7edc3.zip && \
    unzip scm-backup-1.4.0.ae7edc3.zip

# Copy settings.yml from local filesystem to the container (rebuild every time settings.yml is updated)
COPY settings.yml .

# Run the backup
ENTRYPOINT dotnet ScmBackup.dll

settings.yml

content:
localFolder: '/scm-backup-out'

sources:
  - title: git_backup_from_bitbucket
    hoster: bitbucket
    type: org
    name: team_or_workspace_name_here
    authName: username_here_not_email_address
    password: app_password_here

Folder structure:
bitbucket-backups
Dockerfile
settings.yml

Usage:
docker build -t scm-backup .

docker run -t --mount src=`pwd`/bitbucket-backups,target=/scm-backup-out,type=bind scm-backup


text:
Q: Why is a covered query sometimes slower in MongoDB? I was under the impression that covered queries were always faster than scanning the collection itself. So why is this covered query slower?
Covered query:
> db.group_panel_responses.find({}, {_id: 0, _panel_id: 1, _group_id: 1, response_count: 1}).hint({_panel_id: 1, _group_id: 1, response_count: -1}).explain()
{
    "cursor" : "BtreeCursor _panel_id_1__group_id_1_response_count_-1",
    "isMultiKey" : false,
    "n" : 20000,
    "nscannedObjects" : 0,
    "nscanned" : 20000,
    "nscannedObjectsAllPlans" : 0,
    "nscannedAllPlans" : 20000,
    "scanAndOrder" : false,
    "indexOnly" : true,
    "nYields" : 156,
    "nChunkSkips" : 0,
    "millis" : 44,
    "indexBounds" : {
        "_panel_id" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ],
        "_group_id" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ],
        "response_count" : [
            [
                {
                    "$maxElement" : 1
                },
                {
                    "$minElement" : 1
                }
            ]
        ]
    },
    "server" : "DAAVID.local:27017",
    "filterSet" : false
}

Same query but without hinting at the index, so not a covered query:
> db.group_panel_responses.find({}, {_id: 0, _panel_id: 1, _group_id: 1, response_count: 1}).explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 20000,
    "nscannedObjects" : 20000,
    "nscanned" : 20000,
    "nscannedObjectsAllPlans" : 20000,
    "nscannedAllPlans" : 20000,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 156,
    "nChunkSkips" : 0,
    "millis" : 40,
    "server" : "DAAVID.local:27017",
    "filterSet" : false
}

A: Keep in mind that a query that is covered by an index is generally faster than a regular query because you can retrieve the fields for each document in one step, as opposed to two in a regular query, where you hit the index to find the location of the document and then hit the collection itself to retrieve the fields.
To over simplify a bit, in a normal case where my selection criteria would retrieve 20000 documents, a normal query would have 40000 accesses (20000 for the index and 20000 for the collection) while a covered query would only have 20000 accesses.
In your test case, however, you have no selection criteria. So both queries, covered and uncovered, will do a full collection scan. In this case you lose almost all of the performance boost of a covered query with selection criteria.
If you really want to test the value of a covered query I'd use a much larger document collection and a much more selective query. If the test you are using is representative of your actual production usage I would not expect any performance boost at all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failure updating GCP Composer and Airflow image When I try to update my Composer environment (on GCP) from the version composer-1.7.2-airflow-1.10.2 to composer-1.12.0-airflow-1.10.10 (or any other available) I always get this error:
UPDATE operation on this environment failed Just now with the following error message:
Failed to update image version.
The Cloud Build image build failed: Build failed; check build logs for details

After looking in the build logs I can only see this error below that doesn't help me so much:
The command '/bin/sh -c bash installer.sh $COMPOSER_PYTHON_VERSION  fail' returned a non-zero code: 1
ERROR
ERROR: build step 0 "gcr.io/cloud-builders/docker" failed: step exited with non-zero status: 1

What could be going on?

A: I found this guide in Composer Docs https://cloud.google.com/composer/docs/how-to/managing/updating that gave me some clue about what was going on.
Then I succeeded after doing this:

*

*ensured that these conditions from the link above were met

*became Admin, I was editor (that should have permission), but I became Admin to eliminate permissions doubts

*removed all PYPI packages from the environment

Emprically speaking, I think the problem was because of the Pypi packages. Some of them was not compatible with the new composer version and this was broking the build. The logs altought didn't let this clear.
I hope it helps because I struggled to find help with this problem.


text:
Q: Combinatorial Probability vs Binomial Probability Problem:

A gardener has twelve identical looking tulip bulbs, of which eight
  will produce yellow tulips and four will become pink. She randomly
  selects and plants five of them and gives the rest away. When the
  flowers start to bloom, what is the probability that exactly three of
  them are yellow?

I first approached this problem using combinations:
$\frac{\binom{8}{3}\binom{4}{2}}{\binom{12}{5}}=\frac{14}{33}$
Then, just for the heck of it, I attempted to solve the problem using
binomial probability. I defined "success" to be planting a yellow flower and "failure" to be planting a pink flower.
$P(\text{success})=\frac{2}{3}$ and $P(\text{failure})=\frac{1}{3}$
$P(\text{3 successes in 5 trials}) = \binom{5}{3} (\frac{2}{3})^{3} (\frac{1}{3})^{2} = \frac{80}{243}$
I'm guessing one of the conditions for using the binomial distribution was violated?

*

*The number of observations n is fixed.

*Each observation is independent.

*Each observation represents one of two outcomes ("success" or "failure").

*The probability of "success" p is the same for each outcome.

None of these seem to be violated to me. Can someone clarify please?

A: You were correct to use the hypergeometric distribution to solve the problem since the flower bulbs are selected without replacement.  The binomial distribution is used when selections are made with replacement.  In particular, the probability of success must be the same for each outcome, which is not the case here since selecting a yellow flower changes the probability that the next flower you select is also yellow.


text:
Q: С++ Объект удалён, но добраться можно, почему так? class A
    {
    public:
        int d = 4;
    };

    int main( )
{
    A *a = new A();
    cout << a->d << endl;
    A* p = &(*a);
    delete a;
    p->d = 5;
    a->d=3;
    cout << a->d << endl;
    return 0;
}

Поясните пожалуйста этот код. По какой причине p->d работает даже после удаления a? То есть после delete если сразу вывести p->d, там будет мусорное значение.
Верно ли я понимаю, что p попросту указывает на некоторую область памяти, и компилятор(при создании указателя) "узнал", как обрабатывать выражения типа p->d, и дальше ему уже без разницы, есть ли там реально какой-то объект, к которому мы собираемся обращаться другим способом?
И дальше в коде p можно продолжать использовать как указатель на объект? или мы рискуем получить какие-то конфликты с памятью?
Что именно делает delete? Вопрос задан с целью разобраться, что именно происходит. Прилагаю ассемблерный код.
A::A() [base object constructor]:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     rax, QWORD PTR [rbp-8]
        mov     DWORD PTR [rax], 4
        nop
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        push    rbx
        sub     rsp, 24
        mov     edi, 4
        call    operator new(unsigned long)
        mov     rbx, rax
        mov     DWORD PTR [rbx], 0
        mov     rdi, rbx
        call    A::A() [complete object constructor]
        mov     QWORD PTR [rbp-24], rbx
        mov     rax, QWORD PTR [rbp-24]
        mov     eax, DWORD PTR [rax]
        mov     esi, eax
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     esi, OFFSET FLAT:_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
        mov     rdi, rax
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))
        mov     rax, QWORD PTR [rbp-24]
        mov     QWORD PTR [rbp-32], rax
        mov     rax, QWORD PTR [rbp-24]
        test    rax, rax
        je      .L3
        mov     esi, 4
        mov     rdi, rax
        call    operator delete(void*, unsigned long)
.L3:
        mov     rax, QWORD PTR [rbp-32]
        mov     DWORD PTR [rax], 5
        mov     rax, QWORD PTR [rbp-24]
        mov     DWORD PTR [rax], 3
        mov     rax, QWORD PTR [rbp-24]
        mov     eax, DWORD PTR [rax]
        mov     esi, eax
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     esi, OFFSET FLAT:_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
        mov     rdi, rax
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))
        mov     eax, 0
        mov     rbx, QWORD PTR [rbp-8]
        leave
        ret
__static_initialization_and_destruction_0(int, int):
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     DWORD PTR [rbp-4], edi
        mov     DWORD PTR [rbp-8], esi
        cmp     DWORD PTR [rbp-4], 1
        jne     .L7
        cmp     DWORD PTR [rbp-8], 65535
        jne     .L7
        mov     edi, OFFSET FLAT:_ZStL8__ioinit
        call    std::ios_base::Init::Init() [complete object constructor]
        mov     edx, OFFSET FLAT:__dso_handle
        mov     esi, OFFSET FLAT:_ZStL8__ioinit
        mov     edi, OFFSET FLAT:_ZNSt8ios_base4InitD1Ev
        call    __cxa_atexit
.L7:
        nop
        leave
        ret
_GLOBAL__sub_I_main:
        push    rbp
        mov     rbp, rsp
        mov     esi, 65535
        mov     edi, 1
        call    __static_initialization_and_destruction_0(int, int)
        pop     rbp
        ret

A: Это работает только из-за того, что вам повезло. Судя по всему перед этим куском памяти был другой кусок, который принадлежал вашему процессу. Потому менеджер памяти ничего вам не сказал. Был бы перед этим куском памяти другой кусок памяти, который бы принадлежал другому процессу - вам бы не удалось ничего в него записать (Это можно сделать, но не так).


text:
Q: Magic variable for entire command, including && I'm trying to write a little function for bash like so:
alias timesec='/usr/bin/time --format="%C took %e seconds"'

prun() {
    echo \$ $@
    timesec $*
}

But when I use it, I get:
mpen@mpen:/topsecret$ prun echo foo && echo bar
$ echo foo
foo
echo foo took 0.00 seconds
bar

I want that first line to say $ echo foo && echo bar and the timesec should also apply to the entirety of the command (echo foo && echo bar) not just the first half.
How would I do this?

A: You can use the TIMEFORMAT variable to customize the output of bash's time builtin:
 cmd="/bin/echo foo && /bin/echo bar"
 # See man bash for the TIMEFORMAT variable
 PREV_TIMEFORMAT="${TIMEFORMAT}"
 TIMEFORMAT="The command ${cmd} took %lR"
 # You could use time eval "${cmd}". I don't recommend that
 time /bin/echo foo && /bin/echo bar

Output:
foo
bar
The command /bin/echo foo && /bin/echo bar took 0m0.00s

Note: The above "solution" doesn't work when you use bash's echo builtin.


text:
Q: Spring Boot 2.0.x - @Configuration class @Autowired entityManagerFactory NullPointerException I used Hibernate session to query data from MySQL. I used JPA EntityManagerFactory to get Hibernate SessionFactory:
@Configuration
public class DatabaseConfig {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public SessionFactory getSessionFactory() {
        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("Factory is not a hibernate factory");
        }
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
}

This worked fine with Spring Boot 1.5.x. But when I updated Spring Boot to 2.0.1:

Error creating bean with name 'databaseConfig': Unsatisfied dependency expressed through field 'entityManagerFactory';

What should I do to solve this problem in Spring Boot 2.0.x?


text:
Q: C++ Writing a column of a CSV file into a vector I have a CSV file with a bunch of columns, but I only need the information for the 11th column. How do I read through each line and skip to the 11th column in each line? I'm struggling to find clear information on how to read files in c++. This is what I have so far:
#include<iostream>
#include<fstream>
#include<vector>
#include <sstream>
#include <string>

std::string readStock(std::string fileName){
   std::vector<std::string> ticker; //create vector
   std::ifstream f(fileName, std::ios::in|std::ios:: binary|std::ios::ate);
   std::string finalString = "";
   if(f.is_open()){
     std::string str;
     std::getline(f,str); //skip the first row
     while(std::getline(f,str)){ //read each line
       std::istringstream s(str);  //stringstream to parse csv
       std::string val;  //string to hold value
       for(int i=1;i<=10;++i){ //skips everything until we get to the
column that we want
         while(std::getline(s,val, ',')){
         }
       std::getline(s,val,',');
       ticker.push_back(val);
     }
     f.close();

     finalString = ticker.front();
   }
}
   else{
     finalString="Could not open the file properly.";
   }
   return finalString;
}
int main(){
   std::string st;
   st=readStock("pr.csv");
   std::cout<<st<<std::endl;
   return 0;
}

A: There is a very simple solution for your problem.
You define a proxy class that reads one complete line, splits it into ALL tokens, using the dedicated functionality of the std::regex_token_iterator and then extracts the 11th element.
Using this proxy mechanism, you can use the std::istream_iterator to read the complete file, column 11, into a std::vector. For that we use the range constructor of the std::vector.
The result is a simple and short one-liner.
Please see:
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <regex>
#include <iterator>
#include <algorithm>

std::regex delimiter{ "," };
constexpr size_t targetColumn = 10U; // Target column is eleven

struct String11 {   // Proxy for the input Iterator

    // Overload extractor. Read a complete line
    friend std::istream& operator>>(std::istream& is, String11& s11) {

        // Read a complete line
        if (std::string line{}; std::getline(is, line)) {

            // Split it into tokens
            std::vector token(std::sregex_token_iterator(line.begin(), line.end(), delimiter, -1), {});
            // We only need one column
            if (targetColumn < token.size()) {
                // Get column 11
                s11.result = token[targetColumn];
            }
        }
        return is;
    }

    // Cast the type 'String11' to std::string
    operator std::string() const { return result; }

    // Temporary to hold the resulting string
    std::string result{};
};

int main() {

    // Open CSV fíle
    if (std::ifstream csvFile{ "pr.csv" }; csvFile) {

        // Read complete CSV file and get column 11 of each line
        std::vector col11(std::istream_iterator<String11>(csvFile), {});

        // Show output. Show all columns 11
        std::copy(col11.begin(), col11.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    }
    return 0;
}

EDIT:
For having output with doubles.
We just change one line in the cast operator in the proxy. That's all.
Even in main, there is no change in the read operatrion necessary. Through CTAD, the vector will be of type double.
Please see:
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <regex>
#include <iterator>
#include <algorithm>

std::regex delimiter{ "," };
constexpr size_t targetColumn = 10U; // Target column is eleven

struct String11 {   // Proxy for the input Iterator

    // Overload extractor. Read a complete line
    friend std::istream& operator>>(std::istream& is, String11& s11) {

        // Read a complete line
        if (std::string line{}; std::getline(is, line)) {

            // Split it into tokens
            std::vector token(std::sregex_token_iterator(line.begin(), line.end(), delimiter, -1), {});
            // We only need one column
            if (targetColumn < token.size()) {
                // Get column 11
                s11.result = token[targetColumn];
            }
        }
        return is;
    }

    // Cast the type 'String11' to double
    operator double() const { return std::stod(result); }

    // Temporary to hold the resulting string
    std::string result{};
};

int main() {

    // Open CSV fíle
    if (std::ifstream csvFile{ "r:\\pr.csv" }; csvFile) {

        // Read complete CSV file and get column 11 of each line
        std::vector col11(std::istream_iterator<String11>(csvFile), {});

        // Show output. Show all columns 11
        std::copy(col11.begin(), col11.end(), std::ostream_iterator<double>(std::cout, "\n"));
    }
    return 0;
}

Output needs to adapted as well.


text:
Q: WCF fails to deserialize correct(?) response message security headers (Security header is empty) I'm communicating with an OC4J webservice, using a WCF client. The client is configured as follows:
        <basicHttpBinding>
<binding name="MyBinding">
 <security mode="TransportWithMessageCredential">
  <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
  <message clientCredentialType="UserName" algorithmSuite="Default"/>
 </security>
</binding>

My clientcode looks as follows:
    ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

    string username = ConfigurationManager.AppSettings["user"];
    string password = ConfigurationManager.AppSettings["pass"];

    // client instance maken
    WebserviceClient client = new WebserviceClient();

    client.Endpoint.Binding = new BasicHttpBinding("MyBinding");

    // credentials toevoegen
    client.ClientCredentials.UserName.UserName = username;
    client.ClientCredentials.UserName.Password = password;

    //uitvoeren request
    var response = client.Ping();

I've altered the CertificatePolicy to accept all certificates, because I need to insert Charles (ssl proxy) in between client and server to intercept the actual Xml that is sent across te wire.
My request looks as follows:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
 <u:Timestamp u:Id="_0">
  <u:Created>2010-04-01T09:47:01.161Z</u:Created>
  <u:Expires>2010-04-01T09:52:01.161Z</u:Expires>
 </u:Timestamp>
 <o:UsernameToken u:Id="uuid-9b39760f-d504-4e53-908d-6125a1827aea-21">
  <o:Username>user</o:Username>
  <o:Password o:Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username- token-profile-1.0#PasswordText">pass</o:Password>
 </o:UsernameToken>
</o:Security>
</s:Header>
<s:Body>
<getPrdStatus xmlns="http://mynamespace.org/wsdl">
 <request xmlns="" xmlns:a="http://mynamespace.org/wsdl"  xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <a:IsgrStsRequestTypeUser>
   <a:prdCode>LEPTO</a:prdCode>
   <a:sequenceNumber i:nil="true" />
   <a:productionType i:nil="true" />
   <a:statusDate>2010-04-01T11:47:01.1617641+02:00</a:statusDate>
   <a:ubn>123456</a:ubn>
   <a:animalSpeciesCode>RU</a:animalSpeciesCode>
  </a:IsgrStsRequestTypeUser>
 </request>
 </getPrdStatus>
 </s:Body>
</s:Envelope>

In return, I receive the following response:
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://mynamespace.org/wsdl">
<env:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" env:mustUnderstand="1" />
</env:Header>
<env:Body>
<ns0:getPrdStatusResponse>
<result>
  <ns0:IsgrStsResponseTypeUser>
  <ns0:prdCode>LEPTO</ns0:prdCode>
  <ns0:color>green</ns0:color>
  <ns0:stsCode>LEP1</ns0:stsCode>
  <ns0:sequenceNumber xsi:nil="1" />
  <ns0:productionType xsi:nil="1" />
  <ns0:IAndRCode>00</ns0:IAndRCode>
  <ns0:statusDate>2010-04-01T00:00:00.000+02:00</ns0:statusDate>
  <ns0:description>Gecertificeerd vrij</ns0:description>
  <ns0:ubn>123456</ns0:ubn>
  <ns0:animalSpeciesCode>RU</ns0:animalSpeciesCode>
  <ns0:name>gecertificeerd vrij</ns0:name>
  <ns0:ranking>17</ns0:ranking>
  </ns0:IsgrStsResponseTypeUser>
 </result>
</ns0:getPrdStatusResponse>
</env:Body>
</env:Envelope>

Why can't WCF deserialize this response header? I'm getting a "Security header is empty" exception:
Server stack trace:
at System.ServiceModel.Security.ReceiveSecurityHeader.Process(TimeSpan timeout)
at     System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Who knows what is going on here? I've already tried Rick Strahl's suggestion and removed the timestamp from the request header. Any help greatly appreciated!

A: It seems my problem is addressed in the following kb article: http://support.microsoft.com/kb/971493/
Haven't been able to download the fix yet, because no download link seems to be available... Will keep this thread updated.

A: No idea if your specific problem is covered as well, but there are quite some options discussed in this thread.


text:
Q: How to associate the file extension of an Arduino sketch file (.ino file) as a C/C++ file for syntax highlighting? I'd like to use KDevelop as my editor.  How do I tell KDevelop to treat the .ino files as C/C++ files so it does things like syntax highlights and "Jump to Declaration"?
Is there a place to associate file extensions?

A: I take it, you can edit Kate's syntax highlighting file for C++, and add .ino extension to extensions attribute of <language> entity. Let me know if that worked for you, so I'll upstream this.
And BTW, there is a work-in-progress KDevelop plugin for developing for embedded systems. You might find it interesting (if you aren't using it already).

A: Open SystemSettings, go to 'Applications -> File Associations', search for 'x-c++src', and add '*.ino' to the list of filename patterns.
Alternatively, edit /usr/share/mime/text/x-c++src.xml manually, which has the same effect.


text:
Q: How can I simulate click events in jQuery to make a Slide Show advance automaticly I have THIS slideshow. I want it to auto-advance unless someone clicks the navigation elements.
I was thinking about simulating consecutive click events on each link at a certain amount of time (3000 ms, for instance), but my code is ineffective (I'm not so good at JavaScript/jQuery, I admit it). Martin Angelov's nice tutorial, unfortunately does not meet my needs.
Can anyone give a hand please? Thank you!

A: A version adapted from the function in the linked tutorial.  The code could be more condensed, but I tried to make it as clear as possible what's going on.
    (function autoAdvance(index){
    //We use index to keep track of which nav link you should be clicking on.

    //Click on the next nav link
    var allNavLinks = $('#slidernav a'); //This selector gets every anchor that is a descendant of your slidernav list
    var currentNavLink = allNavLinks.get(index);
    currentNavLink.click(); //Simulates a click on your nav link

    // Schedule your next autoAdvance
    var clickNextFn = function(){autoAdvance((index+1)%allNavLinks.length)}; //You need to wrap the callback to autoAdvance in a function so that setTimeout can evaluate it later.
    timeOut = setTimeout(clickNextFn,5000); //Will call the clickNextFn in 5 seconds
})(0); //Start the function by auto clicking on index 0

A: $("#ButtonID").click()

The .click() function simulates a click in jQuery.
Note that this click is not limited to buttons.


text:
Q: Best way to plot a 2d contour plot with a numpy meshgrid i'm looking for the best way to create a contour plot using a numpy meshgrid.
I have excel data in columns simplyfied looking like this:
x data values: -3, -2, -1, 0, 1, 2 ,3, -3, -2, -1, 0, 1, 2, 3
y data values:  1,  1,  1, 1, 1, 1, 1,  2,  2,  2, 2, 2, 2, 2
z data values:  7 , 5,  6, 5, 1, 0, 9,  5,  3,  8, 3, 1, 0, 4

The x and y values define a 2d plane with the length (x-Axis) of 7 values and depth (y-Axis) of 2 values. The z values define the colour at the corresponing points (more or less a z-Axis).
I've tried:
import matplotlib.pyplot as plt
import numpy as np

x = [-3,-2,-1,0,1,2,3]

y = [1,2]

z = [7,5,6,5,1,0,9,5,3,8,3,1,0,4]

x, y = np.meshgrid(x, y)

A = np.array(z)
B = np.reshape(A, (-1, 2))

fig = plt.figure()
ax1 = plt.contourf(x, y, B)

plt.show()

I'm pretty sure i'm not getting how the meshgrid works. Do i have to use the whole List of x and y values for it to work?
How do i create a rectangular 2d plot with the length (x) of 7 and the depth (y) of 2 and the z values defining the shading/colour at the x and y values?
Thanks in advance guys!

A: Try
x_, y_ = np.meshgrid(x, y)
z_grid = np.array(z).reshape(2,7)
fig = plt.figure()
ax1 = plt.contourf(x_,y_,z_grid)
plt.show()

Edit: If you would like to smooth, as per your comment, you can try something like scipy.ndimage.zoom() as described here, i.e., in your case
from scipy import ndimage

z_grid = np.array(z).reshape(2,7)
z_grid_interp = ndimage.zoom(z_grid, 100)
x_, y_ = np.meshgrid(np.linspace(-3,3,z_grid_interp.shape[1]),np.linspace(1,2,z_grid_interp.shape[0]))

and then plot as before:
fig = plt.figure()
ax1 = plt.contourf(x_,y_,z_grid_interp)
plt.show()

A: This is one way where you use the shape of the meshgrid (X or Y) to reshape your z array. You can, moreover, add a color bar using plt.colorbar()
import matplotlib.pyplot as plt
import numpy as np

x = [-3,-2,-1,0,1,2,3]
y = [1,2]
z = np.array([7,5,6,5,1,0,9,5,3,8,3,1,0,4])

X, Y = np.meshgrid(x, y)
print (X.shape, Y.shape)
# (2, 7) (2, 7) Both have same shape
Z = z.reshape(X.shape) # Use either X or Y to define shape

fig = plt.figure()
ax1 = plt.contourf(X, Y, Z)
plt.colorbar(ax1)
plt.show()

A: def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 3 )
y = np.linspace(0, 3, 4)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contour(X, Y, Z, cmap='RdGy');


text:
Q: Mean value on a grouped boxplots in R I want to create grouped boxplots out of my data:
X     variable value
Cat1  Var1     10
Cat2  Var1     8
Cat3  Var1     7
Cat4  Var1     15
Cat1  Var2     4
Cat2  Var2     3
Cat3  Var2     4
Cat4  Var2     1

I was able to retrieve it with:
ggplot() +
    geom_boxplot(aes(x=dataFiltered$X, y=dataFiltered$value, color=dataFiltered$variable))+
    ylim(c(-5, 15))

Right now I want to add additional points which will show average(mean) for each boxplot. I tried:
ggplot() +
    geom_boxplot(aes(x=dataFiltered$X, y=dataFiltered$value, color=dataFiltered$variable))+
    ylim(c(-5, 15))+
    geom_point(stat="identity", aes(x=means$`dataFiltered$X`, y=means$`dataFiltered$value`), col = "red",pch=18)

but it shows 4 values at the same X position (red dots in picture below)
I tried to use facet_wrap but I am not able to correct an error:
ggplot() +
    geom_boxplot(aes(x=dataFiltered$X, y=dataFiltered$value, color=dataFiltered$variable))+
    ylim(c(-5, 15))+
    geom_point(stat="identity", aes(x=means$`dataFiltered$X`, y=means$`dataFiltered$value`), col = "red",pch=18) +
    facet_wrap(~means$`dataFiltered$variable`, scales='free')

Error in layout_base... At least one layer must contain all variables used for facetting.

Is there a way to put a mean value on a grouped boxplots?

A: Try to add a stat_summary() call:
library(dplyr)
library(tidyr)
library(ggplot2)
df <- bind_rows(lapply(c(
  "Cat1  Var1     10",
  "Cat2  Var1     8",
  "Cat3  Var1     7",
  "Cat4  Var1     15",
  "Cat1  Var2     4",
  "Cat2  Var2     3",
  "Cat3  Var2     4",
  "Cat4  Var2     1"), data.frame))
colnames(df) <- "V1"
df2 <- df %>%
        separate(V1, c("X", "variable", "value"), sep="\\s+") %>%
        mutate(value = as.integer(value))

ggplot(df2, aes(x=X, y=value, color=variable)) +
        geom_boxplot()+
        ylim(c(-5, 15)) +
        stat_summary(geom = "point", fun.y = "mean", colour = "red", size = 4)

If you want it for each group, try this:
ggplot(df2, aes(x=X, y=value, color=variable)) +
        geom_boxplot()+
        ylim(c(-5, 15)) +
        stat_summary(geom = "point", aes(group=variable, col=variable),
            fun.y = "mean", size = 4, position=position_dodge(width=0.5))

When there are small sample sizes, these plots can be misleading.


text:
Q: Am I right to call multiple asynchronous methods in a row? During startup, the application I need to get two sets of data, each has its asynchronous method. If I call them one by one, then the second call will pass only after completion of the first.
List<DataOne> DataCollectionOne;
List<DataTwo> DataCollectionTwo;

async void GetDatas()
    {
      if(sameCondOne)
        DataCollectionOne = await GetDataOne();
      if(sameCondTwo)
        DataCollectionTwo = await GetDataTwo();
    }

So I wrapped them in the task calls.
void GetDatas()
    {
      if(sameCondOne)
        Task.Run(() => RunDataOne());
      if(sameCondTwo)
        Task.Run(() => RunDataTwo());
    }

async void RunDataOne()
    {
      DataCollectionOne = await GetDataOne();
    }

async void RunDataTwo()
    {
      DataCollectionTwo = await GetDataTwo();
    }

I am doing right?

A: First of all, you should avoid void returning async methods (Best Practices in Asynchronous Programming).
It is a common practice to suffix async methods with Async (or TaskAsync if Async suffixed methods already exist).
If I understand you correctly, you want to spawn some conditional asynchronous interdependent tasks and wait for  all the tasks to end without having any of them wait for another.
Since you are doing anything with the result of the tasks in the orchestrating method but you need istead some side effects, I would wrap the Get~ methods into Run~  methods like you did.
You could test the condition inside the Run~ methods (either by explicitly testing the condition or having it as a parameter):
async Task RunDataOneAsymc()
{
    if (sameCondOne)
    {
        DataCollectionOne = await GetDataOneAsync();
    }
}

But this would still spawn unnecessary tasks if the condition is false. So, it's better to keep it on the caller side:
async Task RunDataOneAsymc()
{
    DataCollectionOne = await GetDataOneAsync();
}

// ...
if (sameCondOne)
{
    await RunDataOneAsymc();
}

On the orchestating method, you will spawn the tasks if the condition is true and then wait for all of them to complete:
async Task RunAll()
{
    var tasks = new List<Task>();

    if (sameCondOne)
    {
        await RunDataOneAsymc();
    }

    // ...

    if (sameCondN)
    {
        await RunDataNAsymc();
    }

    await Task.WhenAll(tasks);
}

A: No.  You don't need, nor want to spin up a new thread just to be responsible for starting these two asynchronous operations.  Simply start both operations (calling the method is what starts the operation) and don't await either until you've started them both:
var firstTask = GetDataOne();
var secondTask = GetDataTwo();

var firstResult = await firstTask;
var secondResult = await secondTask;

To handle the conditional check just conditionally start the task, and then conditionally assign the result:
Task<T> firstTask = null;
if(shouldGetFirstTask)
    firstTask = GetDataOne();
Task<T> secondTask = null;
if(shouldGetSecondTask)
    secondTask = GetDataTwo();

if(firstTask != null)
    DataCollectionOne = await firstTask;
if(secondTask != null)
    DataCollectionTwo = await secondTask;


text:
Q: UPDATE DB SET ... fills ONE specific VARCHAR with 0 or 1, regardless of the value I set I am running the following query, via php mysqli $con->query($sql);
PHP code:
$sql = 'UPDATE registrations SET '.$update_columns_list.' WHERE registrationkey = "'.$registration['RegistrationKey'].'"';
echo "RESULT: ".$result = $con->query($sql);

Value of $sql in above example:
UPDATE registrations SET referenceid = "4469731" and action = "newregistration" and status = "newregistration" and registrationdatetimegmt = "1363371386" and billingmonth = "2013-03" and accessexpirationdatetimegmt = "1373957999" and returnurl = "https://api.mywebsite.com/login.aspx?siteid=209" and lastmodifieddatetimegmt = "1363371398" and studentkey = "12345-67890-12345-67890" and firstname = "amanda" and lastname = "hemingway" and email = "amandamhemingway@trashymail.com" and phonenumber = "111-111-1111" and city = "city" and state = "ca" and postalcode = "90210" and country = "us" and coursecode = "ABC-406" and coursetitle = "example course title" and courseproductcode = "t3310" WHERE registrationkey = "12345-67890-12345-67890"

Everything seems fine when I run this query (I get a "success" message and the affected row count is just as expected). However, when I look at the affected row in the database via phpMyAdmin, where I continually find either 1 or 0 values in the 'referenceid' column. There are no other scripts affecting this table or database. I have been unable to determine any pattern as to when it places a 0 instead of a 1.
Both referenceid and keyid fields are VARCHAR(100)'s.

A: The update statement you are executing performs boolean operation. It's a behaviour in mysql that I don't like.
The current update statement looks like this:
UPDATE tableName SET col1 = 2 AND col2 = 3

and MySQL server doesn't throw any exceptions because the syntax is permitted and it reads it as:
UPDATE tableName SET col1 = (2 AND (col2 = 3))

If you want to update multiple columns, use , to separate the column not AND.
UPDATE registrations
SET    referenceid = "4469731",
       action = "newregistration", .....

A: When you update you don't add columns with and, rather than with a comma, so your Update should look like:
UPDATE registrations
 SET referenceid = "4469731",
     action = "newregistration",
     status = "newregistration",
     registrationdatetimegmt = "1363371386",
     billingmonth = "2013-03",
     accessexpirationdatetimegmt = "1373957999",
     returnurl = "https://api.mywebsite.com/login.aspx?siteid=209",
     lastmodifieddatetimegmt = "1363371398",
     studentkey = "12345-67890-12345-67890",
     firstname = "amanda",
     lastname = "hemingway",
     email = "amandamhemingway@trashymail.com",
     phonenumber = "111-111-1111",
     city = "city",
     state = "ca",
     postalcode = "90210",
     country = "us",
     coursecode = "ABC-406",
     coursetitle = "example course title",
     courseproductcode = "t3310"
 WHERE registrationkey = "12345-67890-12345-67890"


text:
Q: Node.js: Is there a way to log invisible characters in a string? Is there a way to see invisible characters like whitespace, newlines, and other non-printing characters when you run console.log?
I'm asking this because I'm debugging my code for my program and I noticed when I print the text to the console, it's about 75 length long but then I added an extra console.log to print the length of the text and it said it was 175 length. There are obvious characters that I can't see so I'm wondering what I can do to see these characters.

A: I figured out that if I use encodeURIComponent I can see the invisible characters (sort of?).
In case anyone is wondering this is what it looks like before I used it and after
Before: ffabca9ce1b26dd2a4092e9c0c5eba5c01:4678b1ac28f391cfd08e17e89dcc76e4
After: ffabca9ce1b26dd2a4092e9c0c5eba5c01%3A4678b1ac28f391cfd08e17e89dcc76e4%0A%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00
I'm guessing this has something to go with the TCP connection.


text:
Q: Orchard CMS installation shows setup page without styling I have just installed Orchard CMS for the first time using first the manual option and then the Web Platform Installer option. Both options left me with this ugly screen:

A: So anyway, it turns out that the application pool was set to .Net Framework 4.0 CLASSIC mode. I changed it to Integrated Mode, and now everything is pretty:


text:
Q: How do I get PHP to kill www-data processes? I have a Debian server running apache2/PHP. From this website I can execute many python scripts over time. I want to be able to kill these scripts after a certain amount of time so that they don't pile up. The python scripts are owned by www-data.
I have tried killing the python scripts by storing the PID and the time stamp of execution and then looping through all these to find the ones older than a given time.
for($x = 0; $x < $arraylen; $x++) {
    if ( round(microtime(true)) - $timearray[$x] > 60){
        $command = "kill -9 " .  $pidarray[$x];
        $killme = exec($command);
    }
}

I grab the PID using this:
$PID = shell_exec('/usr/bin/python2.7 /var/www/worker.py ......');

I cannot seem to get PHP to kill these processes. However, if I know the PID of the process I can type this into the terminal which works fine
sudo su www-data
kill "PID of the process"

How do I get PHP to kill one of its own processes?

A: exec("sudo -u <YOURUSER> -S kill $PID");


text:
Q: JSPM bundle fails when use node-sass module I'm triyng to build a module for Jspm using node-sass
but when i try to bundle the package I'll receive this error:
jspm bundle-sfx index

Building the single-file sfx bundle for index...
err  Error: Error loading "npm:node-sass@3.1.2/package.json!github:systemjs/plugin-json@0.1.0" at file:/Users/davide/Learning/JspmNodeSass/jspm_packages/npm/node-sass@3.1.2/package.json
       Error loading "npm:node-sass@3.1.2/package.json!github:systemjs/plugin-json@0.1.0" from "index" at file:/Users/davide/Learning/JspmNodeSass/index.js
       ENOENT, open '/Users/davide/Learning/JspmNodeSass/jspm_packages/npm/node-sass@3.1.2/package.json'

This is the sequence to create from scratch the project and create the error:
mkdir JspmNodeSass
cd JspmNodeSass/
npm init
npm install --save-dev jspm
jspm init
jspm install -save npm:node-sass

create an index.js with the folowing content:
// index.js
var sass = require('node-sass');

..then run
jspm bundle-sfx index


text:
Q: Random forest prediction values Having a dataset like this:
         y     x    size    type    total_neighbours    res
113040  29  1204      15       3                   2      0
66281   52   402       9       3                   3      0
32296   21  1377      35       0                   3      0
48367    3   379     139       0                   4      0
33501    1    66      17       0                   3      0
... ... ... ... ... ... ...
131230  39  1002     439       3                   4      6
131237  40  1301      70       1                   2      1
131673  26  1124     365       1                   2      1
131678  27  1002     629       3                   3      6
131684  28  1301      67       1                   2      1

I would like to use random forest algorithm to predict the value of res column (res column can only take integer values between [0-6])
I'm doing it like this:
labels = np.array(features['res'])
features= features.drop('res', axis = 1)
features = np.array(features)

train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25,
                                                                           random_state = 42)

rf = RandomForestRegressor(n_estimators= 1000, random_state=42)

rf.fit(train_features, train_labels);
predictions = rf.predict(test_features)

The prediction I get are the following:
array([1.045e+00, 4.824e+00, 4.608e+00, 1.200e-01, 5.982e+00, 3.660e-01,
       4.659e+00, 5.239e+00, 5.982e+00, 1.524e+00])

I have no experience on this field so I don't quite understand the predictions.

*

*How do I interpret them?

*Is there any way to limit the predictions to the res column values (integers between [0-6])?

Thanks

A: As @MaxNoe said, I had a misconception about the model. I was using a regression to predict a discrete variable.
RandomForestClassifier is giving the expected output.


text:
Q: WPF: Display notification box when my application is minimized How to implement, using WPF, notifications mechanism similar to what eg. Chrome has?
By which I mean: custom content pop-up, displaying especially when my main application window is minimized.
Things I have tried out so far:

*

*WPF Popup class with StaysOpen property set to true. Seems okay, except that it disappears when I minimize the main window.

*Custom template window: well, it's a window, so it appears as another application window in the taskbar, which I'd like to avoid.


text:
Q: Data transformation from array to multipicklist in salesforce I have a one on one mapping with every field in a custom object to a field in an external system. I have a multipicklist that is mapped to an array of external system, now when the data is passed it errors out with restricted picklist error, how to transform data from array to multi pick list in salesforce

A: Multipickist values are stored in a string that separates each value by a semicolon.  So if you have Apple Orange and Banana all selected as values for a Contact.My_Multi_Picklist__c, they can be saved in the Salesforce field as follows:
Contact.My_Multi_Picklist__c = 'Apple;Orange;Banana';

If you're getting an array of strings and want to convert to a multipicklist value, String.join() should do the trick, using ; as the separator:
List<String> incomingStrArray = new List<String>{'Apple','Orange','Banana'};
Contact.My_Multi_Picklist__c = String.join(incomingStrArray,';');


text:
Q: Sorting an array by their ascending value within the array in JS It's a bit of a tricky situation I'm in, but I have an array like this:
const nums = [32, -3, 62, 8, 121, -231, 62, 13];

and need to replace them by their corresponding ascending index. The above example should yield:
[4, 1, 5, 2, 7, 0, 6, 3]

The solution I've come up with is this: TS Playground
const nums = [32, -3, 62, 8, 121, -231, 62, 13];
const numsCopy = nums.map(e => e);

// Basic sorting
for (let i = 0; i < numsCopy.length; i++) {
    for (let j = 0; j < numsCopy.length; j++) {
        if (numsCopy[i] < numsCopy[j]) {
            let t = numsCopy[j];
            numsCopy[j] = numsCopy[i];
            numsCopy[i] = t;
        }
    }
}

for (let i = 0; i < numsCopy.length; i++) {
    let sortedValue = numsCopy[i];

    nums[nums.indexOf(sortedValue)] = i;
}

Problems arise however when I change nums to include a value nums.length > n >= 0. The call nums.indexOf(...) may return a faulty result, as it may have already sorted an index, even though it exists somewhere in the array.
If you replace nums with these values, -231 will have an index of 2 for some reason...
const nums = [32, -3, 62, 7, 121, -231, 62, 13, 0];

> [5, 1, 6, 3, 8, 2, 7, 4, 0]

Is there a better approach to this problem, or a fix to my solution?

A: You could sort the indices by the value and create a new array with index values a sorted positions.
to get the wanted result call the sorting function again and you get the indices sorted by the index order.

const
    sort = array => [...array.keys()].sort((a, b) => array[a] - array[b]),
    fn = array => sort(sort(array));

console.log(...fn([32, -3, 62, 8, 121, -231, 62, 13])); // 4 1 5 2 7 0 6 3
console.log(...fn([-1, 3, 1, 0, 2, 9, -2, 7])); // 1 5 3 2 4 7 0 6

A: Copy the array, sort its values, get indexOf, and null the value in the sorted copy:

const sortIndicesByValue = array => {
  const sorted = [...array].sort((a, b) => a - b);
  return array.map(e => {
    const i = sorted.indexOf(e);
    sorted[i] = null;
    return i;
  })
}

console.log(...sortIndicesByValue([32, -3, 62, 8, 121, -231, 62, 13]));
console.log(...sortIndicesByValue([-1, 3, 0, 0, 2, 9, -2, 7]));


text:
Q: show(), hide(), vanila Javascript как без jquery сделать show() и hide() у данного примера

   var obj = document.getElementById('add_show');
document.querySelector('#close_add').onclick = function() {
  obj.style.display = 'none';
};
document.querySelector('#add').onclick = function() {
  obj.style.display = 'block';
};
.button {
  display: inline-block;
  background: green;
  border-radius: 2px;
  color: white;
  padding: 7px 11px;
  font-size: 22px;
  cursor: pointer;
}
#add_show {
  position: absolute;
  top: 50px;
  left: 0;
  width: 200px;
  height: 200px;
  background: white;
  border: 1px solid black;
  display: none;
}
#close_add {
  font-size: 25px;
  color: #868686;
  font-weight: 400;
  position: absolute;
  top: 10px;
  left: 8px;
  transform: rotate(45deg);
}

Добавить

+

A:

 var obj = document.getElementById('add_show');
document.querySelector('#close_add').onclick = function(event) {
  event.stopPropagation();
  obj.style.display = 'none';
};
document.querySelector('#add').onclick = function() {
  obj.style.display = 'block';
};
.button {
  display: inline-block;
  background: green;
  border-radius: 2px;
  color: white;
  padding: 7px 11px;
  font-size: 22px;
  cursor: pointer;
}
#add_show {
  position: absolute;
  top: 50px;
  left: 0;
  width: 200px;
  height: 200px;
  background: white;
  border: 1px solid black;
  display: none;
}
#close_add {
  font-size: 25px;
  color: #868686;
  font-weight: 400;
  position: absolute;
  top: 10px;
  left: 8px;
  transform: rotate(45deg);
}

Добавить

+

A: 2 Ошибки:

*

*Не на том элементе показываете.

Было
document.querySelector('#close_add').onclick = function() {
  obj.style.display = 'block';
};

стало
document.querySelector('#add').onclick = function() {
  obj.style.display = 'block';
};

*Не правильная вложенность

Было

Добавить

+

стало

  Добавить

+

Так как при вашей вложенности по клику на крест сработают оба действия.


text:
Q: Deleting unneeded service accounts from gcloud permission denied to owner I have a number of unused service accounts in gcloud that I want to remove.
                          Credentialed Accounts
ACTIVE  ACCOUNT
*       mike@mycompany.com
        tf@mycompany-terraform-admin.iam.gserviceaccount.com
        tf@mycompany-terraform-admin-20190506.iam.gserviceaccount.com
        tf@mycompany-terraform-admin-20190727.iam.gserviceaccount.com
        tf@mycompany-terraform-admin-20190725.iam.gserviceaccount.com
        tf-service@mycompany-terraform-admin-20200422.iam.gserviceaccount.com

However, running
gcloud iam service-accounts delete tf@mycompany-terraform-admin-20190506.iam.gserviceaccount.com

ERROR: (gcloud.iam.service-accounts.delete) PERMISSION_DENIED: Permission  iam.serviceAccounts.delete is required to perform this operation on service account projects/-/serviceAccounts/tf@mycompany-terraform-admin-20190506.iam.gserviceaccount.com.

I am the owner of the account. What more permissions do I need?
Aside: I seem to spend >90% of my time with gcp on permissions instead of actually doing stuff and have not been able to find a clear write-up of this. Anyone knows a good explanation on how to use service-accounts effectively.

A: In order to delete a service account, your permissions must be higher than the editor role (roles/editor) or you must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin).
I suggest that you verify the current account that you are using to make sure that the IAM policies set on it respect the minimum that is required for the actions to be completed successfully.
In regards to the use of Service Accounts, I suggest you consider the following docs:

*

*Understanding Service Accounts; This will give you a detailed, but high level overview of that Service Accounts are, how they work, deletion and recreation of service accounts and best practices.

*Service Account Overview; This is a very general, but well written overview of Service Accounts. It contains an easy to follow and descriptive explination regarding each step that may need to be taken when using service accounts.

*A Hitchhiker's Guide to GCP Service Account Impersonation in Terraform; Adding this here as I noticed that your service accounts were linked to the use of Terraform and many people use Terraform within their projects.

*Managing Service Accounts; This is a very detailed (and thus, long) post explaining how to better manage Service Accounts.

*IAM FAQs; These FAQs, even though very general, they do cover a good chunk of the issues that are to be had with IAM. As Service Accounts are a subset of IAM, I suggest that this be consulted as needed.

I hope that this is helpful. IAM is very big and can take a bit of time to get just right. Keep in mind that once IAM is set up right, you may not need to look at it again.


text:
Q: Conormal Sheaf (Morphisms of Schemes, Stacks Project) The first part of this question refers to Lemma 33.2 from the chapter "Morphisms of Schemes" of the Stacks Project. In particular, if $i: Z \rightarrow X$ is an immersion and $\mathcal{I}$ is the corresponding ideal sheaf, then the conormal sheaf is $C_{Z/X} = i^*(\mathcal{I})$. What i don't see is why $i^*(\mathcal{I}) = i^{-1}(\mathcal{I}/\mathcal{I}^2)$. My efforts: if i apply the definition of the pullback $i^*$ i get
$i^*(\mathcal{I}) = i^{-1} \mathcal{I} \otimes_{i^{-1}O_X} O_Z$. Additionally, i also see that if $R$ is a ring and $I$ some ideal then $I/I^2 = I \times_R R/I$. But i am having trouble combining these two facts to obtain $i^{-1}(\mathcal{I}/\mathcal{I}^2)$.

A: By definition, we have $ i^*(\mathcal{I}) = i^{-1}(\mathcal{I})\otimes _{i^{-1}\mathcal O_X} \mathcal O_Z$.
On the other hand $\mathcal O_Z=i^{-1}(\mathcal O_X/\mathcal I)$, so that
$$ i^*(\mathcal{I}) = i^{-1}(\mathcal{I})\otimes _{i^{-1}\mathcal O_X} i^{-1}(\mathcal O_X/\mathcal I)=i^{-1}[\mathcal I\otimes _{\mathcal O_X} \mathcal O_X/\mathcal I]=i^{-1}[\mathcal I/\mathcal I^2]$$  just as is stated in the Stacks Project.


text:
Q: Can output of an ARM template be used in another template as a reference which is not called as nested? I'm trying to use different templates for creating a NSG and then for a spoke. I don't want to use nested template, instead I want the out of NSG template as resource ID and give reference to spoke template as a parameter. Can this be achieved or is it just the case for nested template also the parameters in the spoke template where NSG resource ID is needed is in a array as I have used copy function.
"outputs": {"resourceID": {
"type": "string",
"value": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]"}}

This output is to be used here
   "subnetsConfiguration": {
        "value": [
            {
                "name": "app-subnet",
                "addressPrefix": "10.112.0.0/20",
                "networkSecurityGroupName": "set the resource ID as a reference here",

A: To get an output value from a linked template, retrieve the property value with syntax like: [reference('deploymentName').outputs.propertyName.value]
First, the linked template- helloworld.json
{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {},
    "variables": {},
    "resources": [],
    "outputs": {
        "greetingMessage": {
            "value": "Hello World",
            "type" : "string"
        }
    }
}

The main template deploys the linked template and gets the returned value -
{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {},
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2020-06-01",
            "name": "linkedTemplate",
            "properties": {
                "mode": "incremental",
                "templateLink": {
                    "uri": "[uri(deployment().properties.templateLink.uri, 'helloworld.json')]",
                    "contentVersion": "1.0.0.0"
                }
            }
        }
    ],
    "outputs": {
        "messageFromLinkedTemplate": {
            "type": "string",
            "value": "[reference('linkedTemplate').outputs.greetingMessage.value]"
        }
    }
}

Please refer this documentation for more details.


text:
Q: Rotating Pictures on Overlay With Map, via Slider. (WP8) My class is making a Windows phone 8 app with many (Nokia) mapping components, I am programming a map with pictures defined on overlays on the map. I have, in my program (C# WP8), a map with the ability to change the heading of the map with a slider; however when the map's heading is changed the overlays with the pictures remain in the same orientation, causing them to be facing in the wrong direction. If anyone knows how to syncronize the rotation of the picutres with the rotation of the map, please spank the solution my way.

A: For rotating the image along with the map, you can add a RotateTransform to the image, and bind its value to the heading of the map. You could do it in code this way:
    myImage.RenderTransformOrigin = new Point(0.5, 0.5);
    var rotateTransform = new RotateTransform();
    Binding myBinding = new Binding("Heading");
    myBinding.Source = myMap;
    BindingOperations.SetBinding(rotateTransform, RotateTransform.AngleProperty, myBinding);
    myIMage.RenderTransform = rotateTransform;


text:
Q: One-dimensional isotropy group in a two-torus
Let $M$ be a real manifold with an action of a two-torus $T^2$. Let $p$ be a point in $M$ and $H_p$ the stabiliser of $p$ in $T^2$. If $\dim H_p = 1$, then $H_p$ is a circle.

I have a topological argument to prove this fact in a specific context, but I came up with a second, more general argument using the exponential map, I would like to double check it or know if it can be improved.
First of all $H_p$ is compact, because it is closed in $T^2$, and Abelian, as a subgroup of an Abelian group. So the claim is that $H_p$ is connected.
Since $H_p$ has dimension one, take a generator $U$ of its Lie algebra. Consider the one-parameter group
$$E := \{ \exp (tU):t \in \mathbb{R}\} \subset T^2.$$
Of course $E \subseteq H_p$. Now the exponential map is known to be surjective on compact and connected groups, so $\exp \colon \mathfrak{t}^2 \to T^2$ is surjective. Then, given $g \in H_p \subset T^2$, there exists $W \in \mathfrak{t}^2$ such that $\exp (W) = g$. Assume $W \not \in \mathbb{R}U$. Then $U$ and $W$ generate $\mathfrak{t}^2$, in particular they commute. Therefore
$$
\exp(W+U)p = \exp(W)\exp(U)p = \exp(W)p = gp = p.
$$
This is equivalent to saying $W+U$ is in the Lie algebra of $H_p$, which is spanned by $U$, and then $W$ is spanned by $U$, contradiction. So $W$ must be in the Lie algebra of $H_p$, namely there is a number $s$ such that $W = sU$, and $g = \exp (W) = \exp (sU) \in E$. This proves $H_p \subseteq E$, which is to say $H_p$ is the image of the line $t \mapsto tU$, which is path-connected and thus connected. But the exponential map is in particular continuous, so $H_p$ is connected. We found that $H_p$ is compact, connected and Abelian, so it is a circle.


text:
Q: Use different databases embedded in Neo4j with Java I am trying to evaluate different datamodels in Neo4j. For that reason I have created two databases which have those different models and saved them in the same directory:
path/to/database/graphModel1
path/to/database/graphModel2

The next step is that I have created an application with java where I can select the datamodel and the query I want to evaluate (there are only a few predefined queries). Depending which model was selected I want to use the instance of the embedded database. At the moment I use the following if-clause to distinguish between them:
if (model.equals("G1")) {
    graph = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH_1);
} else if (model.equals("G2")) {
    graph = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH_2);
}
registerShutdownHook(graph);

But using that snippet of code I got the following exception after I did the first query with model1 and want to compute the same query with model2:
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.StoreLockerLifecycleAdapter@1f1e9b8' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:330)
... 69 more
Caused by: org.neo4j.kernel.StoreLockException: Unable to obtain lock on store lock file: path/to/database/graphModel1/store_lock. Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)
at org.neo4j.kernel.StoreLocker.checkLock(StoreLocker.java:78)
at org.neo4j.kernel.StoreLockerLifecycleAdapter.start(StoreLockerLifecycleAdapter.java:44)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
... 71 more
Caused by: java.io.IOException: Couldn't lock lock file path/to/database/graphModel1/lock because another process already holds the lock.
at org.neo4j.io.fs.FileLock.getLockFileBasedFileLock(FileLock.java:126)
at org.neo4j.io.fs.FileLock.getOsSpecificFileLock(FileLock.java:70)
at org.neo4j.io.fs.DefaultFileSystemAbstraction.tryLock(DefaultFileSystemAbstraction.java:85)
at org.neo4j.kernel.StoreLocker.checkLock(StoreLocker.java:74)
... 73 more

I realized that there are already a store_lock and a lock on the first database but how does this affect starting a second embedded database? Does anyone know how to solve this problem?
Thanks in advance!

A: It is possible that your GraphDatabase instance was not properly shut down - leaving it in a locked state. I see in your code above that you are registering a shutdown hook, but for graphDB not graph. This might explain how the instance was not properly shut down.
If you know there are no other instances pointing to your Neo4j directory you can try manually deleting the graph.db/lock and graph.db/store_lock files and running your code again.

A: There's long term common misunderstanding in the directory structure for (embedded) database storage location. Designers submit "root" DB folder in the API while required to submit child repository folder.
new GraphDatabaseFactory().newEmbeddedDatabase( "path/to/db" ) // wrong
new GraphDatabaseFactory().newEmbeddedDatabase( "path/to/db/repository" ) // correct

For described case, consider to extend paths to created/reused database locations, by "repository" folder (this name could be varied):
path/to/database/graphModel1/repository
path/to/database/graphModel2/repository

When both DB instances start simultaneously, you will see next file system items created:
path/to/database/graphModel1/repository
path/to/database/graphModel1/logs
path/to/database/graphModel1/store_lock

path/to/database/graphModel2/repository
path/to/database/graphModel2/logs
path/to/database/graphModel2/store_lock

As one can see, there are no any "store_lock" conflicts there. Verified with Neo4j version 3.5.17, "embedded" setup.


text:
Q: Instantly show the automatically posted comment when voting to close The recent auto-comment-on-close feature is a good thing; however I wonder if most close voters are aware that their close vote triggers a comment being posted in their name, because they won't see it unless they refresh the page.
I suggest to AJAX-reload the comments or at least auto-refresh the page when the vote triggered a comment.

A: It's a bit jarring to see a comment from you when revisiting a question you've voted to close. Makes you wonder what else you've been doing that you don't really remember.
AJAX-reloading the comments would allow you to see the comment and further edit it to add more information as to why you think it's a dupe, if you so please (I sometimes do that).

A: The auto-generated comment is now loaded via ajax.


text:
Q: Cuál es la implicación de b? Por qué esto no me arroja error:
 <?php

    echo b"Porqué sucede esto";

    ?>

Pero esto sí:
<?php

    echo c"Porqué sucede esto";

    ?>

Como puedo verse solo cambié la 'b' por una 'c' , y ahí si arroja ERROR, por qué?

A: Según el Manual de PHP, b se usa para conversión de tipos binarios.

El forzado (binary) y el soporte del prefijo b fueron añadidos en PHP
  5.2.1

Esto fue introducido porque al parecer en PHP 6 había un proyecto de incluir el manejo de cadenas binarias, el cual parece estar abandonado (ver al final).
Por tanto al hacer:
echo b"Porqué sucede esto";

No da error, porque PHP intenta forzar un binario desde esa cadena.
Es como si hicieras:
 echo (int) "Porqué sucede esto";

Sólo que ahí verías la conversión realizada y se imprimiría 0 en pantalla.
Hubo un intento de declarar este uso como obsoleto, con la intención posterior de eliminarlo del core de PHP, según el reporte: PHP RFC: Binary String Deprecation

En la versión 5.2.1, el prefijo b y el cast (binary) se introdujeron
  para compatibilidad directa con el proyecto PHP-6. Sin embargo, ese
  proyecto nunca llegó a ser y nadie puede decir si alguna vez será el
  enfoque elegido en un posible intento futuro de implementar cadenas
  binarias. Sin embargo, estos son aún aceptados por el escáner de
  idioma, aunque ignorado a partir de entonces.

Y luego dice:

Este RFC pretende despreciar el prefijo, ya que no produce ningún
  efecto en la cadena literal y el molde binario, ya que es lo mismo
  que la conversión de cadena.
La implementación propuesta consiste en lanzar un E_DEPRECATED
  durante la compilación cuando se utiliza el prefijo o el molde. En
  una versión posterior mayor de PHP, el soporte para estos debe ser
  eliminado.
Por último, este RFC también incluye un parche para la documentación
  para eliminar la referencia a este elenco en la página de Conversión
  de Tipos y otro para la especificación del idioma.

No obstante, como ha señalado @Xerif en un comentario, dicho intento fracasó. En el enlace del RFC citado más arriba dice que se requería 2/3 de votos a favor para aprobar este intento, pero no se llegó a dicho consenso (la votación terminó con 19 votos a favor y 13 en contra).
¿El motivo?, no aparecía indicado en ninguna parte. Yo lo he preguntado en el hilo de Github donde se discutía sobre el asunto:

Do you know why this RFC was rejected? And, it can be deprecated in
  PHP 8? Thanks.

Y ha habido la siguiente respuesta una hora después:

you can find the discussion here and more here The RFC itself is found
  here. Given the rejection, it is very unlikely it will get deprecated
  any time soon.

usted puede encontrar la discusión aquí y también aquí. El
  RFC en sí mismo se encuentra aquí. Teniendo en cuenta el
  rechazo, es muy poco probable que sea declarada obsoleta en un futuro
  próximo.


text:
Q: Cannot view CSS error in Internet Explorer 8 I've been trying to track down a problem in Internet Explorer. My client sees the products on a certain page as all stretched out. I can view the problem via http://ipinfo.info/netrenderer/ but not in an actual PC browser with Internet Explorer 8. How can this be tested and then fixed?
This is the page:
  http://maxwellshousedc.com/wordpress/rugs/

A: I can see the problem using IE8. However, when I turned on compatibility mode it went away. Check that you are not running in compatibility mode for this site.


text:
Q: JSF and Richfaces rich:select and f:selectItems how to highlight elements in a list with different colors using JSF and Richfaces

A: You may try using the jQuery odd and even selectors on table row selectors shown in the rich faces docs i.e. .rf-dt-r and apply a different class.
something like:
<script>
$(document).ready(function()
{

  //for table row
  $("tr:even").css("background-color", "#F4F4F8");
  $("tr:odd").css("background-color", "#EFF1F1");
});
</script>

As seen in this page.


text:
Q: Use of \null versus \hbox{} in a table made with the longtable package In this answer, \null is said to be equivalent to \hbox{} and is therefore never needed. The same advice is more or less given here as it's not a user-level macro, which I take to be the same as "don't use it after \begin{document}".
I'm compiling a special calendar (using longtable), where some cells need to be empty. There's simply no entry for them. The original code which I'm borrowing uses \null for the blanks, but I'm wondering if that should be replaced by \hbox{} or if it would instead have any deleterious effects.
Here's an MWE stripped down to the bare bones. I don't know slash don't understand what's going on under the hood so to speak, but at least a Ctrl + F search-and-replace would be a trivial fix. Thanks for your insights.
\documentclass[11pt]{article}

\usepackage{longtable}
\usepackage{multirow,makecell}

\begin{document}

\setlength\LTleft{0pt}
\setlength\LTright{0pt}
\setlength{\tabcolsep}{5pt}
\renewcommand{\arraystretch}{1.4}
\fontsize{8}{9}\selectfont

\begin{longtable}{>{\centering}p{0.025\textwidth}|>{\raggedright}p{0.040\textwidth}|>{\raggedleft}p{0.025\textwidth}|>{\raggedright\arraybackslash}p{0.85\textwidth}}
text & text & text & text \\ %% this looks ugly, it's fine for sample purposes.
\null & \null & \null & text \\ %% this generates empty space as needed.
\hbox{} & \hbox{} & \hbox{} & text %% it appears the same as the above line.

\end{longtable}

\normalsize

\end{document}

A: Since \null is the same as \hbox{}, there can be no difference.
But there's no difference also if you type in nothing at all, which is actually the preferred way.
\documentclass[11pt]{article}

\usepackage{longtable,array}

\begin{document}

\begingroup
\setlength\LTleft{0pt}
\setlength\LTright{0pt plus 1fil}
\setlength{\tabcolsep}{5pt}
\renewcommand{\arraystretch}{1.4}
\fontsize{8}{9}\selectfont

\begin{longtable}{
  >{\centering}p{0.025\textwidth}|
  >{\raggedright}p{0.040\textwidth}|
  >{\raggedleft}p{0.025\textwidth}|
  >{\raggedright\arraybackslash}p{0.7\textwidth}
}
T & T & T & T \\ %% this looks ugly, it's fine for sample purposes.
\null & \null & \null & T \\ %% this generates empty space as needed.
\hbox{} & \hbox{} & \hbox{} & T \\ %% it appears the same as the above line.
T & T & T & T \\ %% this looks ugly, it's fine for sample purposes.
 &  &  & T \\ %% this generates empty space as needed.
 &  &  & T \\%% it appears the same as the above line.
 &  &  & \\ %% this generates empty space as needed.
 &  &  & T \\%% it appears the same as the above line.
\end{longtable}
\endgroup

\end{document}


text:
Q: I have been using firebase in a terminal . I am getting this error when i go for deploying $ firebase deploy

npm ERR! code Z_DATA_ERROR npm ERR! errno -3 npm ERR! invalid distance
  too far back
npm ERR! A complete log of this run can be found in: npm ERR!
  /data/data/com.termux/files/home/.npm/_logs/2018-10-16T05_15_44_149Z-debug.log
Error: An unexpected error has occurred.

Having trouble? Try again or contact support with contents of firebase-debug.log?

A: I solved it , just by downgrading my npm version


text:
Q: Асинхронность при отправке данных Доброго времени суток!
Есть задача:
Делаю API, который принимает список монет и список валют, после чего уходит запрос на сторонний внешний API и получает данные по конвертации монеты в указанные валюты.
Так же, чтобы лишний раз не делать запросы, то я кеширую данные.
Проблема в том, что response уходит до того, как я сформирую данные. Понимаю,что дело в асинхронности, но не могу ее настроить правильно, чтобы работало, как я подразумеваю
код:
      export async function getTickersConvertData (ctx: Koa.Context, next: Koa.Next): Promise<void> {
  const { ticker, currency } = ctx.query
  const tkr: string = ticker.toString()
  const cur: string = currency.toString()

  const arrayTickers = tkr.split(',')

  const data = await arrayTickers.map(async (key) => {
    const cacheKey = `convert${key}`

    let convertsData = cashTickersConvert.get(cacheKey)

    if (!convertsData) {
      const data = await cryptoCompare(key, cur, true)

      if (data) {
        convertsData = data
        cashTickersConvert.set(cacheKey, convertsData, 300)
      } else {
        throw new Error('No data was found')
      }
    }
    return convertsData
  })

  ctx.body = <IObject> {
    response: data,
  }
  await next()
}

Ответ, который приходит :
    {
    "response": [
        {},
        {},
        {}
    ]
}

convertsData:
[
  { ETH: { USD: 3169.01, RUB: 232120.59, EUR: 2703.5 } },
  { BTC: { USD: 46067.83, RUB: 3378079.45, EUR: 39232.63 } },
  { LTC: { USD: 180.98, RUB: 12686.81, EUR: 153.41 } }
]


text:
Q: Xamarin, New activity on itemClick in RecyclerView I'm trying to make Master and Details Application for learning purpose.
In my recyclerview, When I click item I want to start new activity and send data to a new activity.
I was making it in listview examples, but I struggled here.
This is my Adapter
using Android.App;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using System;
using System.Threading;
using System.Collections.Generic;
using Android.Content;
using Newtonsoft.Json;
using Petrolium.DataObjects;
using Petrolium.Utilities;
using Petrolium.Activities;
using Android.Support.V7.Widget;
using Android.Views;
using static Android.Support.V7.Widget.RecyclerView;

namespace Petrolium.Adapters
{
    public class CompanyRecyclerAdapter : RecyclerView.Adapter
    {
        static List<Company> _companies = new List<Company>();
        public CompanyRecyclerAdapter(Context context, List<Company> companies) => _companies = companies;

        public override int ItemCount => _companies.Count;

        private class CompanyViewHolder : ViewHolder
        {
            public ImageView companyImageView
            {
                get;
                set;
            }

            public TextView companyNameView
            {
                get;
                set;
            }

            public CompanyViewHolder(View itemView) : base(itemView)
            {

                companyImageView = itemView.FindViewById<ImageView>(Resource.Id.company_image);
                companyNameView = itemView.FindViewById<TextView>(Resource.Id.company_name);

                itemView.Click += (sender, e) =>
                {
                    var context = itemView.Context;
                    Intent intent = new Intent(context, typeof(DetailsActivity));
                    intent.PutExtra(GetText(Resource.String.DetailsStringToJSON),
                                    JsonConvert.SerializeObject(_companies[e.Position].Fuels));

                    StartActivity(intent);
                };
            }
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            CompanyViewHolder vh = holder as CompanyViewHolder;

            vh.companyImageView.SetImageResource(Resource.Drawable.gulf);
            vh.companyNameView.Text = _companies[position].Name;
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            View itemview = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.Company, parent, false);
            CompanyViewHolder vh = new CompanyViewHolder(itemview);

            return vh;
        }
    }
}

But there isn't GetText method, also e. doesn't have any Position field or property.
Also, there isn't StartActivity method to pass my intent on it.
What is best-practice to make itemClick in recyclerView and start a new activity? How to handle this problem?
I'm the beginner in android development and sorry if I'm asking something simple.

A: Your ViewHolder should be just pass out the click event to the Adapter then back to the Fragment or Activity to handle the event.
public CompanyViewHolder(View itemView, Action<int> listener) : base(itemView)
{
    companyImageView = itemView.FindViewById<ImageView>(Resource.Id.company_image);
    companyNameView = itemView.FindViewById<TextView>(Resource.Id.company_name);

    itemView.Click += (sender, e) => listener (base.LayoutPosition);
}

Then in your adapter should have an event to let Fragment or Activity to bind to:
public class CompanyRecyclerAdapter : RecyclerView.Adapter
{
    public event EventHandler<int> ItemClick;

    void OnClick(int position)
    {
        if (ItemClick != null)
            ItemClick(this, position);
    }

    ...

    public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
    {
        View itemview = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.Company, parent, false);
        CompanyViewHolder vh = new CompanyViewHolder(itemview, OnClick);

        return vh;
    }
}

Then finally in your Fragment or Activity you can bind to the ItemClick event in Adapter to handle it:
mAdapter = new CompanyRecyclerAdapter(mPhotoAlbum);
mAdapter.ItemClick += OnItemClick;


text:
Q: Requirements, Specs, and Managing Up in an Agile Environment My company has tried to adopt the scrum methodology with mixed success.  Theses are some areas where we've had issues.  How do you handle these?

*

*Tracking requirements from
Product Marketing through to product.  We're trying out JIRA to track all requirements individually and assigning a release to each one as it is picked for implementation.

*Who creates stories? Product
Management who doesn't know enough
to create effectively small stories,
developers who may not have domain
knowledge, an analyst in between?

*Functional specs

*

*do you write them or just try to get them into a story
definition?

*Do you write functional
specs per story?  Per feature?

*How do you see the relationship between functional specs and stories?

*answering the question from people
with VP in their title "what are we
going to get by [8 months from
now]?"

A: Let's see if my take adds anything (not certain by any means...)

*

*I'm not sure about the "assigning a release to each one" thing. I thought the idea was to put a "price" on each story/function point/unit of development and pick what goes into the current sprint. Everything else is backlog - you can offer some indication of remaining effort (see evidence based scheduling in FogBugz) but I don't think you should be allocating to specific sprints - you don't know what'll be in the backlog by the time you get there, for one thing. All you know is that it's going to change, so why waste time on it?

*There should be a designated user representative. Or more than one, if domain knowledge can't be concentrated in one individual. But someone from the business domain should be in charge overall of deciding what goes into a sprint, subject to the effort available, of course. There can be a place for a Business Analyst type, but they need to be domain experts. If your user(s) can't write stories, even with your help (it's a co-operative thing, or should be) then you all need help. Consider getting a coach involved for a sprint or two.

*You won't be writing functional specs in an Agile environment. You'll be writing code. Your user will be on hand at all times (or you're already exposed to significant risk) and they're your spec. The story tells you "what", and is going to be a small enough unit of work that you should be able to decide on "how" fairly quickly. And refactor. Always refactor. It's not an overhead, it's part of the process and your design won't evolve satisfactorily without it.

*If you have VPs (hey, I'm a VP, we're not all bad!) who ask that sort of question, then parts of your company are not getting it yet. Choose someone (the person best able to deal with non-techies, perhaps, or maybe the person least able, since they clearly need the practice) to explain it to them. If what's built is important to them, perhaps their questions are an indication that someone's not as involved as they should be.

A: *

*You should translate your requirements into a Product Backlog. This backlog is what you use to decide what Sprint Backlog items are chosen for each Sprint iteration. Management decides what is on the Product Backlog, but the team needs to agree to what they can produce in the Sprint (this is a negotiation that occurs at every sprint).

*Your Product Owner (usually a product manager) drives the creation of the stories. The Stories are simple (as a system admin, I need to be able to add a user). If your product management does not understand your product, you are in trouble.

*Agile is about designing as required. The design is never in the story. The spec can be per story, or per feature. You could design all your CRUD inside of one spec, which covers multiple stories.

*The Product Owner gets a product demo at the end of every Sprint. So value is demonstrated at every cycle. So your VP would get reports on a monthly basis (ususally 3 weeks of dev + 1 week to prepare for the Sprint demo).

A: If you are going to do anything in regards writing or designing code, one of the things you should always do, is write a spec, irrespective of whatever methodology you are using, wether it is Scrum, XP, Agile or SDLC.  Many people who say that writing specs is so unagile and a monument to wasteful bureaucratic paperwork. The simple fact is that they are misguided when they say that code is the spec.
The clear fact is that a spec allows you to formulate your ideas and designs beforehand,  and its much easier to change a spec than it is to change a program, especially if you are working outside the confines of simple LOB application. Specs ensure you have a clearer understanding of what is required when you start coding.
Its been show time and time again that teams that use specs, design better software.
In my opinion, if you hear anybody say the code is the spec, that is dogma, plain and simple, and  is storing up huge maintainability problems for the future.
As an aside, I don't have anything against the Agile Manifesto or light management process centric methods like Scrum. I've used it in the past few years a number of times,
and it delivers. I've also seen good software down the drain, where an agile focus would have saved it. But it is no panacea or silver bullet.


text:
Q: How to make client not disconnect when server response takes a long time I have a Java backend with REST-API and an Angularjs frontend. Users can use the frontend to request information from the backend. When this happens, the backend generates a file on the fly and sends it to the frontend. So far so good.
The problem occurs when users request large amounts of information. This makes generating the file take so long that the frontend times out and aborts the connection.
Is there a way to reassure the client that a response is actually going to come, or increase the timeout limit for this one endpoint only? Alternatively, is there a way for the server to send two responses, one immediately after receiving the request and one after the file is generated?
The API endpoint looks like this:
@Path("download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public Response download() {

    StreamingOutput stream = //stream containing file

    return Response.ok(stream)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"download.xlsx\"")
        .build();
}

The frontend makes the request by doing window.open(download url, '_blank', '') (the content of the file depends on previous input from the user).


text:
Q: How to hide login button on revolution slider once the user loggedin I have a wordpress website in which i have put a login button on the revolution slider. I want the login button hides when the user loggedin to wordpress website. I see there is option in menus to show for loggedin or loggedout users but i don't know how to hide login on revolution slider when the user loggedin

A: You can use jQuery to check if the user is logged in or not. Then, implement your logic to hide the login button from revolution slider.
Check if user is logged in using JQuery
Your jQuery would look something like this:
$('.rev-slider-login-button').hide();


text:
Q: Good and clean way to wait until the file closes
Possible Duplicate:
Wait until file is unlocked in .NET

I have an open file, like a .Doc or .txt, and I have to wait until the user close it.
I already try this, according to Wait until file is unlocked in .NET :
while (true)
{
    try
    {
      using (FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100))
        {
            //the file is close
            break;
        }
    }
    catch (IOException)
    {
        //wait and retry
        Thread.Sleep(1000);
    }
}

This works well ,but it may be possible to find a solution without a try/catch and handler the exception ?

A: For one, though, don't use the loop you have right now, breaking if there's no exception - perform your actual file access in that using loop.
Next, if the file is open in a known process, you could get its Process object, set EnableRaisingEvents to true, and handle its Exited event to try again. It's not failsafe, though, so you would still handle exceptions and use a loop.

A: Unfortunately no, there is no other way.
The API doesn't have an event that will fire when a file in unlocked or anything else that is convenient.
Retrying with waits is the best solution with the current API.

A: You can make P/Invoke calls to native CreateFile function and then analyze error code. However, try/catch will still be necessary.


text:
Q: Why do I get a ssh Permission denied (publickey)? I have two machines on Google compute engine and I want to ssh the other server. Therefore, on the first machine (namenode), I created a passwordless ssh key for user hadoop and did a cat id_rsa.pub >> authorized_keys. On the second machine (datanode1) there is also a user called hadoop. The second machine's hadoop user has an empty ~/.ssh directory.
When I now try to ssh from the first to the second machine I get:
hadoop@namenode:~/.ssh$ ssh -v hadoop@datanode1
OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1e 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to datanode1 [10.240.223.55] port 22.
debug1: Connection established.
debug1: identity file /home/hadoop/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/hadoop/.ssh/id_rsa-cert type -1
debug1: identity file /home/hadoop/.ssh/id_dsa type -1
debug1: identity file /home/hadoop/.ssh/id_dsa-cert type -1
debug1: identity file /home/hadoop/.ssh/id_ecdsa type -1
debug1: identity file /home/hadoop/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.0p1 Debian-4
debug1: match: OpenSSH_6.0p1 Debian-4 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.0p1 Debian-4
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA 10:54:3e:ec:07:58:48:85:28:40:90:43:e1:8f:3d:f0
debug1: Host 'datanode1' is known and matches the ECDSA host key.
debug1: Found key in /home/hadoop/.ssh/known_hosts:1
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/hadoop/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/hadoop/.ssh/id_dsa
debug1: Trying private key: /home/hadoop/.ssh/id_ecdsa
debug1: No more authentication methods to try.
Permission denied (publickey).

I do not understand what is happening here.
UPDATE: I did copy the id_rsa.pub to the authorized_keys file on the destination server. However, now I get the following error:
hadoop@namenode:~/.ssh$ ssh datanode1
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The ECDSA host key for datanode1 has changed,
and the key for the corresponding IP address 10.240.226.88
is unknown. This could either mean that
DNS SPOOFING is happening or the IP address for the host
and its host key have changed at the same time.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
9f:8d:07:09:a9:67:63:b4:b9:2b:f5:39:ed:ef:55:d6.
Please contact your system administrator.
Add correct host key in /home/hadoop/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/hadoop/.ssh/known_hosts:1
ECDSA host key for datanode1 has changed and you have requested strict checking.
Host key verification failed.

Adding "StrictHostKeyChecking=no" to the /etc/ssh/ssh_config repaired this issue.

A: Your SSH public key needs to be copied to the destination server, not the source.

*

*Create your SSH key on the server you will be connecting from

*Cat the ~/.ssh/id_rsa.pub file you just created

*Copy this key to the ~/.ssh/authorized_keys file on the sever you will be connecting to

*Check permissions on ~/.ssh/authorized_keys are set to 0600

*You can also use the ssh-copy-id helper application depending on your OS (I don't have direct experience with Google Compute, so this may not work for you).

A good way (for me at least) of remembering how SSH key authentication works is this:

*

*The computer you're connecting from reads the private key (e.g. ~/.ssh/id_rsa), and generates the public key to forward to the receiving machine.

*The key file (e.g. ~/.ssh/id_rsa.pub) that is generated when creating the key is for information only, and can be re-created/calculated if you have the private key.

*Because of this, your private key should never be shared.

*The ~/.ssh/authorized_keys file is a "white-list" of sorts. It lists all the public key signatures that are allowed to connect to that user's account.

A: i'd suggest you to update the host fingerprint in /home/hadoop/.ssh/known_hosts (or delete the line and re-confirm the host when logging in again) and not disable the StrictHostKeyChecking.
(this assuming that your server doesn't change IP maintaining the DNS)


text:
Q: Proving a group with prime order has to be cyclic and has no nontrivial subgroups I have a question about the proof of some facts. We have a group $G$ and its order is a prime number, let's say $p$. I know this group has to be cyclic and $G$ has no nontrivial subgroups. But how can I prove these facts?

A: You should be familiar with the Lagrange theorem, stating that the order of any subgroup divides the order of the group.
For the second question, by the Lagrange theorem, the order of any subgroup must divide $p$ which is a prime, so the order must be 1 or $p$, so the subgroup is trivial.
To prove that G is cyclic, take any element $g\not=1$. The set $\langle g\rangle=\{g^n:n\in\mathbb{N}\}$ is a subgroup so, by the second question, it must be trivial i.e. $\langle g\rangle=1$ or $\langle g\rangle=G$. But since $g\in \langle g\rangle$ and $g\not=1$ it must be $\langle g\rangle=G$, so g is a generator.


text:
Q: How to make RStudio a default app for Rfiles instead of Notepad? I need your help on something that is considered "easy" but has troubled me some days now.
Some months ago, something changed on my computer and I couldn't open R files with Rstudio (or even R) but only with Notepad and honestly, this has been very tiring lately.
The thing is that when I select RStudio to open the file instead of Notepad, there is NOT the option to "Always open R files with RStudio"
I've also tried to change it through the settings by changing .R files to open with RStudio but the option of .R files doesn't even appear.
Does anyone have any idea of what is going on?
To make it more clear, I simply want to double-click on an R file and instantly open RStudio with the same script.
Thank you all in advance!

A: I'd try right clicking on the file, then NOT clicking on Open with... RStudio. Instead, click on "Choose another app"
example of the menu I'm talking about
What options Windows shows for opening a file is a total mystery; if you don't have that context menu available (I actually don't for .R files, I had to right click on a .PNG to get this screenshot example) then make sure whatever option you are clicking on opens up some dialog to chose the program. If the program is just listed in the context menu, clicking on it won't give you an option to change the association.