text:
Q: Parse a JSON struct as a JSON object in Scala / Spark I store into my MongoDB collection a huge list of JSON strings. For simplicity, I have extracted a sample document into the text file businessResource.json:
{
   "data" : {
        "someBusinessData" : {
            "capacity" : {
                "fuelCapacity" : NumberLong(282)
            },
            "someField" : NumberLong(16),
            "anotherField" : {
                "isImportant" : true,
                "lastDateAndTime" : "2008-01-01T11:11",
                "specialFlag" : "YMA"
            },
   ...
}

My problem: how can I convert the "someBusinessData" into a JSON object using Spark/Scala?
If I do that (for example using json4s or lift-json), I hope I can perform basic operations on them, for example checking them for equality.
Have in mind that this is a rather large JSON object. Creating a case class is not worth it in my case since the only operation I will perform will be some filtering on two fields, comparing documents for equality, and then I will export them again.
This is how I fetch the data:
 val df: DataFrame = (someSparkSession).sqlContext.read.json("src/test/resources/businessResource.json")

 val myData: DataFrame = df.select("data.someBusinessData")
 myData.printSchema

The schema shows:
root
 |-- someBusinessData: struct (nullable = true)
 |    |-- capacity: struct (nullable = true)

Since "someBusinessData" is a structure, I cannot get it as String. When I try to print using
myData.first.getStruct(0), I get a string that contains the values but not the keys: [[[282],16,[true,2008-01-01T11:11,YMA]
Thanks for your help!

A: Instead of using .json use .textFile to read your json file.

*

*Then we convert rdd to dataframe(will have only one string column).

Example:
//read json file as textfile and create df

val df=spark.sparkContext.textFile("<json_file_path>").toDF("str")

//use get_json_object function to traverse json string
df.selectExpr("""get_json_object(str,"$.data.someBusinessData")""").show(false)

//+-----------------------------------------------------------------------------------------------------------------------------------------------------+
//|get_json_object(str,$.data.someBusinessData)                                                                                |
//+-----------------------------------------------------------------------------------------------------------------------------------------------------+
//|{"capacity":{"fuelCapacity":"(282)"},"someField":"(16)","anotherField":{"isImportant":true,"lastDateAndTime":"2008-01-01T11:11","specialFlag":"YMA"}}|
//+-----------------------------------------------------------------------------------------------------------------------------------------------------+

A: In fact, my post containd two questions:

*

*How can I convert the "someBusinessData" into a JSON object using Spark/Scala?

*How can I get the JSON object as a String?

1. Conversion into a JSON object
What I was doing, was already creating a DataFrame that can be navigated as a JSON object:
//read json file as Json and select the needed data
val df: DataFrame = sparkSession.sqlContext.read.json(filePath).select("data.someBusinessData")

If you do .textFile you correctly get the String, but parse the JSON you then need to resort to the answer from Shu.
2. How can I get the JSON object as a String?
Trivially:
    df.toJSON.first


text:
Q: Block reduction in CUDA I am trying to do reduction in CUDA and I am really a newbie. I am currently studying a sample code from NVIDIA.
I guess I am really not sure how to set up the block size and grid size, especially when my input array is larger (512 X 512) than a single block size.
Here is the code.
template <unsigned int blockSize>
__global__ void reduce6(int *g_idata, int *g_odata, unsigned int n)
{
    extern __shared__ int sdata[];
    unsigned int tid = threadIdx.x;
    unsigned int i = blockIdx.x*(blockSize*2) + tid;
    unsigned int gridSize = blockSize*2*gridDim.x;
    sdata[tid] = 0;

    while (i < n)
    {
        sdata[tid] += g_idata[i] + g_idata[i+blockSize];
        i += gridSize;
    }

    __syncthreads();

    if (blockSize >= 512) { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); }
    if (blockSize >= 256) { if (tid < 128) { sdata[tid] += sdata[tid + 128]; } __syncthreads(); }
    if (blockSize >= 128) { if (tid < 64) { sdata[tid] += sdata[tid + 64]; } __syncthreads(); }

    if (tid < 32)
    {
        if (blockSize >= 64) sdata[tid] += sdata[tid + 32];
        if (blockSize >= 32) sdata[tid] += sdata[tid + 16];
        if (blockSize >= 16) sdata[tid] += sdata[tid + 8];
        if (blockSize >= 8) sdata[tid] += sdata[tid + 4];
        if (blockSize >= 4) sdata[tid] += sdata[tid + 2];
        if (blockSize >= 2) sdata[tid] += sdata[tid + 1];
    }

    if (tid == 0) g_odata[blockIdx.x] = sdata[0];
}

However, it seems to me the g_odata[blockIdx.x] saves the partial sums from all blocks, and, if I want to get the final result, I need to sum all the terms within the g_odata[blockIdx.x] array.
I am wondering: is there a kernel to do the whole summation? or am I misunderstanding things here? I would really appreciate if anyone can educate me with this. Thanks very much.

A: In order to have a better idea of this topic, you can have a look on this pdf of NVIDIA that explains, graphically, all the strategies that you have used in your code.

A: Your understanding is correct. The reductions demonstrated here end up with a sequence of block-sums deposited in global memory.
To sum all of these block sums together, requires some form of global synchronization.  You must wait until all the blocks are complete before adding their sums together.  You have a number of options at this point, some of which are:

*

*launch a new kernel after the main kernel to sum the block-sums together

*add the block sums on the host

*use atomics to add the block sums together, at the end of the main kernel

*use a method like threadfence reduction to add the block sums together in the main kernel.

*Use CUDA cooperative groups to place a grid-wide sync in the kernel code.  Sum the block sums after the grid-wide sync (perhaps in one block).

If you search around the CUDA tag you can find examples of all these, and discussions of their pros and cons.  To see how the main kernel you posted is used for a complete reduction, look at the parallel reduction sample code.

A: Robert Crovella has already answered this question, which is mainly about understanding rather than performance.
However, for all those bumping into this question, I just want to highlight that CUB makes block reduction features available. Below, I'm providing a simple worked example on how using CUB's BlockReduce.
#include <cub/cub.cuh>
#include <cuda.h>

#include "Utilities.cuh"

#include <iostream>

#define BLOCKSIZE   32

const int N = 1024;

/**************************/
/* BLOCK REDUCTION KERNEL */
/**************************/
__global__ void sum(const float * __restrict__ indata, float * __restrict__ outdata) {

    unsigned int tid = blockIdx.x * blockDim.x + threadIdx.x;

    // --- Specialize BlockReduce for type float.
    typedef cub::BlockReduce<float, BLOCKSIZE> BlockReduceT;

    // --- Allocate temporary storage in shared memory
    __shared__ typename BlockReduceT::TempStorage temp_storage;

    float result;
    if(tid < N) result = BlockReduceT(temp_storage).Sum(indata[tid]);

    // --- Update block reduction value
    if(threadIdx.x == 0) outdata[blockIdx.x] = result;

    return;
}

/********/
/* MAIN */
/********/
int main() {

    // --- Allocate host side space for
    float *h_data       = (float *)malloc(N * sizeof(float));
    float *h_result     = (float *)malloc((N / BLOCKSIZE) * sizeof(float));

    float *d_data;      gpuErrchk(cudaMalloc(&d_data, N * sizeof(float)));
    float *d_result;    gpuErrchk(cudaMalloc(&d_result, (N / BLOCKSIZE) * sizeof(float)));

    for (int i = 0; i < N; i++) h_data[i] = (float)i;

    gpuErrchk(cudaMemcpy(d_data, h_data, N * sizeof(float), cudaMemcpyHostToDevice));

    sum<<<iDivUp(N, BLOCKSIZE), BLOCKSIZE>>>(d_data, d_result);
    gpuErrchk(cudaPeekAtLastError());
    gpuErrchk(cudaDeviceSynchronize());

    gpuErrchk(cudaMemcpy(h_result, d_result, (N / BLOCKSIZE) * sizeof(float), cudaMemcpyDeviceToHost));

    std::cout << "output: ";
    for(int i = 0; i < (N / BLOCKSIZE); i++) std::cout << h_result[i] << " ";
    std::cout << std::endl;

    gpuErrchk(cudaFree(d_data));
    gpuErrchk(cudaFree(d_result));

    return 0;
}

In this example, an array of length N is created and the result is the sum of 32 consecutive elements. So
result[0] = data[0] + ... + data[31];
result[1] = data[32] + ... + data[63];
....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove white color on highlight bar button In one of my controller i have bar button image as follow (when tapped):

In my other controller it look like:

It always use same image from assets. I need my button to always be 2nd variant.
First (wrong) button declared as follow:
bbiRight = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:riVM.itemPictureName] style:UIBarButtonItemStylePlain target:nil action:nil];

                [RACObserve(((id<CDRRightNavItemProtocol>)self.viewModel), itemPictureName) subscribeNext:^(NSString * x) {
                    [bbiRight setImage:[UIImage imageNamed:x]];
                }];

Second (correct one) is:
 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage: [UIImage imageNamed: @"m_starnotactive"] forState:UIControlStateNormal];
    [btn setImage: [UIImage imageNamed: @"m_staractive"] forState:UIControlStateSelected];
    btn.frame = (CGRect){88,11, 22,22};
    btn.rac_command = self.viewModel.cmdSaveToFavorites;
    RAC(btn, selected) = RACObserve(self.viewModel, inFavorites);

    UIBarButtonItem *bbiFav = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = bbiFav;

Problem is, first case is used in abstract class that used in many classes in my app, how to modify it so my bar button dont look white when selected?

A: You may want to try to use setTitleColor:forState: with UIControlStateHighlighted or UIControlStateSelected to specify the color upon selecting the button.
If your image asset is transparent, you might also want to try to use
imageWithRenderingMode: with UIImageRenderingModeAlwaysTemplate and configure the color using tintColor specifically to your requirements.


text:
Q: Question about a single photon's wave Assume you have a single photon generator in empty space surrounded by a spherical array of many detectors each of which is 10 light seconds from the generator.  A single photon is generated.  I assume that the wave equation would describe a spherical propagation of the wave outward from its source.  If a photon is detected by one element in the detector array, does the wave function instantly collapse?  If a spherical wave is generated, how does the wave on the opposite side of the array instantly "know" the photon has been detected? Does the answer involve quantum entanglement?

A: ("Collaps of the wave function" is a concept in the Copenhagen interpretation of quantum mechanics, so I will stick to that. In other interpretations - such as many-worlds - the explanation would be different, though all results are of course the same)
Yes, the wave function collapses when you measure the particle at one point. This does indeed mean that the wave function on the opposite side immediately "knows" that it isn't there. This does seem to violate special relativity, because this "signal" traveled faster than light. In fact it does not violate anything, because this signal does not carry information from one side to the other (after all, the location where the photon is measured is random). But still, it is quite weird and means that physics is not really "local" in a strong sense. This is called the "EPR paradoxon" (google it. Its quite fascinating).
Usually, the word "entanglement" is used if the states of two (or more) particles are correlated with each other. So this setting with a single photon would not be called entanglement, even though its essentially the same phenomenon. And you can easily get an entangled state out of this setting: If you let the photon be detected by one of the detectors, but you dont look at them (impossible in practice, but fine as a thought experiment). Then the states of the detectors (which are both in a superposition between "I have detected the photon" and "I have not detected the photon) are entangled with each other. This collapses once you look at one of the detectors to see which it is.

A: Wave function collapse is not a physical phenomenon. It does not happen. In this example there is a spherical wave, which describes the probability that photons reach the detectors. If the wave intensity is low and you don't integrate over along time, then it may be that only one photon is detected, with equal probability, by any of the detectors.


text:
Q: $ \lim_{n \to +\infty} \sqrt[n]{\frac{1}{3^n}+\frac{n^5}{5^n}+\frac{1}{2^{nn^{10^{10}}}}}$ Did I do it right? I need to find the limit of this expression:
$$ \lim_{n \to +\infty} \sqrt[n]{\frac{1}{3^n}+\frac{n^5}{5^n}+\frac{1}{2^{nn^{10^{10}}}}} \implies \sqrt[n]{0 + 0 + 0} \implies 0$$
from squeeze theorem (for every $n \geq 2$ : $ n^5 < 5^n$):
$$ 0 \Longleftarrow \frac{n^5}{6^n} \leq \frac{n^5}{5^n} \leq \frac{(n+1)^5}{5^n} \implies 0$$
Every other part seams obvious. Did I do it right?

A: You can't let the argument of the $n$-th root go to infinity while leaving the $n$ in the index of the root fixed, it has to go to infinity too (indeed, it would give you a $0^0$ indeterminate form).
The correct way is notice that
$$\sqrt[n]{\frac{1}{3^n}+\frac{n^5}{5^n}+\frac{1}{2^{nn^{10^{10}}}}}=e^{\frac{1}{n}\log\left(\frac{1}{3^n}+\frac{n^5}{5^n}+\frac{1}{2^{nn^{10^{10}}}}\right)}$$
And the exponent tends to $\log(1/3)$ as $n\to\infty$, to see it you can use the property of log after writing $\log\left(\frac{1}{3^n}+\frac{n^5}{5^n}+\frac{1}{2^{nn^{10^{10}}}}\right)=\log\left(\frac{1}{3^n}\left(1+\frac{3^nn^5}{5^n}+\frac{3^n}{2^{nn^{10^{10}}}}\right)\right)$.


text:
Q: Text-mining with the tm-package - word stemming I am doing some text mining in R with the tm-package. Everything works very smooth. However, one problem occurs after stemming (http://en.wikipedia.org/wiki/Stemming). Obviously, there are some words, which have the same stem, but it is important that they are not "thrown together" (as those words mean different things).
For an example see the 4 texts below. Here you cannnot use "lecturer" or "lecture" ("association" and "associate") interchangeable. However, this is what is done in step 4.
Is there any elegant solution how to implement this for some cases/words manually (e.g. that "lecturer" and "lecture" are kept as two different things)?
texts <- c("i am member of the XYZ association",
"apply for our open associate position",
"xyz memorial lecture takes place on wednesday",
"vote for the most popular lecturer")

# Step 1: Create corpus
corpus <- Corpus(DataframeSource(data.frame(texts)))

# Step 2: Keep a copy of corpus to use later as a dictionary for stem completion
corpus.copy <- corpus

# Step 3: Stem words in the corpus
corpus.temp <- tm_map(corpus, stemDocument, language = "english")

inspect(corpus.temp)

# Step 4: Complete the stems to their original form
corpus.final <- tm_map(corpus.temp, stemCompletion, dictionary = corpus.copy)

inspect(corpus.final)

A: I'm not 100% sure what you're after and don't totally get how tm_map works.  If I understand then the following works.  As I understand you want to supply a list of words that should not be stemmed.  I'm using the qdap package mostly because I'm lazy and it has a function mgsub I like.
Note that I got frustrated with using mgsub and tm_map as it kept throwing an error so I just used lapply instead.
texts <- c("i am member of the XYZ association",
    "apply for our open associate position",
    "xyz memorial lecture takes place on wednesday",
    "vote for the most popular lecturer")

library(tm)
# Step 1: Create corpus
corpus.copy <- corpus <- Corpus(DataframeSource(data.frame(texts)))

library(qdap)
# Step 2: list to retain and indentifier keys
retain <- c("lecturer", "lecture")
replace <- paste(seq_len(length(retain)), "SPECIAL_WORD", sep="_")

# Step 3: sub the words you want to retain with identifier keys
corpus[seq_len(length(corpus))] <- lapply(corpus, mgsub, pattern=retain, replacement=replace)

# Step 4: Stem it
corpus.temp <- tm_map(corpus, stemDocument, language = "english")

# Step 5: reverse -> sub the identifier keys with the words you want to retain
corpus.temp[seq_len(length(corpus.temp))] <- lapply(corpus.temp, mgsub, pattern=replace, replacement=retain)

inspect(corpus)       #inspect the pieces for the folks playing along at home
inspect(corpus.copy)
inspect(corpus.temp)

# Step 6: complete the stem
corpus.final <- tm_map(corpus.temp, stemCompletion, dictionary = corpus.copy)
inspect(corpus.final)

Basically it works by:

*

*subbing out a unique identifier key for the supplied "NO STEM" words (the mgsub)

*then you stem (using stemDocument)

*next you reverse it and sub the identifier keys with the "NO STEM" words (the mgsub)

*last complete the Stem (stemCompletion)

Here's the output:
## >     inspect(corpus.final)
## A corpus with 4 text documents
##
## The metadata consists of 2 tag-value pairs and a data frame
## Available tags are:
##   create_date creator
## Available variables in the data frame are:
##   MetaID
##
## $`1`
## i am member of the XYZ associate
##
## $`2`
##  for our open associate position
##
## $`3`
## xyz memorial lecture takes place on wednesday
##
## $`4`
## vote for the most popular lecturer

A: You can also use the following package for steeming words: https://cran.r-project.org/web/packages/SnowballC/SnowballC.pdf.
You just need to use the function wordStem, passing the vector of words to be stemmed and also the language you are dealing with. To know the exactly language string you need to use, you can refer to the method getStemLanguages, which will return all possible options for it.
Kind Regards


text:
Q: How to silently install Visual Assist X in Visual Studio 2012 with licence If possible, we'd like the option of installing Visual Assist X (latest version) on PC with Visual Studio 2012 silently with the licence key already inserted.
Do you know if this is possible? I don't think Visual Studio 2010 and later supports command modifiers but maybe we could put the licence in the registry somewhere?


text:
Q: AIX auto completion:  how to show a whole file name by type in only a few letters I used to work on Redhat Linux and really enjoy its feature that I can only type a few letters on the command line, and the rest of a file name would show up.  I am running AIX 5 or 6 now, and it does not have this feature.
Do you know if there is a way to turn on this feature in AIX?  Does AIX have this feature at all?
Thanks so much.
Dave

A: AIX does have this feature.
By default, AIX uses korn shell and vi as the editor. Command completion is:
ESC+\
To scroll through command history use:
ESC+k
ESC+j
vi is tricky to use at first, but it puts a whole new spin on the keyboard once you get common functionality down.


text:
Q: Simple string substitution in Makefile I want to replace the string libswscale.so.2 by libswscale.so (variables called $(SLIBNAME_WITH_MAJOR) and $(SLIBNAME), respectively). This is what I tried in the Makefile:
$(SUBDIR)$(SLIBNAME_WITH_MAJOR): $(OBJS) $(SUBDIR)lib$(NAME).ver
    [...]
    @echo SHFLAGS=$(SHFLAGS)
    @echo SLIBNAME_WITH_MAJOR=$(SLIBNAME_WITH_MAJOR)
    @echo SLIBNAME=$(SLIBNAME)
    @echo A $(patsubst $(SLIBNAME_WITH_MAJOR),$(SLIBNAME),$(SHFLAGS))
    @echo B $(SHFLAGS:$(SLIBNAME_WITH_MAJOR)=$(SLIBNAME))
    @echo C $($(SHFLAGS):$(SLIBNAME_WITH_MAJOR)=$(SLIBNAME))
    @echo D $(SHFLAGS:$(SLIBNAME_WITH_MAJOR)=$(SLIBNAME))
    @echo E $(subst $(SLIBNAME_WITH_MAJOR),$(SLIBNAME),$(SHFLAGS))
    @echo F $(subst l,L,$(SHFLAGS))

The output is
SHFLAGS=-shared -Wl,-soname,libswscale.so.2 -Wl,-Bsymbolic -Wl,--version-script,libswscale/libswscale.ver
SLIBNAME_WITH_MAJOR=libswscale.so.2
SLIBNAME=libswscale.so
A -shared -Wl,-soname,libswscale.so.2 -Wl,-Bsymbolic -Wl,--version-script,libswscale/libswscale.ver
B -shared -Wl,-soname,libswscale.so.2 -Wl,-Bsymbolic -Wl,--version-script,libswscale/libswscale.ver
C
D -shared -Wl,-soname,libswscale.so.2 -Wl,-Bsymbolic -Wl,--version-script,libswscale/libswscale.ver
E -shared -Wl,-soname,libswscale.so.2 -Wl,-Bsymbolic -Wl,--version-script,libswscale/libswscale.ver
F -shared -WL,-soname,libswscale.so.2 -WL,-BsymboLic -WL,--version-script,LibswscaLe/LibswscaLe.ver

The last one (F) is especially ridiculous. What is wrong here? Is it because $(SHFLAGS) is made up of variables as well?

A: Found it: $(SHFLAGS) was defined as
SHFLAGS=-shared -Wl,-soname,$$(@F) blablafoo

and using any substitution on it would not work until $$(@F) is actually evaluated (in my case to libswscale.so.2).
I solved it by replacing the variable reference:
@echo $(subst $$(@F),$(SLIBNAME),$(SHFLAGS))

Small hint on assignments: VAR = $(OTHERVAR) is evaluated when used, VAR := $(OTHERVAR) is evaluated immediately.


text:
Q: How to pass to Nginx fastcgi_pass inside ngx_http_lua_module? I need to pass an Nginx variable to my PHP 7.0 backend using the excellent library https://github.com/openresty/lua-nginx-module
I prefer to use content_by_lua_block instead of set_by_lua_block, because the documentation for the 'set' function states "This directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided.".
https://github.com/openresty/lua-nginx-module#set_by_lua
However, since the 'content_...' function is non-blocking, the following code does not return in time, and $hello is unset when passed to PHP:
location ~ \.php{
    set $hello '';

    content_by_lua_block {
        ngx.var.hello = "hello there.";
    }

    fastcgi_param HELLO $hello;
    include fastcgi_params;
    ...
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

The problem is, my Lua code has the potential to be "time consuming code sequences" if certain code paths are taken, using crypto for example.
The following Nginx location works just fine, but that's because set_by_lua_block() is a blocking function call:
location ~ \.php {
    set $hello '';

    set_by_lua_block $hello {
        return "hello there.";
    }

    fastcgi_param HELLO $hello;
    include fastcgi_params;
    ...
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

My question is, what is the best approach here?  Is there a way to call the Nginx directive fastcgi_pass and related directives from within a content_by_lua_block() only after my variables have been set?

A: Yes, it's possible with ngx.location.capture.  Write a separate location block, example:
    location /lua-subrequest-fastcgi {
        internal;   # this location block can only be seen by Nginx subrequests

        # Need to transform the %2F back into '/'.  Do this with set_unescape_uri()
        # Nginx appends '$arg_' to arguments passed to another location block.
        set_unescape_uri $r_uri $arg_r_uri;
        set_unescape_uri $r_hello $arg_hello;

        fastcgi_param HELLO $r_hello;

        try_files $r_uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

Which you can then call thusly:
    location ~ \.php {
        set $hello '';

        content_by_lua_block {
            ngx.var.hello = "hello, friend."

            -- Send the URI from here (index.php) through the args list to the subrequest location.
            -- Pass it from here because the URI in that location will change to "/lua-subrequest-fastcgi"
            local res = ngx.location.capture ("/lua-subrequest-fastcgi", {args = {hello = ngx.var.hello, r_uri = ngx.var.uri}})

            if res.status == ngx.HTTP_OK then
                ngx.say(res.body)
            else
                ngx.say(res.status)
            end
        }
    }


text:
Q: First server in history was used through Usenet, right? For some studying and research pupose, I need to know when the first used server was. I tried to google it, but I only got the first web server in 1990.
I know about ARPA in 1969. But as far as I understand, ARPA network was between computers and there were no servers. Although they used the convetion of server host and user host, still there was no dedicated server. I mean dedicated in a way like high and powerful resouces compared to hosts.
For Usenet in 1981, there were servers. I mean dedicated powerful news servers relativly to users PCs.
If so, can we say that the first used server was in 1981 (Usenet)?

A: On the one hand, definitely not. For Usenet in 1981, there weren't anything like "dedicated powerful news servers".
Usenet itself is older than Internet and possibly older than ARPAnet; initially the news spools were kept on the same computer (e.g. a university's Unix system) that everyone logged in to from their local terminals – the same system that employees or students used for mail, text editing, typesetting, and other stuff; so definitely not a "dedicated server". Programs like rn used to simply access /var/spool/news, and to this day you can have email delivered to /var/spool/mail/$USER.
Also, for a long time dial-up UUCP links were their primary mail & news exchange mechanism, creating a peer-to-peer mesh – the closest thing to "dedicated server" would have been a few popular hosts with a lot of peers, e.g. decvax. "Bang paths" (host!host!…!user) come from UUCP. You can find an old news archive at OldUsenet.

But on the other hand, maybe even earlier than that.
The computers (minicomputers and mainframes) used by companies and universities were already significantly more powerful than the average personal computer of that time, with much more memory and disk space, and possibly hosting several dozen user logins at once – acting as a "terminal server". So maybe you could say that servers were born before networked hosts. (Disclaimer: I haven't checked actual dates of when things happened.)

So I would say that there really isn't a single point in time when someone "invented the server" – I do not know the history well, but it does seem that this sort of thing just gradually evolved.
After all, the first "web server" was merely a NeXT workstation with "do not turn off" written on it. And many people used to run dial-up BBSes off their own PCs, with some more disk space added – those were dedicated, but far from "high and powerful".


text:
Q: Автоматизация тестирования Подскажите, какие программы существуют для записи действий пользователя и последующего их повторения, с возможностью настройки количества тестов, задержек итд и наличием лога?
Сам для этой цели использовал TestComplete, но мне кажется он избыточен для данной задачи, минусом является и что, что он платный.
A: Своими глазами на одной из презентаций видел майкрософтовскую штуку из Team Foundation. Действия пользователя пишутся в лог, плюс, пишется видео с экрана ну и все такие стандартные фичи. Отличительная супер-особенность: в случае падения к багрепорту прикрепляется стек трейс и какие-то ещё дампы, которые позволяют в точности восстановить состояние программы.
Есть возможность записывать наборы действия для автоматического тестирования.

Штука, действительно, очень классная. Но, к сожалению, заметный профит будет только в том случае, если вся разработка ведётся именно в околостудийно среде. Ну и финансовый вопрос, разумеется.
A: Возможно, пригодится:

*

*тестирование пользовательского интерфейса;

*и конкретно, создание записи действий.

A: Если нужно тестировать UI могу посоветовать Sikuli (http://sikuli.org/). Скрипты пишутся на облегченном питоне. Специальная ИДЕ вставляет в код картинки по которым нужно кликнуть/подождать и т.д.
A: Одно из последних решений, стремительно набирающих обороты, Katalon Studio.

*

*Бесплатный.

*Web, mobile, API

*Репозитории объектов, кейвородов, подключение к БД и проч.

*Java, Groovy

Офф.сайт
Документация


text:
Q: How can I tell which version of Android tools is used by IntelliJ if an Android project is not Maven or Gradle-based I'm using IntelliJ IDEA 14.0.2 Ultimate for Android development.  Where in the IDE can I find the version of Android SDK build tools and platform tools it uses to build an Android project that's not a Gradle or Maven project?  (Does that mean IntelliJ is using Ant to build?)

A: Uninstall Gradle and try building the project again from the IntelliJ. If it doesn't work, it's probably using Gradle then, so then type gradle -v or gradle --version from the command line.
If it still works after you've uninstalled Gradle, it's probably using Ant I suppose. If you want to find out more, start the SDK manager from IntelliJ. At the top of the window of your sdk manager should be the path to the Android SDK IntelliJ is using.
Then look in the platform-tools/ folder or the tools/ folder. And type ant -version from the command line if you want to know the version of ant you're using.


text:
Q: List to dictionaty using functional programming in python I want to convert list to dict using rule x if x odd; (x*2, x*3) if x is even using functional programming in python.
Example list([1, 2, 3]) to dict({1:1, 4:2, 6:2, 3:3})
I have a code that converts list to {1: 1, (4, 2): (6, 2), 3: 3}
from itertools import chain
print(
    dict(
        map(
            lambda elem:
            (lambda x: (x, x))(elem) if elem % 2 == 1
            else (lambda x: chain(
                ((x*2, x), (x*3, x))
            ))(elem),
            list([1, 2, 3])
        )
    )
)

Could anyone figure it out?
The result should be the same as this code produces
d = dict()
for x in [1, 2, 3]:
    if x % 2 == 1:
        d[x] = x
    else:
        d[x*2] = x
        d[x*3] = x

A: You can simply use dictionary comprehension:
lst = [1, 2, 3]

out = {k: v for v in lst for k in ((v,) if v % 2 else (v * 2, v * 3))}
print(out)

Prints:
{1: 1, 4: 2, 6: 2, 3: 3}

EDIT: Without for-loops or any libraries:
d = (
    dict(map(lambda x: (x, x), filter(lambda x: x % 2, lst)))
    | dict(map(lambda x: (x * 2, x), filter(lambda x: x % 2 == 0, lst)))
    | dict(map(lambda x: (x * 3, x), filter(lambda x: x % 2 == 0, lst)))
)
print(d)

Prints:
{1: 1, 3: 3, 4: 2, 6: 2}


text:
Q: wp_signon() does not authenticate user guidance needed I use form to send POST request to a page and to login user with wp_signon() in order to authenticate user to my wordpress installation as described in WP documentation:
$creds = array();
$creds['user_login'] = $_POST["user-login"];
$creds['user_password'] = $_POST["user-password"];
$creds['remember'] = true;

$user = wp_signon( $creds, false );

After this little piece of code I'm checking if user was logged in:
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }

But I got FAIL! all the time. Then after sniffing around I found this little trick:
wp_set_current_user( $user );
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }

I've got SUCCESS on this one but when I leave this page I got FAIL again and again.
Can anyone explain me how to login user with wp_signon() without logging her out after page is changed or reloaded or whatever.

I've got desirable result when I go to /wp_admin and login with WP's default login form. I can navigate through every page of my WP site remaining logged-in all the time. But when I try to do this outside the default form I FAIL.
Guide me! PLEASE!

A: finally this is working for me on my local WP installation after replacing - with _ from input  attribute name and using full php start tags <?php instead of <? the final code is here copy and paste into your template.
<?php if ( isset($_POST["user_email"]) && isset($_POST["user_password"]) ) {

$user_login     = esc_attr($_POST["user_email"]);
$user_password  = esc_attr($_POST["user_password"]);
$user_email     = esc_attr($_POST["user_email"]);

$user_data = array(
    'user_login'    =>      $user_login,
    'user_pass'     =>      $user_password,
    'user_email'    =>      $user_email,
    'role'          =>      'student'
);

// Inserting new user to the db
//wp_insert_user( $user_data );

$creds = array();
$creds['user_login'] = $user_login;
$creds['user_password'] = $user_password;
$creds['remember'] = true;

$user = wp_signon( $creds, false );

$userID = $user->ID;

wp_set_current_user( $userID, $user_login );
wp_set_auth_cookie( $userID, true, false );
do_action( 'wp_login', $user_login );

}

if ( is_user_logged_in() ) : echo 'SUCCESS'; ?>

Html for logged in user

<?php else : echo 'FAIL!'; ?>
<form id="user-credentials" method="post" action="<?php the_permalink(); ?>">

<input name="user_email" type="text" placeholder="Email" />

<input name="user_password" type="password" placeholder="Password" />

<input type="submit" class="button blue size-s" value="Submit" />

</form>
<?php endif; ?>

A: If your password includes the # and/or @ characters, you need to urlencode before sending in the form, and then urldecode before setting the credentials in wp_signon.
The url encoding for @ is %40, # is %23 and ! is %21
if your password is mY!p@ssWord# then should be URL encoded before POSTING to mY%21p%40ssWord%23, then URL decoded before setting the credentials for wp_signon


text:
Q: Gradle - include class files from one project in another So I have a multi project setup that looks something like this
Root Project
--> common
--> project1
--> project2
--> 3rd_party_api

So common obviously contains a bunch of code shared across the other projects. Projects 1 and 2 are fine because they are wars and contain the common jar file as a dependency without any issues.
The problem I have is with my 3rd_party_api project. This is quite a small jar file that we will be delivering to other teams so that they can integrate with our code. Most of the java code required is contained in this project folder however there are 3 or 4 classes that are in the common project and need to be included in this library. Because it has to be standalone I need to wrap those classes in the jar file.
I have tried various iterations of srcDirs and source but I can't for the life of me figure out an easy way to do this.
As I've said I've looked at different approaches but my latest attempt looked a bit like this:
project(':api') {
  defaultTasks 'jar'
  apply plugin: 'java'
  sourceSets {
    main {
      java {
        srcDir 'src/main/java'
        srcDir fileTree(dir: '../common/src/main/java').matching { include 'com/my/classes/**' }
      }
    }
    dependencies {
      compile project(':common')
    }
}

This compiles successfully but the extra classes from common are not included in the jar.
Any help would be greatly appreciated.

A: Thanks Dirk,
Didn't quite work for me but got me thinking about other approaches. I eventually got it to do what I needed using a custom jar task. Something like the following:
defaultTasks 'lib'

dependencies {
  compile project(':common')
}

task lib( type: Jar, dependsOn: classes) {
  from sourceSets.main.output
  from (project(':common').sourceSets.main.output) {
    include 'com/myclasses/stuff/**'
    include 'com/specificclass/MyClass.class'
  }
}

A: maybe something like:
jar {
    baseName = 'yourJarFileName'
    from('path/to/your/dir/') {
        include 'local/path/from/there/**/*.jar'
    }
}

didn't checked this ... so don't blame me if it does not work out of the box ;)
other possibility would be to define your custom sourceSets ... but never tried this either.


text:
Q: Reference for LIL for fractional Brownian motion (Cross-posted to https://math.stackexchange.com/questions/2377810/law-of-iterated-logarithm-for-fractional-brownian-motion.)
It seems strange but, even after consulting several books, and hours spent on google, nothing came out about a law of iterated logarithm for the fractional Brownian motion.
I just need a precise reference, on where I can find such a law.
EDIT: My goal is to prove that the fractional Brownian motion of hurst parameter $0<H<1$ has not $H$-Holder continuous trajectories; for the standard BM this can be done in a few lines by exploiting the "standard LIL"; thus, I thought in the fractional case, this can be done in a similar way.
EDIT 2: The law I'm searching for was proved in the 70's, when the expression "fractional Brownian motion" wasn't in use yet; this a reason for which I can't find so much material on the web. Maybe "gaussian process" is better than "fractional BM", as a research advice.
EDIT 3: In the book "Probability and Its Applications" by J. Gani, C.C. Heyde, P. Jagers, T.G. Kurtz, at page 11 holder regularity of fBM is discussed; it's proved that a.s. the $H$-fBM has $\alpha$-Holder continuous trajectories for all $0<\alpha<H$; then when they shows the trajectories are not $H$-Holder, they exploits the following limit
$$
\limsup_{t\to0+}\frac{|B_t^H|}{t^H\sqrt{\log\log(1/t)}}=c_H
$$
where $c_H$ is a "suitable constant"; thus we know that this $\limsup$ is finite and clearly $\ge0$, but can $c_H$ be zero? The reference the authors give is this paper by M. Arcones; I'm looking in it, but till now I didn't found nothing "clean" as the $\limsup$ above.

A: There is formula here (item 3):
https://math.stackexchange.com/a/2417816/21498
and how about that:
Séminaire de Probabilités XLI pp 161-179
Part of the Lecture Notes in Mathematics book series (LNM, volume 1934)
A Law of the Iterated Logarithm for Fractional Brownian Motions
Driss BarakaThomas Mountford

A: This has been proved by S. Orey in this article:
Steven Orey. Growth rate of certain Gaussian processes. Proceedings of the Sixth Berkeley Symposium on Mathematical Statistics and Probability, Vol. II : Probability theory. Berkeley, Calif. : Univ. California Press, 443-451, 1972.
Note that the growth rate is equivalent to the behavior at 0 by time inversion. You can get as well the LIL at any point by increments stationarity.


text:
Q: What is Explicit Project in TFS Reports? I have been trying to generate reports using the Default Reports(Bug Status) in TFS but I don't know what value to give for Explicit Project?
Can anyone help me regarding this?

A: That parameter is supposed to be hidden and automatically populated by the Report Server based on the folder the report is stored in. You seem to have a modified version of the report or your report server is not setup correctly to set the project automatically.


text:
Q: VFS and FS i-node difference What is the difference between VFS i-node and FS (e.g. EXT) i-node?
Is it possible that EXT i-node is persistent (contains/points to data blocks), but VFS i-node is created just in i-node cache after read/use of EXT i-node?
Or the VFS i-node is just an image of FS i-node (it's the same) and i-nodes in those systems, which are not working with i-nodes (e.g. FAT, NTFS) has to be emulated (HOW?) to allow VFS work with those FS like they would support i-nodes?

A: You seem to have answered your questions yourself :)
Let's consider the case of EXT4:
The file system inode is stored on disk in the format as exactly described by struct ext4_inode. The struct ext4_inode_info is just an in-memory representation of the same. The VFS inode also an in-memory object that contains inode information that is common irrespective of the file system type and thus can be abstracted. It is allocated from the inode cache (a memory pool got using the slab allocator).The VFS struct inode is embedded in the filesystem specific in-memory struct inode. For example, struct ext4_inode_info has a member called struct inode vfs_inode. Given a VFS inode, you can get the FS specific inode using the standard container_of macro found in the kernel code. Thus any FS can get to it's own inode struct when it is handed over the generic inode struct by VFS.
Checkout what happens when a new inode is created using __ext4_new_inode()
FAT usually stores the metadata (i.e. inode information) on a directory entry. So the linux fat driver just reads it, populates the necessary fields in memory. Since there's no concept of inodes in FAT, the inode number is a random number- a call to iunique() to be precise.
Some good resources on VFS:
http://www.win.tue.nl/~aeb/linux/lk/lk-8.html
http://lxr.free-electrons.com/source/Documentation/filesystems/vfs.txt


text:
Q: Cannot update systemuser.domainname in CRM In MS Dynamic CRM, I am trying to update systemuser.domainname using web services, but it is invalid for update. How can I do it?

A: According to the documentation this field cannot be updated. The documentation is for CRM 4.0 but I believe this hasn't changed in CRM 2011. There are also some constraints - e.g. domainname has to exist in the Active Directory and must not be used by any other CRM user.
Valid for update = False

I would consider deleting the original user and creating a new one.

A: For on premise CRM system the systemuser.domainname is resolved from Active Directory, once the user is created (this is in case if it is not integrated with Office 365). If this username is not found in AD you cannot create a user in CRM. So, in order to change the domainname through code, you should firstly change change the username in Active.
Check out the the following KB article from Microsoft:
http://support.microsoft.com/kb/930853
In order to change the AD username through code, you can check out the following answer,
How to change login name of user in Active Directory
and then try to change it in CRM through your services.

A: Changing the domainname field of a systemuser record is supported in CRM.
However the new domainname must successfully match to a user record in Active Directory. If it doesn't, CRM will throw and error and not allow the record to be saved.


text:
Q: Hot to use custom CSS with Material UI and NextJS I am try to add some CSS to my components. However, when the website renders the custom CSS is always removed. I am styling my own pages and do not override the CSS of third parties, at least not consciously. I am using Material UI and NextJS and realised that while following  this
that all server-side CSS is removed. I suspect that this is the issue, but not sure how to work around it. The CSS is just custom to the component and follows the naming convention of Next :
[filename].modules.css

Does anyone know what do do?


text:
Q: mysqli_stmt to return a result object When querying using mysqli_stmt::prepare() and execute(), it will not return the result set. But we need to access using the mysqli_stmt:fetch() on the stmt object. There is one function in the php manual called mysqli_stmt::get_result() that will return the result set into a variable we define, but when I use it, it gives me undefined method error. The manual say it is probably in SVC which I am not sure what.
The codes:
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD, DB_NAME);
$stmt =  $conn->stmt_init();
$stmt->prepare("select * from users where u_id = ? ");
$stmt->bind_param('s', $param);
$stmt->execute();

Edit :
I know I can use bind_result() and fetch() function to retrieve the record like :
$stmt->bind_result($column1, $column2, $column3);

while ($stmt->fetch()) {
    echo "Column 1: $column1\n";
    echo "Column 2: $column2\n";
    echo "Column 3: $column3\n";
}

But, my objective is to get the result set (the resource type object) after I execute, something like this:
$result = $stmt->execute();

so I can use the normal mysqli::fetch_object on the result set
$conn->fetch_object($result);

Is there any way to achieve this? thanks
Update:
The get_result function is exactly what I need, but it's not working on my PHP

A: Well, if you do not want to use mysqli_stmt::fetch() but mysqli_result::fetch_*(), I guess it will be a little cumbersome.
http://www.joekolba.com/node/2
Alternatively, use PDO.

A: I have done it in the following way:
$stmt->prepare("select * from users where u_id = ? ");
$stmt->bind_param('s', $param);
$stmt->execute();

$stmt->bind_result($columns['column_name1'], $columns['column_name2'], $columns['column_name3']);

while ($stmt->fetch()) {
  $row = (object) $columns;
}

That comes quite near the FETCH_OBJECT method. You can access all the data of one row via $row->column_name1 etc. Of course you would have to update the associative columns-array, when you alter your table and change names. But it works quite well for me. Didn't want to switch to PDO - considering the fact I switched to MYSQLi just some days ago ;)

A: To enable the method mysqli_stmt::get_result(), you need to use the mysqlnd (MySQL Native Driver) extension: http://php.net/manual/en/book.mysqlnd.php
For some reason, this concrete method is not implemented with the more usual libmysqlclient. In my debian server (and also on my ubuntu desktop) this amounted to run:
sudo apt-get install php5-mysqlnd

A: You need to call bind_result to tell mysqli which variables should hold the columns. Then every time you call fetch, those variables will be automatically filled in, and you can access them like normal. See the code below (not sure if it works, ymmv).
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD, DB_NAME);

if($stmt = $conn->prepare('select * from users where u_id = ?'))
{
    $stmt->bind_param("s", $param);
    $stmt->execute();
    $stmt->bind_result($column1, $column2, $column3);

    while ($stmt->fetch()) {
        echo "Column 1: $column1\n";
        echo "Column 2: $column2\n";
        echo "Column 3: $column3\n";
    }

    $stmt->close();
}


text:
Q: Python - What does it mean for a Class to be callable? I am trying to understand what 'callables' are in Python and what it means for a class to be callable. I was playing with the following code:
class A(object):

    def __init__(self):
        pass

print("Is A callable? " + str(callable(A)))
a=A()
print("created a")
a()

This gives the following result:
Is A callable? True
created a
Traceback (most recent call last):
File "test2.py", line 11, in <module>
a()
TypeError: 'A' object is not callable

Furthermore,
print(type(A.__call__()))

Gives:
<class '__main__.A'>

Does this mean that class A has a __call__ method? and why is it of type class?
is A.__call__() being called each time I instantiate with A()?

A: When a __something__ method of an object is called, something like this happens:

*

*Does the object's class have it? If so, return.

*Does its class's superclass have it? If so, return.

*Does its class's superclass's superclass have it? If so, return.

*...

Note that it never looks at the object's class's class.
Since classes are instances of type (or a subclass of it, see here), classes are callable (type has __call__). However, unless the class also defines __call__, its instances won't have it, because it will never look in the class's class.

A: So, start with the fact that in Python, ordinarily functions are callable, and classes are callable.
Leaving apart the mechanisms that mark functions as callable, Python classes have, as you know, special methods. The method that makes instances of a class callable is __call__. So, if your class has an explicit __call__ method, its instances are callable and  end of story: when you call the instance, it is the __call__ method that is called.
That answers half your question - now let's check what the __call__  method on the class of classes does.
Classes in Python are themselves also first class objects - but they have to be an instance of type. That is, calling type as one calls a class to create an instance, creates a new class. The Python runtime does this automatically when a class body block is met in code.
(but one can also create new classes programmaticaly by explicitly calling type in its three+ parameter form)
As type itself is a subclass of object - its  __new__ method is what it has of special, as it creates a new class, filling up all needed data structures as required by the cPython ABI, allocating memory, and putting values into fields that are not accessible from pure Python codes. As it is the class for any kind of class-object in Python it is called a metaclas. One can derive other classes from type and create custom metaclasses, to run code,r insert attributes, register data and so on at the moment classes are created - but that is optional. Any class created goes through type's __new__.
And when you instantiate a class? I wrote above that what makes an object callable in Python is the presence of a __call__ method in its class. type being the class of all classes, it does feature a __call__ method - and it contains the code needed to orchestrate the call to the class' __new__ and __init__ methods. And that is why classes are callable, and why Python can use the same syntax for function calls and object instantiation.

is A.__call__() being called each time I instantiate with A()?

Not properly - what is called is type(A).__call__. A.__call__ and type(A).__call__ will be the same if there is no explict __call__ method defined in A (then its class, type is searched for __call__. But special methods are not called implicitly by Python by ordinary attribute retrieval: they are always picked from the object's class - and that is made inside the runtime.
You might be confused for the metaclass' call not to be available to the class: that is simply not defined like that in the method retrieval algorithms from Python. When you ask for an attribute or method of an object- including a special method like __call__, the class is searched for the attribute in the form a descriptor (to provide custom attribute access)  - and then the base classes of that class, but not the class of that class. (Also, for special methods, they are only special if they are defined in the object's class itself: being attached directly to an instance have no effect).
The key document where this is all published is the Python's Data Model - it can take some time and experimenting to figure everything out from there, though.


text:
Q: How to get Sentinel logged user to front-end I want to get the sentinel logged user to front-end. In my front-end blade PHP I used Sentinel::check() method. But it return false. When I check the same condition in the controller class it return true. So I want to find out how to get the logged user to front-end.

A: You can get the logged user to all the front-end pages by adding following line of code to boot method in AppServiceProvider.php class.
view()->share( 'loggedUser', Sentinel::getUser() );

After that you can access the Sentinel user from the loggedUser variable in all the front-end classes. Form it you can access all the Sentinel::getUser() related methods from the front-end.


text:
Q: XML Serialization - Leaving part of the XML as an XmlElement I have an object something like this:
public class MyClass {
  public string AValue {get;set;}
  public XmlElement AdditionalConfig {get;set;}
}

I'm generating this from a block of XML that looks like:
<MyClass>
  <AValue>Something</AValue>
  <AdditionalConfig>
    <NewNode Att="Value" />
  </AdditionalConfig>
</MyClass>

If I use the XmlSerializer to de-serialize the XML then the AdditionalConfig XmlElement property is NewNode. Now, if I add a second element in there:
<MyClass>
  <AValue>Something</AValue>
  <AdditionalConfig>
    <NewNode Att="Value" />
    <AnotherNewNode />
  </AdditionalConfig>
</MyClass>

The deserialization doesn't work - it complains about an unrecognised element 'AnotherNewNode'.
I tried making MyClass.AdditionalConfig an array but no luck there. How would I get all the contents of the  node into XmlElement objects?
As always, thanks a lot

A: I'm not sure why that doesn't work.  However, to get the functionality you require, you can instead introduce an AdditionalConfig container class for your additional elements as follows:
public class AdditionalConfig
{
    [XmlAnyAttribute]
    public XmlAttribute[] attributes;
    [XmlAnyElement]
    public XmlElement[] elements;
}

public class MyClass
{
    public string AValue { get; set; }
    public AdditionalConfig AdditionalConfig { get; set; }
}

[XmlAnyElement] when applied to an array of XmlElement or XElement types captures any and all unknown elements in the XML to be deserialized.  Similarly [XmlAnyAttribute], if needed, captures unknown attributes of the <AdditionalConfig> element into an XmlAttribute array.
Prototype fiddle.


text:
Q: Can't run program after compilation with gcc So, i am trying to run a program i wrote in C, in my Samsung Galaxy Tab 2 (in a virtual machine)
it compiles without a problem, the make command runs smoothly but the program itself doesn't run
shell$ ./prot
This gives me the following error:
bash: ./prot: Permission Denied

These are the permissions on the file:
-rw-rw-r-- 1 root sdcard-rw 8609 Mar 20 16:23 prot

What could this be, and how can i overcome this little problem?
PS.: I'm using Ubuntu, this program compiles and runs well on my Mac.
EDIT: See the answer of teppic, it solved my problem.

A: It's very likely that your sdcard is mounted with noexec, which prevents you from executing any files on it. If you look in /etc/fstab, and there's an entry for the sdcard, take out this option. It's also normally possible to remount with the exec option with mount -o remount,exec.
Otherwise, you may be able to copy it somewhere where executables are allowed (e.g. /tmp).

A: You have to have permission for execution, i. e. the x bit set. Try
chmod +x prot

to fix it.

A: Maybe you need admin permission to change it, try:
$> sudo chmod 777 prot


text:
Q: Simulator options won't show in Xcode 6.4 I don't get the option to run my app on a certain simulator or anything. I'm trying to upload my app to iTunes Connect but it won't even let me.

A: Try increasing your screen resolution, or making the Xcode window wider. Then it will reappear.
If you can't do either of those (do to screen resolution constraints), then use the Product menu and then the Destination sub-menu as a workaround.
And by the way, this looks like a duplicate Question #31318316


text:
Q: I Forget to upload screenshots of my iOS universal app I submitted my iOS universal apps binary to apple iTunes appstore, but i forgot to put screen-shots of my app, is it possible to upload now since my app is still in review process its not yet approved.
Any help is thanks in advance.

A: I think you can do it from itunesconnect website.

A: Yes you can add/edit/remove the screenshots at any time from itunesconnect.


text:
Q: Запретить повторную отправку POST Yii2 Для примера есть такой код
public function actionCategory(){
    $this->layout='content';

    $model=Category::find()->all();

    $item=new Category();

    if ($item->load(Yii::$app->request->post())){
        if ($item->save()){
            Notification::widget([
                'type' => 'success',
                'message' => 'Категория добавлена',
            ]);

            return;
        }
    }

    return $this->render('category', ['model'=>$model, 'item'=>$item]);
}

Все работает, но есть одна проблема. Если обновить страницу еще раз - категория снова добавится.
Как убрать повторную отправку POST?

A: Вариантов два.

*

*Подписываете веб-форму (можно почитать у Котерова как он это реализовывал в 2005 году в своей библиотеке)

*После обработки запроса делаете редирект
Второй явно проще, первый бывает достаётся из коробки.


text:
Q: Non-zero homotopy/homology in diffeomorphism groups Let $M$ be a (possibly simply connected) compact manifold $M$. Are there always non-zero classes in the homotopy or homology of $\mathrm{Diff}(M)$ that directly arise from the topology of $M$ itself?
As an example of the type of answers I am looking for I construct non-zero classes in the homotopy and homology of the loop space $\Omega(M)$, which come from the topology of $M$.
Let $M$ be simply connected. Then there is a smallest positive dimension $d$ where $H^d(M)$ is nonzero. Hence $\pi_d(M)\cong H_d(M)$ is non-zero by Hurewicz' Theorem. The long exact sequence in homotopy of the pathspace fibration shows that $\pi_{d-1}(\Omega M)\cong \pi_d(M)$. Applying Hurewicz' Theorem again we see that $H_{d-1}(\Omega M)\cong \pi_{d-1}(\Omega M)\cong \pi_d(M)\cong H_d(M)$. Thus the homology and homotopy have non-trivial elements that come from the topology of $M$.

A: If ${\rm Diff}(M)$ is contractible then the question of course has a negative answer. Examples where this happens are known in dimension three but not in higher dimensions.  For $M$ a closed hyperbolic 3-manifold Gabai proved that ${\rm Diff}(M)$ has contractible components, and it was known earlier that $\pi_0{\rm Diff}(M)$ is isomorphic to the finite group of isometries of $M$ by Mostow rigidity and Waldhausen's work, so one just needs to find hyperbolic manifolds with trivial isometry group. The software package SnapPy should be able to do this. I dimly recall seeing papers giving examples, and perhaps someone can add a comment with a reference.

A: The diffeomorphism groups $\text{Diff}(M)$ are sensitive to stabilization, say replacing $M$ by $M \times [0,1]$, so the direct contribution of the homotopy type of $M$ to $\text{Diff}(M)$ can be obscure.  If you instead look at the concordance = pseudoisotopy spaces $$P(M) = \text{Diff}(M \times [0,1] \ \text{rel}\  M \times \{0\}),$$ then the stabilization maps $P(M) \to P(M \times [0,1])$ get highly connected as the dimension of $M$ grows (by Kiyoshi Igusa's stability theorem), hence the low-dimensional homotopy and (co-)homology of $P(M)$ agrees with that of the stable pseudoisotopy space $$\mathscr{P}(M) = \text{colim}_n P(M \times [0,1]^n).$$  The homotopy type of $M$, being the space of points in $M$, and the homotopy type of the free loop space $\mathscr{L}M = Map(S^1, M)$, being the space of closed loops in $M$, both contribute to $\mathscr{P}(M)$, basically through maps $$\mathscr{P}(*) \times M \to \mathscr{P}(M)$$ and $$\mathscr{P}(S^1) \times \mathscr{L}M \to \mathscr{P}(M).$$  See the paper
https://projecteuclid.org/download/pdf_1/euclid.jdg/1214447541
of Tom Farrell and Lowell Jones.  There is a naturally defined involution on $P(M)$, and by the work of Allen Hatcher, Michael Weiss and Bruce Williams you can use it to largely recover $\text{Diff}(M)$ from $P(M)$.  A more precise statement involves the block diffeomorphism group $\widetilde{\text{Diff}}(M)$, which is quite well understood by surgery theory.  The survey "Automorphisms of manifolds" by Weiss and Williams might be a good source.  By the stable parametrized $h$-cobordism theorem, written up by Friedhelm Waldhausen, Bjørn Jahren and myself, the spaces $\mathscr{P}(*)$ and $\mathscr{P}(S^1)$ are very close to Waldhausen's algebraic $K$-theory spaces $A(*)$ and $A(S^1)$, which agree with the algebraic $K$-theory spaces of the ring spectra $S$ and $S[\mathbb{Z}]$, respectively.  I have some papers on $K(S)$, and Lars Hesselholt has more information about $K(S[\mathbb{Z}])$.  I think this is one of the main reasons to be interested in the algebraic $K$-theory of ring spectra.

A: Here is a very naive approach: choose a basepoint in the manifold (call it $M$). Then evaluation at the basepoint gives a map
$$
\text{Diff}(M) \to M
$$
and so cohomology classes on $M$ pull back to ones on $\text{Diff}(M)$.
If for example,  $M$ admits a nowhere zero vector field, then using the associated flow one can construct a section of the above map, so cohomology classes in $M$ inject into the cohomology of the diffeomorphism group. has the structure of a Lie group, then the above map has a section and the cohomology of $M%$ will inject into the cohomology of the diffeomorphism group via the section.
This would seem to do what your asking, right?
Let me remark that
the general problem constructing non-trivial cohomology classes in the diffeomorphism group is almost 50 years old and has a lot to do with higher algebraic K-theory. The early work of Hatcher and Wagoner, Hsiang et. al., Waldhausen, Igusa, Goodwillie, Weiss and Williams are some of the names that deserve to be cited in this context.


text:
Q: How to configure AWS Chatbot to deliver useful messages from Beanstalk to Slack? We have an Elastic Beanstalk deployment and wanted to receive events into our Slack channel. We setup EventBridge and Chatbot to deliver notifications. Everything works, except the notifications are useless, because Chatbot does not map the message detail only the detail type, which does not tell much. See the attached image of a notification (cropped to cut out the region/account info), the message is not too useful without telling us what was the actual change, which is in the event received by EventBridge and sent to SNS, but not mapped by Chatbot when sending to Slack.

Even their example test notification demonstrates the same problem:

I checked the Chatbot documentation where they claim support for multiple services via EventBridge. I checked EventBridge documentation where they list Elastic Beanstalk among supported services.
I also subscribed and tested Health service notifications, which work just fine. See the example test notification below.

I could not find a way to configure Chatbot to do the right thing. I could write my own message transformer for certain events and call a Slack webhook instead of using Chatbot, but I wanted to avoid writing custom code here for now.
Does anyone know if it is possible to fix Beanstalk notifications that are sent from EventBridge to Chatbot then to Slack? Or is AWS working on supporting more service notifications and in the future this might start working as it should?
Thank you in advance.


text:
Q: Spring 4 + Hibernate 5: No bean named 'transactionManager' is defined I have a problem with my project when I call a URL.
This is my applicationContext
    <context:component-scan base-package="com.prova" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <bean id="dataSource"
        <!-- connection to datasource -->
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.prova.model"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.id.new_generator_mappings">false</prop>
                <prop key="hibernate.cache.use_second_level_cache">false</prop>
                <prop key="hibernate.cache.use_query_cache">false</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager"
        name ="transactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

This is my Controller
package com.prova.controller;
<!-- import -->

@Controller
public class EmployeeController {
    private static final Logger logger = Logger
            .getLogger(EmployeeController.class);

    public EmployeeController() {
        System.out.println("EmployeeController()");
    }

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/all")
    public ModelAndView listEmployee(ModelAndView model) throws IOException {
        List<Employee> listEmployee = employeeService.getAllEmployees();
        model.addObject("listEmployee", listEmployee);
        model.setViewName("home");
        return model;
    }
...
...
...

When I call in postman the url http://localhost:8082/prova/all I receive this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'transactionManager' - neither qualifier match nor bean name match!

Please help me because I try all solutions.
Thanks!


text:
Q: Passing data from RecyclerView.Adapter to fragment onClick I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.
I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?
The Adapter class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {

    private Context context;

    ArrayList<FoodActivity> list;
    public FoodAdapter(ArrayList<FoodActivity> list){
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        holder.foods.setText(list.get(position).getName());
        holder.carbo.setText(list.get(position).getCarbohydrates());
        holder.protein.setText(list.get(position).getProtein());
        holder.fats.setText(list.get(position).getFats());

        //Get items from recyclerview when user clicks them. Then send them to FoodFragment
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String foods = list.get(position).getName();
                String carbo = list.get(position).getCarbohydrates();
                String protein = list.get(position).getProtein();
                String fats = list.get(position).getFats();

                Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView foods, carbo, fats, protein;

        public ViewHolder(View itemView) {
            super(itemView);

            carbo = itemView.findViewById(R.id.carbo);
            protein = itemView.findViewById(R.id.protein);
            fats = itemView.findViewById(R.id.fats);
            foods = itemView.findViewById(R.id.food);
        }
    }
}

The Fragment where the data comes from:
public class TrackingFragment extends Fragment {

    DatabaseReference databaseReference;
    ArrayList<FoodActivity> list;
    RecyclerView recyclerView;
    SearchView searchView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tracking, container, false);

        databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
        recyclerView = view.findViewById(R.id.rv);
        searchView = view.findViewById(R.id.searchFood);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        if(databaseReference != null){
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.exists()){
                        list = new ArrayList<>();
                        for(DataSnapshot ds : dataSnapshot.getChildren()){
                            list.add(ds.getValue(FoodActivity.class));
                        }
                        FoodAdapter adapter = new FoodAdapter(list);
                        recyclerView.setAdapter(adapter);

                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
        if(searchView != null){
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    search(newText);
                    return true;
                }
            });
        }
    }

    private void search(String str){
        ArrayList<FoodActivity> searchList = new ArrayList<>();
        for(FoodActivity object : list){
            if(object.getName().toLowerCase().contains(str.toLowerCase())){
                searchList.add(object);
            }
        }
        FoodAdapter foodAdapter = new FoodAdapter(searchList);
        recyclerView.setAdapter(foodAdapter);
    }

}

And the class where it needs to go:
public class FoodFragment extends Fragment {

    ImageButton addFood;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_food, container, false);

        addFood = view.findViewById(R.id.addFood);

        addFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentTransaction fr = getFragmentManager().beginTransaction();
                fr.replace(R.id.fragment_container, new TrackingFragment());
                fr.addToBackStack(null).commit();
            }
        });

        return view;
    }

}

A: The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:

*

*in activity:
String foods;

public String getFoods() {
    return foods;
}

public void setFoods(String foods) {
    this.foods = foods;
}

*in adapter:
   holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           ((YourActivity)getActivity()).setFoods("Any value");
        }
    });

*in destination fragment:
String foods = ((YourActivity)getActivity()).getFoods();

A: Add an interface to your adapter as follow
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {

interface OnClickListener {
    void onClick(FoodActivity clickedItem);
}

private OnClickListener mCallback;
private ArrayList<FoodActivity> list;

public FoodAdapter(ArrayList<FoodActivity> list){
    this.list = list;
}

public void setOnClickListener(OnClickListener callback) {
    mCallback = callback;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    holder.foods.setText(list.get(position).getName());
    holder.carbo.setText(list.get(position).getCarbohydrates());
    holder.protein.setText(list.get(position).getProtein());
    holder.fats.setText(list.get(position).getFats());

    //Get items from recyclerview when user clicks them. Then send them to FoodFragment
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCallback != null)
                mCallback.onClick(list.get(position));
        }
    });
}

@Override
public int getItemCount() {
    return list.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    TextView foods, carbo, fats, protein;

    public ViewHolder(View itemView) {
        super(itemView);

        carbo = itemView.findViewById(R.id.carbo);
        protein = itemView.findViewById(R.id.protein);
        fats = itemView.findViewById(R.id.fats);
        foods = itemView.findViewById(R.id.food);
    }
}
}

A: Android sometimes is a little complicated, when it involves the full stack:
01 RecyclerView Adapter
/** 01. Some Adapter */
public class SomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private WeakReference<Context> mContext;

    /** Constructor */
    public SomeAdapter(@NonNull Context context) {
        this.mContext = new WeakReference<>(context);
    }

    @NonNull
    protected Context getContext() {
        return this.mContext.get();
    }

    /** Call to Activity from within the adapter. */
    private void someMethod() {
        SomeActivity activity = (SomeActivity) getContext();
        synchronized(activity) {activity.showLoginDialog();}
    }
}

02 AppCompatActivity
/** 02. Some Activity */
public class SomeActivity extends AppCompatActivity {

    @Nullable
    private BaseFragment currentFragment = null;

    /** Constructor */
    public SomeActivity() {}

    public void setCurrentFragment(Fragment fragment) {
        this.currentFragment = fragment;
    }

    /** Call to the current Fragment. */
    public void someMethod() {
        if (currentFragment != null) {
            currentFragment.someMethod();
        }
    }
}

03 Fragment
/** Some Fragment */
public class SomeFragment extends Fragment {

    /** Constructor */
    public SomeFragment() {}

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        ((BaseActivity) context).setCurrentFragment(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        ((BaseActivity) getActivity()).setCurrentFragment(this);
    }
}

A: To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.
To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938


text:
Q: Pictures in tableview change when use search bar I have created a TableView with a cell containing a label and a image. When i don't use the Search Bar everything works fine, But when I use the Search Bar picture 1.png is always showed first. Is it a way to connect the pictures to the labels when using search bar? Thanks for your help
import UIKit

class TableViewController: UITableViewController, UISearchResultsUpdating {

var TitleList = ["101", "121", "122", "131", "132"]
let ImageList = ["1.png", "2.png", "3.png", "4.png", "5.png"]

var filteredfarger = [String]()
var resultSearchController = UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.resultSearchController = UISearchController(searchResultsController: nil)
    self.resultSearchController.searchResultsUpdater = self
    self.resultSearchController.dimsBackgroundDuringPresentation = false
    self.resultSearchController.searchBar.sizeToFit()
    self.tableView.tableHeaderView = self.resultSearchController.searchBar
    self.tableView.reloadData()

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.resultSearchController.active {
        return self.filteredfarger.count
    }
    else {

        return self.TitleList.count
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
    cell.LabelTitle.text = TitleList[indexPath.row]
    cell.CellDescription.text = DescriptionList[indexPath.row]

    let imagename = UIImage(named: ImageList[indexPath.row])
    cell.CellImage.image = imagename

    if self.resultSearchController.active {
        cell.LabelTitle?.text = self.filteredfarger[indexPath.row]
    }
    else {
        cell.LabelTitle?.text = self.TitleList[indexPath.row]
    }

    return cell

}

func updateSearchResultsForSearchController(searchController: UISearchController) {

    self.filteredfarger.removeAll(keepCapacity: false)
    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    let array = (self.TitleList as NSArray).filteredArrayUsingPredicate(searchPredicate)
    self.filteredfarger = array as! [String]
    self.tableView.reloadData()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "DetailView") {
        let VC = segue.destinationViewController as! DetailedViewController
        if let cell = sender as? TableViewCell {
            VC.SentData1 = cell.LabelTitle.text
        }
    }
}

A: When you search, the filtered array will only have the matched titles. There is most likely only one match, so filteredfarger.count is 1.
When cellForRowAtIndexPath is called while searching, you generate the image according to UIImage(named: ImageList[indexPath.row]). Since filteredfarger.count is 1, only 1 row will be created and similarly indexPath.row will be 0. This will result in image 1.png always being referenced from the ImageList array.

A: Here's the example of your code using a dictionary. I haven't checked or compiled this using Xcode but the general ideas are there for you to see.
import UIKit

class TableViewController: UITableViewController, UISearchResultsUpdating {

// This is an array of dictionaries
let images = [["title" : "101", "image" : UIImage(named: "1.png")],
    ["title" : "121", "image" : UIImage(named: "2.png")],
    ["title" : "122", "image" : UIImage(named: "3.png")],
    ["title" : "131", "image" : UIImage(named: "4.png")],
    ["title" : "132", "image" : UIImage(named: "5.png")]]

var filteredImages = [Dictionary]()
var resultSearchController = UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.resultSearchController = UISearchController(searchResultsController: nil)
    self.resultSearchController.searchResultsUpdater = self
    self.resultSearchController.dimsBackgroundDuringPresentation = false
    self.resultSearchController.searchBar.sizeToFit()
    self.tableView.tableHeaderView = self.resultSearchController.searchBar
    self.tableView.reloadData()

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.resultSearchController.active {
        return filteredImages.count
    }
    else {
        return images.count
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell

    if self.resultSearchController.active {
        let image = filteredImages[indexPath.row]
        cell.LabelTitle?.text = image["title"]
        cell.CellImage.image = image["image"]
    }
    else {
        let image = images[indexPath.row]
        cell.LabelTitle?.text = image["title"]
        cell.CellImage.image = image["image"]
    }
    return cell
}

func updateSearchResultsForSearchController(searchController: UISearchController) {
    filteredImages.removeAll(keepCapacity: false)
    for imageDictionary in images {
         if imageDictionary["title"] == searchController.searchBar.text! {
             filteredImages += imageDictionary
         }
    }
    self.tableView.reloadData()
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "DetailView") {
        let VC = segue.destinationViewController as! DetailedViewController
        if let cell = sender as? TableViewCell {
            VC.SentData1 = cell.LabelTitle.text
        }
    }
}

A: this will work
cell.TitleLabel.text = titleList[indexPath.row]
        cell.DescriptionLabel.text = DescriptionList[indexPath.row]
    let imagename =  UIImage(named: ImageList[indexPath.row])
    cell.imageView?.image = imagename
    return cell


text:
Q: Storing messages in new conversation collections; MongoDB I'm a student working on a chat application for my internship, where I use socket.io.
Right now I am busy thinking of a good way to store the messages send in conversations.
As of now I do the following:

*

*For each conversation between one user and another user, a new collection is made.

*On every message sent, the message is stored in the according conversation collection in a single document.

The collections:

Where the document looks as follows:

Now I wonder if there is a good argument to be made to have just one collection "conversations", and store all the messages in multiple documents, where each conversation is a new document.

A: Creating a new collection for every message is very bad idea instead of that you use a simple schema as given below to store your messages
const conversation_schema = new Schema({
  from: {
    type: ObjectID,
    ref: 'User'
  },
  to: {
    type: ObjectID,
    ref: 'User'
  },
  messageBody: {  // body of the message(text body/ image blob/ video blob)
    type: String,
  },
  messageType: { // type of the message(text, mp3, mp4, etc...)
    type: String,
  },
  read: { // to boolean flag to mark whether the to user has read the message
    type: Boolean,
    default: false,
  },
  createdAt: { // when was this message goit created
    type: Date,
    default: new Date(),
  },
});

you can fetch the conversation between the two users using the following query
conversations.find({
      $or: [
       {from: 'user1', TO: 'user2},
       {from: 'user2', TO: 'user1},
      ],
    }).populate({ path: 'to', model: User })
      .populate({ path: 'from', model: User })
      .sort({ createdAt: -1 })


text:
Q: cx_freeze and openssl error after compilation I have a PySide program that uses pyOpenSSL to do a certificate check, I compile it with Cx_Freeze and whenever I try to open it after compiling it I get the following error:

I'm using pyOpenSSL 0.14, Cx_Freeze 4.3.3 and PySide 1.2.2.
Why am I getting the exception?

A: Reposting from the mailing list: Adding cryptography to packages in the setup.py file fixed this issue. The cryptography package loads some submodules using __import__(), which prevents cx_Freeze from automatically finding what modules are needed. Putting it in packages makes cx_Freeze copy all submodules.


text:
Q: position vectors The line $L$ passes through a point with position vector $5\vec{k}$ and is parallel to the vector $a\vec{i}+b\vec{j}+c\vec{k}$ where $a$,$b$ and $c$  are positive integers. The shortest distance between $L$ and the line $r=u\vec{j}$ is 4 units where $h$ and $u$ are real numbers. find one possible set of values of $a$, $b$ and $c$.

A: the vector equation  for L is < 0 ,0, 5 > + t < a , b, c > = < 0,0,5> + t P;
the point (0,u,0) is on the line r , let Q = < 0 , u , - 5 > be the vector that goes from r to L ; then [ P x Q x P ] is orthogonal to both L and r...using the dot product we have
4 | P x Q x P | = [ P x Q x P ] dot Q...this will yield relationships involving a , b , c


text:
Q: How to use ElasticSearch API in Android Can anyone explain how can I use the ElasticSearch API in Android.
Does anyone successfully integrated the api in android?
I added following dependencies in Gradle:
compile 'org.elasticsearch.client:transport:5.2.1'

Of course I run into issues:

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
  com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE
      File1: C:\Users\dude.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpcore-nio\4.4.5\f4be009e7505f6ceddf21e7960c759f413f15056\httpcore-nio-4.4.5.jar
      File2: C:\Users\dude.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpasyncclient\4.1.2\95aa3e6fb520191a0970a73cf09f62948ee614be\httpasyncclient-4.1.2.jar
      File3: C:\Users\dude.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.dataformat\jackson-dataformat-yaml\2.8.6\8bd44d50f9a6cdff9c7578ea39d524eb519e35ab\jackson-dataformat-yaml-2.8.6.jar
      File4: C:\Users\dude.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpcore\4.4.5\e7501a1b34325abb00d17dde96150604a0658b54\httpcore-4.4.5.jar
      File5: C:\Users\dude.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-core\2.8.6\2ef7b1cc34de149600f5e75bc2d5bf40de894e60\jackson-core-2.8.6.jar

.
UPDATE 1:
Well I have to use the REST API using Android Asynchronous Http Client, because adding packagingOptions does not solve the issue

A: Ok so I found out how to access a REST API from Android using a library.
Check out more details on Android Asynchronous Http Client and Github.
First add the permission into the manifest
<uses-permission android:name="android.permission.INTERNET" />

In gradle add:
compile 'com.loopj.android:android-async-http:1.4.9'

Now you can start implementing the REST API like this:
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

public class ElasticRestClient {

    private static final String BASE_URL = "http://httpbin.org/"; //http://localhost:9200/
    private static final String CLASS_NAME = ElasticRestClient.class.getSimpleName();

    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }

    public void getHttpRequest() {
        try {

            ElasticRestClient.get("get", null, new JsonHttpResponseHandler() { // instead of 'get' use twitter/tweet/1
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    // If the response is JSONObject instead of expected JSONArray
                    Log.i(CLASS_NAME, "onSuccess: " + response.toString());
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    Log.i(CLASS_NAME, "onSuccess: " + response.toString());
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                    Log.e(CLASS_NAME, "onFailure");
                    // called when response HTTP status is "4XX" (eg. 401, 403, 404)
                }

                @Override
                public void onRetry(int retryNo) {
                    Log.i(CLASS_NAME, "onRetry " + retryNo);
                    // called when request is retried
                }
            });
        }
        catch (Exception e){
            Log.e(CLASS_NAME, e.getLocalizedMessage());
        }
    }
}

A: I faced exactly the same issue when I tried to add the ES rest client in gradle:
compile 'org.elasticsearch.client:rest:5.4.0'

I finally resolved it by adding these lines at the top of my build.gradle file:
android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}

The lines above simply remove all duplicated dependencies. And after doing it, you can refer to the ES documentation for querying your data.


text:
Q: error while using springloaded in jboss startup I am using springloaded agent in jboss and it is giving me error in startup. Error is related to logmanager and desvribed in https://github.com/spring-projects/spring-loaded/issues/94. I am able to resolve this issue after making following changes in standalone.conf
JBOSS_LOG_MANAGER_LIB="$(echo $JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-*.jar)" # resolve logmanager jar

JAVA_OPTS="$JAVA_OPTS -Xbootclasspath/p:$JBOSS_LOG_MANAGER_LIB  -Djboss.modules.system.pkgs=org.jboss.byteman,org.jboss.logmanager,org.springsource  -Djava.util.logging.manager=org.jboss.logmanager.LogManager" # register jboss logmanager at jvm early startup

Is there a way i can relocate package in springloaded jar using maven shaded plugin so that there will be no more additional settings required.
I have tried relocating java.util.Logger but nothing works.
Is there any other way i can make some changes in spring loaded to avoid this custom settings for jboss.

A: No I don't think you have any other option as JbossLogManager has to be registered as the LogManager.
You might try  "-Dorg.wildfly.logging.skipLogManagerCheck" option, but I'm not sure this would be sufficient.


text:
Q: Suppress _id on MongoDB I am learning MongoDB with this tutorial https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and running the tests on the v3.4.11.
I am having issues with the following exercise which is supposed to show all the documents in the collection but without the _id field:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers").find({}, { _id: 0 }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

But what I get is the full list with all the fields:
[ { _id: 5a734e6e77a6510d2193b4df,
    name: 'Company Inc',
    address: 'Highway 37' },
  { _id: 5a734e8e7c3e9a0d35a604c3,
    name: 'John',
    address: 'Highway 71' },
  { _id: 5a734e8e7c3e9a0d35a604c4,
    name: 'Peter',
    address: 'Lowstreet 4' },
  { _id: 5a734e8e7c3e9a0d35a604c5,
    name: 'Amy',
    address: 'Apple st 652' },
  { _id: 5a734e8e7c3e9a0d35a604c6,
    name: 'Hannah',
    address: 'Mountain 21' },
  { _id: 5a734e8e7c3e9a0d35a604c7,
    name: 'Michael',
    address: 'Valley 345' },
  { _id: 5a734e8e7c3e9a0d35a604c8,
    name: 'Sandy',
    address: 'Ocean blvd 2' },
  { _id: 5a734e8e7c3e9a0d35a604c9,
    name: 'Betty',
    address: 'Green Grass 1' },
  { _id: 5a734e8e7c3e9a0d35a604ca,
    name: 'Richard',
    address: 'Sky st 331' },
  { _id: 5a734e8e7c3e9a0d35a604cb,
    name: 'Susan',
    address: 'One way 98' },
  { _id: 5a734e8e7c3e9a0d35a604cc,
    name: 'Vicky',
    address: 'Yellow Garden 2' },
  { _id: 5a734e8e7c3e9a0d35a604cd,
    name: 'Ben',
    address: 'Park Lane 38' },
  { _id: 5a734e8e7c3e9a0d35a604ce,
    name: 'William',
    address: 'Central st 954' },
  { _id: 5a734e8e7c3e9a0d35a604cf,
    name: 'Chuck',
    address: 'Main Road 989' },
  { _id: 5a734e8e7c3e9a0d35a604d0,
    name: 'Viola',
    address: 'Sideway 1633' } ]

Does anyone know what am I doing wrong?

A: You have to put projections in a nested projection property in the options parameter of find.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers")
  .find({}, { projection: { _id: 0 } })
  .toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

The node mongodb driver is slightly different than just using mongodb shell syntax, so make sure you're looking up the node mongodb driver docs, specific to your version. https://mongodb.github.io/node-mongodb-native/


text:
Q: binary diff library for Java There are several questions about text-diff libraries for Java on SO, but none about binary diff. So here I go:
I'm looking for a binary diff library, implemented in Java. I found javaxdelta and GNU Diff port but I wonder if there are some other hidden gems out there? And, maybe someone has experience with above mentioned libraries? A comparison would be super helpful.
Finally, maybe it is helpful to know that I want to diff objects serialized with Avro.

A: I've found a new (as far as I can tell) Java implementation of a binary diff: JBDiff

A: If you want to compare Avro Files, have a look at Avro Editor, it contains a compare utility for Avro serialised Files.

A: Your question isn't specific enough to get a good answer.  What do you mean by "binary diff"?
If you want to see a list of all the differences between one byte array and another, you can implement or use the xdelta algorithm.  You could also convert the file to hex using the od command and use the standard patch/diff command if you would rather write a shell script than C.
However, it sounds like you want to do something specific to Avro.  Is that true?
If you just want to compare the field values of two different Avro files and generate a diff, and you're already familiar with Avro, all you would need to do is write a program that reads both files and prints out the differences in a way that you can read in later to transform the original.


text:
Q: What is the name of this digraph created from other digraphs? Let $D_1, D_2, ..., D_n$ be digraphs of various sizes and let $C$ be a diagraph with $n$ vertices $\{1,...,n\}$. Construct a new digraph, $D$, whose vertex set is $V(D) = V(D_1) \cup \cdots \cup V(D_n)$ and whose edge set is defined by $u \to v$ if and only if one of the two conditions hold:
$\quad$(a) $u,v \in V(D_i) \text{ and } u \to v \text{ in } D_i$
$\quad$(b) $\exists i \neq j$ such that $u \in V(D_i), v\in V(D_j)\text{ and } i \to j \text{ in } C$.
In other words, $D$ is the digraph obtained by replacing the vertices of $C$ with the diagraphs $D_1,D_2,...,D_n$.
Question: Is there a canonical name/notation for this process? I was digging through the Wikipedia article Graph operations to find something similar, but to no avail (perhaps I just missed it). In particular, I'm interested in when $D_1, D_2, ..., D_n$ are strongly connected and $C$ is transitive. Then the condensation of $D$ is $C$. My idea is to "reverse" the process of condensation.

A: This can be phrased as a "partial graph join" (the graph join is a well-known operation) described by $C$. Indeed, suppose $C$ has the edge $1 \to 2$. Then $D$ has an edge $u \to v$ if $u \in D_1$ and $v \in D_2$; i.e., join all vertices of $D_1$ to vertices of $D_2$, respecting the orientation $1 \to 2$.
Thus the adjacency matrix $A$ of $D$ will be of the following block form, writing $IJ$ for the $ij$th block of the adjacency matrix, $A_i$ for the adjacency matrix of $D_i$, $\mathbf{1}$ for the all-ones matrix, and $\mathbf{0}$ for the all-zeroes matrix:
$$(A)_{IJ} = \begin{cases} A_i &\text{if } I = J = i \\ \mathbf{1} &\text{if } I \to J \in C\\ \mathbf{0} &\text{else }\end{cases}$$
Based off a comment, if we denote the graph join as $G \leftrightarrow H$, then one can extend this by induction to $\leftrightarrow_{j=1}^n G_j$, which is clearly associative. Then if we index the graph created by the procedure in the question as $C(D_1,\dots,D_n)$ one can see why I thought "partial" graph join was a suitable name; on the underlying graphs $G_i$ of the $D_i$:
$$K_n(G_1,\dots G_n) = \hphantom{ }\leftrightarrow_{j=1}^n G_j$$
It is also partial in the sense that this algorithm acts on digraphs, which could be considered "partial graphs" insofar as we can identify (nonloop) $2$-cycles with edges.

A: I finally found a canonical name for this process in this article: Hamiltonian tournaments with the least number of $3$-cycles. The author calls $D = C(D_1,D_2,...,D_n)$ the composition of the $n$ components $M_1,M_2,...,M_n$ with the quotient $C$.


text:
Q: Using Like T SQL Statement to search and replace quotation marks Because the quotation mark is a special character is there a way to replace all quotation with nothing
Original Query
Update table X
Set mycolumn = Replace(mycolumn,''','')
Where mycolumn like '%'%'

Error

(Incorrect SQL Syntax - Unclosed quotation mark after the character string ''')

A: Escape the single quote ' by doubling ''
Update table X
Set mycolumn = Replace(mycolumn,'''','')

you don't need the superfluous WHERE clause.

A: You need to escape the ' by doubling it:
Update table X
Set mycolumn = Replace(mycolumn,'''','')
Where mycolumn like '%''%'

Though the Where clause is probably redundant.

A: Hmm - not entirely sure what you are up to, but you could try the QuoteName string function.