问:
Why use shm_open?
What's the advantage of doing: shm_open followed a mmap?

Why not create a regular file, and then pass that fd to mmap?

I can't see the advantage of shm_open - these are just references, are they not?

I've read the man of the whole family. It seems to me, that the "secret" is in the mmaping action - the file "type" seems to be meaningless.

Any pointers will be good, especially with performance account.

My context is a (cyclic over-writable) buffer (say 128MB) that will be constantly written to be one process, and constantly dumped from by another.

As an example: what's wrong with this open/mmap approach.

EDIT

To be precise, is one of the following better than the other:

```<code>fd = open("/dev/shm/myshm.file", O_CREAT|O_RDWR, S_IRUSR | S_IWUSR);
mem = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
</code>```

vs.

```<code>fd = shm_open("/myshm.file", O_RDWR|O_CREATE, S_IRUSR | S_IWUSR);
mem = mmap(...same as before...);
</code>```

When I created a file with regular open under the /dev/shm fs, and dumped a Gig of garbage to it, my available memory went down by 1G, and my avaiable disk space remained the same.

What's the difference between the two methods?

答:
Both calls are essentially equivalent on modern Linux
 - 1st approach could be used to access POSIX shared memory from languages like go (see https://github.com/fabiokung/shm/blob/master/shm_linux.go) where POSIX shared memory not natively available - it might be different for other OS/version where 1st call would lead to some file  creation or /dev/shm just not available and/or possibly slower performance. Rules of path merging might also be evolving from version to version of librt

1st approach called memory mapped files API (supported in std libs)

2nd called POSIX shared memory API (requires librt aka libposix on Linux as dependence It's internally constructs path and calls open)

Title: Why use shm_open?

Body:
What's the advantage of doing: shm_open followed a mmap?

Why not create a regular file, and then pass that fd to mmap?

I can't see the advantage of shm_open - these are just references, are they not?

I've read the man of the whole family. It seems to me, that the "secret" is in the mmaping action - the file "type" seems to be meaningless.

Any pointers will be good, especially with performance account.

My context is a (cyclic over-writable) buffer (say 128MB) that will be constantly written to be one process, and constantly dumped from by another.

As an example: what's wrong with this open/mmap approach.

EDIT

To be precise, is one of the following better than the other:

fd = open("/dev/shm/myshm.file", O_CREAT|O_RDWR, S_IRUSR | S_IWUSR);
mem = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

vs.

fd = shm_open("/myshm.file", O_RDWR|O_CREATE, S_IRUSR | S_IWUSR);
mem = mmap(...same as before...);

When I created a file with regular open under the /dev/shm fs, and dumped a Gig of garbage to it, my available memory went down by 1G, and my avaiable disk space remained the same.

What's the difference between the two methods?


来源: stackexchange

问:
Storing code snippets in eclipse
I'm a recent semi-convert to Eclipse after 20 years of using vi and gvim.  One of the things I miss about gvim is that I could cut a bunch of different snippets of code into named buffers, and paste them at will when doing something like repeating a common idiom.  For instance I'd have it so "ap would paste

```<code>DatabaseHandle handle = null;
try
{
  handle = DatabaseConnectionPool.newHandle();
</code>```

and then "bp would paste

```<code>  handle.commit();
}
finally
{
  handle.rollback();
  DatabaseConnectionPool.returnHandle(handle);
}
</code>```

And I could repeat both of them over and over in the course of a day.  In an answer to another question, somebody mentioned that you could "manage code snippets" in Eclipse, but didn't mention how.  So now I'm asking: how do you manage code snippets in Eclipse?

答:
Use Eclipse Snipmatch (Part of Eclipse for Java Developers Package).

Works very well for Java code snippets but also works for any other language like HTML, ABABP, PHP etc.

You can convert any code fragment from your editor directly to a code template. Highlight the code you'd like to convert to a snippet, context menu "create snippet", complete the form and done.

snippets can be shared via Git repositories with your team members

Manual:
https://www.eclipse.org/recommenders/manual/#snipmatch

Installation:
https://marketplace.eclipse.org/content/snipmatch

OwnerDisplayName: Paul Tomblin

ContentLicense: CC BY-SA 2.5

Title: Storing code snippets in eclipse

Body:
I'm a recent semi-convert to Eclipse after 20 years of using vi and gvim.  One of the things I miss about gvim is that I could cut a bunch of different snippets of code into named buffers, and paste them at will when doing something like repeating a common idiom.  For instance I'd have it so "ap would paste

DatabaseHandle handle = null;
try
{
  handle = DatabaseConnectionPool.newHandle();

and then "bp would paste

  handle.commit();
}
finally
{
  handle.rollback();
  DatabaseConnectionPool.returnHandle(handle);
}

And I could repeat both of them over and over in the course of a day.  In an answer to another question, somebody mentioned that you could "manage code snippets" in Eclipse, but didn't mention how.  So now I'm asking: how do you manage code snippets in Eclipse?

ContentLicense: CC BY-SA 3.0


问:
I want to fetch the Column Name Of Small(Range,1)
I want to fetch the Column Name Of Small(Range,1)

Ive a top row that has names on it. I want a cell that shows

Smallest out of the row with the name concatenated

Example it shows like this : ABC - 1000

If 1000 is the smallest number in the row it show concatenate 1000 with the name of the top row above 1000.

Can anyone help me with the solution.

答:
Try the formula below,

```<code>=A1&" "&SMALL(A2:A5,1)
</code>```

Where, A1 is the row name and A2:A5 is the range

Body:
Try the formula below,

=A1&" "&SMALL(A2:A5,1)

Where, A1 is the row name and A2:A5 is the range


问:
for-loop over directory to zip subdirectories
My question is really simple but it's been too long since I last read bash-scripts so I cannot understand bash anymore...

I have a folder (name containing spaces) which has x subfolders. Now I want to zip each subfolder in its own zip archive.

The following script is what I have:

```<code>#!/bin/bash
cd $1
for folder in $1/* do
zip -r "${folder%/}" "${folder%/}"
done
</code>```

every time I try to execute it with ./test.sh . I just get

```<code>./test.sh: line 4: syntax error near unexpected token `zip'
./test.sh: line 4: `zip -r "${folder%/}" "${folder%/}"'
</code>```

what is wrong with my thoughts and why?

if I enter a variable (e.g. file="subfolder i want to zip") in the shell and execute zip -r "${file}" "${file}" it just works fine for the one folder.

I appreciate any help and hope my question can be solved easily (so I'm able to understand it).
Thanks a lot in advance.

答:
Try this -

```<code>#!/bin/bash
cd $1
for folder in $1/*
do
zip -r "${folder%/}" "${folder%/}"
done
</code>```

Either put ";" after $1/* or use do in next line.

Body:
My question is really simple but it's been too long since I last read bash-scripts so I cannot understand bash anymore...

I have a folder (name containing spaces) which has x subfolders. Now I want to zip each subfolder in its own zip archive.

The following script is what I have:

#!/bin/bash
cd $1
for folder in $1/* do
zip -r "${folder%/}" "${folder%/}"
done

every time I try to execute it with ./test.sh . I just get

./test.sh: line 4: syntax error near unexpected token `zip'
./test.sh: line 4: `zip -r "${folder%/}" "${folder%/}"'

what is wrong with my thoughts and why?

if I enter a variable (e.g. file="subfolder i want to zip") in the shell and execute zip -r "${file}" "${file}" it just works fine for the one folder.

I appreciate any help and hope my question can be solved easily (so I'm able to understand it).
Thanks a lot in advance.

Body:
Try this -

#!/bin/bash
cd $1
for folder in $1/*
do
zip -r "${folder%/}" "${folder%/}"
done

Either put ";" after $1/* or use do in next line.


问:
Deploying WAR File to Glassfish
I'm just getting to grips with the NetBeans 6.9 / Glassfish 3 combo, and have developed a Java EE app consisting of a WAR module and an EJB module. Having played around with the EJB side of things for a while, I went back to run the web code, and started having problems.

When I try to run the WAR file, it fails to deploy, and the error from the server is `WEB0113: virtual server [server] already has a web module [MyApp-war.war] loaded.' But I haven't edited the web side code since I last ran it, and I'm rather puzzled as to what it's trying to do.

I've tried the usual things: restarting the server, undeploying and redeploying the application, but to no avail... so if anyone with any more experience with Glassfish has any hints, they will be gratefully received!

答:
I had the same problem. Restart of glassfish server helped.

What was interesting, the Applications list did not have the application. Apparently some glassfish/netbeans bug.

Title: Deploying WAR File to Glassfish


问:
How to use Python parallel modules like multiprocessing.Pool on Sun SGE grid
I have a piece of python code that runs on a single machine with multiprocessing.Pool for lots of independent jobs. I wonder if it's possible to make it even more parallel on a SGE grid, e.g., each node of the grid runs multiple threads for these independent jobs.

Originally, I have:

```<code># function def
# some_function(param1, param2, param3, process_index)
func = functools.partial(some_function, file_list, param1, param2, param3)
pool = multiprocessing.Pool(processes=some_integer)
ret_list = pool.map(func, range(processes))
pool.close()
</code>```

It seems to be working fine on a local machine, but if submitted onto a SGE grid as is, it indeed quit abnormally without spitting an error message. The submission command may look like this:

```<code>qsub -V -b yes -cwd -l h_vmem=10G -N jobname -o grid_job.log -j yes "python worker.py"
</code>```

Ideally, I'm looking for minimum changes to the local version of python code so that it can be run on SGE grid, because it's hard to install new tools on the grid or change any grid configurations without affecting other users.

On the minimum, I understand it's possible to just rewrite the code such that the processing of each of the jobs (a file in file_list) is handled by one qsub command. But I wonder what the best practice is.

答:
What i would do is to make Python script read file list and number of processes as command line arguments. This way it's easier to call it. I would write a Bash script which receive the file list as arguments and submits all the jobs depending on what you want to do. This way you can do two levels of parallelization : on several nodes (qsub) and several processes per node (python multiprocess). To do it the right way, you need to tell qsub the number of SLOTS you want for each job. This is done by submitting in a parallel environment and specifying a SLOT number (-pe ENV_NAME NBSLOTS) :

```<code>#!/bin/bash

NB_PROCESS_PER_JOB=2
NB_FILE_PER_JOB=3
CPT=0
BUF=""
NUMJOB=1

for i in "$@"; do
    BUF="$BUF '$i'"
    ((CPT++))
    if ((CPT == NB_FILE_PER_JOB)); then
        echo qsub -pe multithread $CPT -V -b yes -cwd -l h_vmem=10G -N jobname$NUMJOB -o grid_job.log -j yes "python worker.py $NB_PROCESS_PER_JOB $BUF"
        BUF=""
        CPT=0
        ((NUMJOB++))
    fi
done
if [[ "$BUF" != "" ]]; then
    echo qsub -pe multithread $CPT -V -b yes -cwd -l h_vmem=10G -N jobname$NUMJOB -o grid_job.log -j yes "python worker.py $NB_PROCESS_PER_JOB $BUF"
fi
</code>```

The Python script would look like :

```<code>import sys

nb_processes = int(sys.argv[1])
file_list = sys.argv[2:]

pool = multiprocessing.Pool(processes=nb_processes)
ret_list = pool.map(some_function, file_list)
pool.close()
</code>```

If your SGE cluster does not have any parallel environment, i suggest you do not parallelize the Python script (remove -pe ENV_NAME NBSLOTS argument and do not use pool in Python script or make it produce only one process). A simple SGE job is not supposed to be multithreaded. If a simple job is multithreaded, it uses unreserved resource and might slow down other users jobs.

Body:
I have a piece of python code that runs on a single machine with multiprocessing.Pool for lots of independent jobs. I wonder if it's possible to make it even more parallel on a SGE grid, e.g., each node of the grid runs multiple threads for these independent jobs.

Originally, I have:

# function def
# some_function(param1, param2, param3, process_index)
func = functools.partial(some_function, file_list, param1, param2, param3)
pool = multiprocessing.Pool(processes=some_integer)
ret_list = pool.map(func, range(processes))
pool.close()

It seems to be working fine on a local machine, but if submitted onto a SGE grid as is, it indeed quit abnormally without spitting an error message. The submission command may look like this:

qsub -V -b yes -cwd -l h_vmem=10G -N jobname -o grid_job.log -j yes "python worker.py"

Ideally, I'm looking for minimum changes to the local version of python code so that it can be run on SGE grid, because it's hard to install new tools on the grid or change any grid configurations without affecting other users.

On the minimum, I understand it's possible to just rewrite the code such that the processing of each of the jobs (a file in file_list) is handled by one qsub command. But I wonder what the best practice is.

Body:
What i would do is to make Python script read file list and number of processes as command line arguments. This way it's easier to call it. I would write a Bash script which receive the file list as arguments and submits all the jobs depending on what you want to do. This way you can do two levels of parallelization : on several nodes (qsub) and several processes per node (python multiprocess). To do it the right way, you need to tell qsub the number of SLOTS you want for each job. This is done by submitting in a parallel environment and specifying a SLOT number (-pe ENV_NAME NBSLOTS) :

#!/bin/bash

NB_PROCESS_PER_JOB=2
NB_FILE_PER_JOB=3
CPT=0
BUF=""
NUMJOB=1

for i in "$@"; do
    BUF="$BUF '$i'"
    ((CPT++))
    if ((CPT == NB_FILE_PER_JOB)); then
        echo qsub -pe multithread $CPT -V -b yes -cwd -l h_vmem=10G -N jobname$NUMJOB -o grid_job.log -j yes "python worker.py $NB_PROCESS_PER_JOB $BUF"
        BUF=""
        CPT=0
        ((NUMJOB++))
    fi
done
if [[ "$BUF" != "" ]]; then
    echo qsub -pe multithread $CPT -V -b yes -cwd -l h_vmem=10G -N jobname$NUMJOB -o grid_job.log -j yes "python worker.py $NB_PROCESS_PER_JOB $BUF"
fi

The Python script would look like :

import sys

nb_processes = int(sys.argv[1])
file_list = sys.argv[2:]

pool = multiprocessing.Pool(processes=nb_processes)
ret_list = pool.map(some_function, file_list)
pool.close()

If your SGE cluster does not have any parallel environment, i suggest you do not parallelize the Python script (remove -pe ENV_NAME NBSLOTS argument and do not use pool in Python script or make it produce only one process). A simple SGE job is not supposed to be multithreaded. If a simple job is multithreaded, it uses unreserved resource and might slow down other users jobs.


问:
How to post data using HttpClient? (an answer than actually works)
There is another question about this, but it doesn't have a functioning solution at the end, and the only good answer, for some reason, doesn't work, not for the guy who ask it, not for me either.

This such question is here:
How to post data using HttpClient?

Given the corresponding aclarations, this is the code I have so far:

The methods to call the method who connects with the web server:

```<code>private void Button_Click(object sender, System.EventArgs e)
{
    //. . . DO SOMETHING . . .
    PopulateListView();

    //. . . DO SOMETHING ELSE . . .
}

private void PopulateListView()
{
   //. . . DO SOMETHING . . .

   list = await "http://web.server.url".GetRequest<List<User>>();

   //. . . DO SOMETHING ELSE . . .
}
</code>```

The method than connects with the web server:

```<code>public async static Task<T> SendGetRequest<T>(this string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        MainActivity.ConsoleData = json.ToString();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error: "+ex.ToString());
        return default(T);
    }
}
</code>```

You maybe guessed it, but I'm trying to make a method that send some data (through POST) called "markString" to a web-server than receive it and, depending of the "markString" it returns certain json Objects.

This web server is already working properly (I tested it out with some plug-in, it work like it should)

This method is supposed to send the "markString" and receive the data back so then i can use it in the app.

I'm making a Xamarin Android application.

Also have in mind than I don't have any connection problem at all, in fact the app is sending data in an excellent matter when I try to do it using web client, but I want it to send it using HttpClient.

The problem

The code is not returning anything. Any request for information, clarification, question, constructive comments or anything than can lead to an answer would be greatly appreciated too.

Thanks in advance.

答:
```<code>void Main()
{
    var test = SendGetRequest("http://www.google.com");
    test.Dump();
}

public async static Task<string> SendGetRequest(string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();

        return json;
    }
    catch (System.Exception ex)
    {
        Console.WriteLine("Error: " + ex.ToString());
        return string.Empty;
    }

}
</code>```

Body:
There is another question about this, but it doesn't have a functioning solution at the end, and the only good answer, for some reason, doesn't work, not for the guy who ask it, not for me either.

This such question is here:
How to post data using HttpClient?

Given the corresponding aclarations, this is the code I have so far:

The methods to call the method who connects with the web server:

private void Button_Click(object sender, System.EventArgs e)
{
    //. . . DO SOMETHING . . .
    PopulateListView();

    //. . . DO SOMETHING ELSE . . .
}

private void PopulateListView()
{
   //. . . DO SOMETHING . . .

   list = await "http://web.server.url".GetRequest<List<User>>();

   //. . . DO SOMETHING ELSE . . .
}

The method than connects with the web server:

public async static Task<T> SendGetRequest<T>(this string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        MainActivity.ConsoleData = json.ToString();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error: "+ex.ToString());
        return default(T);
    }
}

You maybe guessed it, but I'm trying to make a method that send some data (through POST) called "markString" to a web-server than receive it and, depending of the "markString" it returns certain json Objects.

This web server is already working properly (I tested it out with some plug-in, it work like it should)

This method is supposed to send the "markString" and receive the data back so then i can use it in the app.

I'm making a Xamarin Android application.

Also have in mind than I don't have any connection problem at all, in fact the app is sending data in an excellent matter when I try to do it using web client, but I want it to send it using HttpClient.

The problem

The code is not returning anything. Any request for information, clarification, question, constructive comments or anything than can lead to an answer would be greatly appreciated too.

Thanks in advance.


答:
You need a semicolon before the do:

```<code>for folder in $1/*; do
  zip -r "${folder%/}" "${folder%/}"
done
</code>```

This is needed to disambiguate the grammar, specifically to indicate "no more strings to iterate over". Eg. this allows to iterate over shell keywords:

```<code>for k in do if done; do
  ...
done
</code>```

Title: for-loop over directory to zip subdirectories

Body:
You need a semicolon before the do:

for folder in $1/*; do
  zip -r "${folder%/}" "${folder%/}"
done

This is needed to disambiguate the grammar, specifically to indicate "no more strings to iterate over". Eg. this allows to iterate over shell keywords:

for k in do if done; do
  ...
done


问:
angular-cli, route.hash = true and ng build
I use angular-cli and router.forRoot({hash: true}). When I run ng build it gives me a <base href="/"> added to the generated index.html which screws up the loading of the app.

I want to use route.hash = true and not having to delete each time the tag <base href="/"> from the generated dist/index.html.

How to avoid this?

答: The <base href="/"> is not dynamically added on build. At least not for beta 24 all the way to 1.0.0. It's static in /src/index.html just remove it from /src/index.html and it should not appear when you run ng serve


问:
jQuery getJSON function not returning anything
I have this code:

```<code>$.getJSON('data.json', function (data) {
    console.log(data);
});
</code>```

And this is the data.json file:

```<code>{
  "Sameer": {
    "Phone": "0123456789",
  },
  "Mona": {
    "Phone": "0123456789",
  },
}
</code>```

But the console.log(data) not returning anything, Not even an error I don't know what is wrong with my code.

I tried to use $.ajax() function instead but no luck. And when I change my data.json file to something random like: data.asd I get an error that saying the file data.asd not found!

Body:
I have this code:

$.getJSON('data.json', function (data) {
    console.log(data);
});

And this is the data.json file:

{
  "Sameer": {
    "Phone": "0123456789",
  },
  "Mona": {
    "Phone": "0123456789",
  },
}

But the console.log(data) not returning anything, Not even an error I don't know what is wrong with my code.

I tried to use $.ajax() function instead but no luck. And when I change my data.json file to something random like: data.asd I get an error that saying the file data.asd not found!

Body:
Correct jSon format :

{
    "Sameer": {
        "Phone": "0123456789"
    },
    "Mona": {
        "Phone": "0123456789"
    }
}


问:
How to filter containments by associated data?
I want to get associated only if the second level associated data respect the given condition.

The query will maybe better explain what I try to do.

```<code>$selSite = $this->Sites->get($selSiteId, [
    'contain' => [
        'Agplans.Products' => function ($q) {
            return $q
            ->where([
                'Products.type' => 'hosting',
            ]);
        }
    ]
]);
</code>```

So I expect an agplan only if its associated product matches the condition.

But the result is:

```<code>'agplans' => [
    (int) 0 => object(App\Model\Entity\Agplan) {

        'id' => (int) 20,
        'product_id' => (int) 4,
        'product' => null,
        ...,

    },
    (int) 1 => object(App\Model\Entity\Agplan) {

        'id' => (int) 21,
        'site_id' => (int) 64,
        'product_id' => (int) 75,
        'product' => object(App\Model\Entity\Product) {

            'id' => (int) 75,
            ...,

        },
        ...,

    }
],
</code>```

My problem here is to get agplan[0] with a product => null.
It's not what I understood from the doc.
How to get the agplan with 'product' => object(App\Model\Entity\Product) only?

答:
So thanks to what @ndm pointed me out I understood that I have to build my query like that:

```<code>$selSite = $this->Sites->get($selSiteId, [
    'contain' => [
        'Agplans.Products',
        'Agplans' => function ($q) {
            return $q
            ->matching('Products', function ($q) {
                return $q
                ->where([
                    'type' => 'hosting',
                ]);
            });
        }
    ]
]);
</code>```

That way, I only get agplans matching the given product.
Anyway, I find the CakePHP doc not clear on the contain feature about restricting associated.

Body:
I want to get associated only if the second level associated data respect the given condition.

The query will maybe better explain what I try to do.

$selSite = $this->Sites->get($selSiteId, [
    'contain' => [
        'Agplans.Products' => function ($q) {
            return $q
            ->where([
                'Products.type' => 'hosting',
            ]);
        }
    ]
]);

So I expect an agplan only if its associated product matches the condition.

But the result is:

'agplans' => [
    (int) 0 => object(App\Model\Entity\Agplan) {

        'id' => (int) 20,
        'product_id' => (int) 4,
        'product' => null,
        ...,

    },
    (int) 1 => object(App\Model\Entity\Agplan) {

        'id' => (int) 21,
        'site_id' => (int) 64,
        'product_id' => (int) 75,
        'product' => object(App\Model\Entity\Product) {

            'id' => (int) 75,
            ...,

        },
        ...,

    }
],

My problem here is to get agplan[0] with a product => null.
It's not what I understood from the doc.
How to get the agplan with 'product' => object(App\Model\Entity\Product) only?

Body:
So thanks to what @ndm pointed me out I understood that I have to build my query like that:

$selSite = $this->Sites->get($selSiteId, [
    'contain' => [
        'Agplans.Products',
        'Agplans' => function ($q) {
            return $q
            ->matching('Products', function ($q) {
                return $q
                ->where([
                    'type' => 'hosting',
                ]);
            });
        }
    ]
]);

That way, I only get agplans matching the given product.
Anyway, I find the CakePHP doc not clear on the contain feature about restricting associated.


问:
Django: How can I provide different users a different subset of options for the same ManyToManyField

The Question:

How can I provide different users a different subset of options for the same ManyToManyField in the admin, and have each user's selections only affect their options?

The Scenario:

I am building an interactive map web app. There can be many Maps. There can be many MapItems.
MapItems can be on many Maps and Maps can have many Map Items. Thus a ManyToMany relationship.

Each Map has an owner, and I want only the owner of a Map to be able to add or remove MapItems from his/her Map.

Here are the relevant parts of my models:

```<code>class Map(models.Model):
    # Omit
    owner = models.ForeignKey(User, default=1)

class MapItem(models.Model):
    # Omit
    map = models.ManyToManyField(Map, default=None, blank=True)
</code>```

MapItem.map is represented by a <select> on the MapItem admin interface:

```<code><select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
  <option value="2">Sally's Map</option>
</select>
</code>```

I want Bob to only have the option to select/deselect Bob's Map and not even see Sally's Map as an option.

I have been able to filter the options that are displayed in the admin <select> widget by overriding get_form() on the ModelAdmin.

```<code>def get_form(self, request, obj=None, **kwargs):
    kwargs['form'] = MapItemAdminForm
    form = super(MapItemAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['map'].queryset = form.base_fields['map'].queryset.filter(Q(owner=request.user) | Q(groups__in=request.user.groups.all()))
    return form
</code>```

So far so good. This gives me a select with only the desired options:

```<code><select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
</select>
</code>```

The problem comes in when Bob saves. When Bob saves, it wipes out any saved value for Sally's Map. So if Sally's Map was selected, when Bob saves (even though Bob can't see it), Sally's Map gets deselected.

Is there a better approach to this problem? Is there a way to ensure that unchanged values (like Sally's Map being selected) persist on save?

答:
@lufte's answer was close, but not quite what I needed. It did put me on the right scent though. Here is my solution:

save_model is great for tweaking the values of fields that are not ManyToMany. However, ManyToMany fields
are not able to be affected in this method, as whatever changes made will be cleared prior to being saved.

save_related, on the other hand, is just what I needed. I was able to determine which Maps my user should be able to affect in get_form and pass any others on to be saved in save_related. DOCS.

Here's some code for reference:

```<code>def get_form(self, request, obj=None, **kwargs):
      form = super(MapItemAdmin, self).get_form(request, obj, **kwargs)

      # Filter already selected maps
      # and create a list of map current user can't touch
      self.existing_maps = [m.id for m in obj.map.all() \
      if not m.owner == request.user and not \
      m.groups.filter(id__in=request.user.groups.all())]

      # Filter the options that will be displayed in the admin <select>
      form.base_fields['map'].queryset = \
      form.base_fields['map'].queryset.filter(Q(owner=request.user) \
      | Q(groups__in=request.user.groups.all()))
      return form

  def save_related(self, request, form, formsets, change):
      super(MapItemAdmin, self).save_related(request, form, formsets, change)

      # Re-add any previously selected maps that the current user can't touch
      for em in self.existing_maps:
          form.instance.map.add(em)
</code>```

Body:
The Question:

How can I provide different users a different subset of options for the same ManyToManyField in the admin, and have each user's selections only affect their options?

The Scenario:

I am building an interactive map web app. There can be many Maps. There can be many MapItems.
MapItems can be on many Maps and Maps can have many Map Items. Thus a ManyToMany relationship.

Each Map has an owner, and I want only the owner of a Map to be able to add or remove MapItems from his/her Map.

Here are the relevant parts of my models:

class Map(models.Model):
    # Omit
    owner = models.ForeignKey(User, default=1)

class MapItem(models.Model):
    # Omit
    map = models.ManyToManyField(Map, default=None, blank=True)

MapItem.map is represented by a <select> on the MapItem admin interface:

<select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
  <option value="2">Sally's Map</option>
</select>

I want Bob to only have the option to select/deselect Bob's Map and not even see Sally's Map as an option.

I have been able to filter the options that are displayed in the admin <select> widget by overriding get_form() on the ModelAdmin.

def get_form(self, request, obj=None, **kwargs):
    kwargs['form'] = MapItemAdminForm
    form = super(MapItemAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['map'].queryset = form.base_fields['map'].queryset.filter(Q(owner=request.user) | Q(groups__in=request.user.groups.all()))
    return form

So far so good. This gives me a select with only the desired options:

<select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
</select>

The problem comes in when Bob saves. When Bob saves, it wipes out any saved value for Sally's Map. So if Sally's Map was selected, when Bob saves (even though Bob can't see it), Sally's Map gets deselected.

Is there a better approach to this problem? Is there a way to ensure that unchanged values (like Sally's Map being selected) persist on save?

Body:
@lufte's answer was close, but not quite what I needed. It did put me on the right scent though. Here is my solution:

save_model is great for tweaking the values of fields that are not ManyToMany. However, ManyToMany fields
are not able to be affected in this method, as whatever changes made will be cleared prior to being saved.

save_related, on the other hand, is just what I needed. I was able to determine which Maps my user should be able to affect in get_form and pass any others on to be saved in save_related. DOCS.

Here's some code for reference:

def get_form(self, request, obj=None, **kwargs):
      form = super(MapItemAdmin, self).get_form(request, obj, **kwargs)

      # Filter already selected maps
      # and create a list of map current user can't touch
      self.existing_maps = [m.id for m in obj.map.all() \
      if not m.owner == request.user and not \
      m.groups.filter(id__in=request.user.groups.all())]

      # Filter the options that will be displayed in the admin <select>
      form.base_fields['map'].queryset = \
      form.base_fields['map'].queryset.filter(Q(owner=request.user) \
      | Q(groups__in=request.user.groups.all()))
      return form

  def save_related(self, request, form, formsets, change):
      super(MapItemAdmin, self).save_related(request, form, formsets, change)

      # Re-add any previously selected maps that the current user can't touch
      for em in self.existing_maps:
          form.instance.map.add(em)


问:
How to access (copy) specific elements of Mat in OpenCV?
Let's say I have a matrix of single row x. In MATLAB, I can access specific elements of x via

```<code>x=[10 6 9 12 15 20 22];
index=[1 3 7];
y=x(index)
y =
    10     9    22
</code>```

How can I do the same in OpenCV (without for loop)?

I know there are ways to access rows or columns of the matrix, but I couldn't find a way to access only specific elements in OpenCV.

Edit:

I am using C++. What if x is NxM matrix and I want to access some elements in the 5th column. In MATLAB, I can do it as x(index,5). I can sure do it with for loops in OpenCV. My question is, is there any ready OpenCV function that returns me the specific elements of x?

答:
As mentioned in the comments you will have to use a loop. Unlike Matlab you can't access all the elements at once. Assuming you have a single row matrix with one channel as you indicated, the following code will work (depending on the datatype you use):

```<code>int foo[TheNumberOfColumnsYouNeed];
for(int i = 0; i < matrix.cols; i++)
{
    if(i == TheColumnsYouNeed)
        foo[i] = matrix.at<double>(0, i);
}
</code>```

If you specifically want the 5th column of a single row matrix, you can do the following without a loop (assuming datatype double):

```<code>foo = matrix.at<double>(0, 5);
</code>```

Body:
Let's say I have a matrix of single row x. In MATLAB, I can access specific elements of x via

x=[10 6 9 12 15 20 22];
index=[1 3 7];
y=x(index)
y =
    10     9    22

How can I do the same in OpenCV (without for loop)?

I know there are ways to access rows or columns of the matrix, but I couldn't find a way to access only specific elements in OpenCV.

Edit:

I am using C++. What if x is NxM matrix and I want to access some elements in the 5th column. In MATLAB, I can do it as x(index,5). I can sure do it with for loops in OpenCV. My question is, is there any ready OpenCV function that returns me the specific elements of x?

Body:
As mentioned in the comments you will have to use a loop. Unlike Matlab you can't access all the elements at once. Assuming you have a single row matrix with one channel as you indicated, the following code will work (depending on the datatype you use):

int foo[TheNumberOfColumnsYouNeed];
for(int i = 0; i < matrix.cols; i++)
{
    if(i == TheColumnsYouNeed)
        foo[i] = matrix.at<double>(0, i);
}

If you specifically want the 5th column of a single row matrix, you can do the following without a loop (assuming datatype double):

foo = matrix.at<double>(0, 5);


问:
How to delete folders in sdcard of file explorer?
I created several folders in the sdcard (Eclipse) by running an Android application in the emulator. Now I want to delete the folders which I have created on the sdcard.

I am able to delete files in the folders but I could not delete the folders in the sdcard.

How can I do this? Is there a way to delete folders?

答:
We can do it in a single command line as under:</p>

```<code>adb shell rm -r sdcard/<dirname>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
We can do it in a single command line as under:

adb shell rm -r sdcard/<dirname>


问:
Access Blob Properties in Azure
I need to get the blob properties, in there is a last modified date. I need the date for comparison. Have read a number of articles, and thought it was because I was not using a CloudBlockBlob, but I cannot extract the properties from it.

My code so far returns the names of the blobs:

```<code>public static void ListBlobsAnonymously()
    {
        //Get the blob from the URL - URL is in the app.config file so it can be changed easily should it need it.
        CloudBlobContainer container = new CloudBlobContainer(new Uri(ConfigurationManager.AppSettings["VOURL"]));

        //For each of the blobs, write the file name out. This will be needed for a comparison.
        foreach (IListBlobItem blobItem in container.ListBlobs())
        {
            string name = blobItem.Uri.Segments.Last();
            Console.WriteLine(name);
        }

        Console.ReadKey();
    }
</code>```

This is the structure of the blobs:

```<code><EnumerationResults ServiceEndpoint="https://test.blob.core.windows.net/" ContainerName="downloads">
<Blobs>
    <Blob>
        <Name>
        This_is_a_test
        </Name>
        <Properties>
            <Last-Modified>Tue, 01 Oct 2010 14:33:48 GMT</Last-Modified>
            <Content-Length>452</Content-Length>
            <Content-Type>application/zip</Content-Type>
            <BlobType>BlockBlob</BlobType>
        </Properties>
    </Blob>
</Blobs>
</EnumerationResults>
</code>```

It is the last modified within the properties that I need to get hold of and cannot.

答:
Try this code: (note: not supported/working on NET Core)

```<code>        CloudBlobContainer container = new CloudBlobContainer(new Uri(ConfigurationManager.AppSettings["VOURL"]));

        //For each of the blobs, write the file name out. This will be needed for a comparison.
        foreach (IListBlobItem blobItem in container.ListBlobs())
        {
            var blob = (CloudBlob)blobItem;
            if (blob != null)
            {
                string name = blobItem.Uri.Segments.Last();
                Console.WriteLine(name);
                Console.WriteLine(blob.Properties.LastModified);
            }
        }

        Console.ReadKey();
</code>```

Basically you would need to cast IListBlobItem to CloudBlob and there you will have access to blob's properties.

Title: Access Blob Properties in Azure

Body:
I need to get the blob properties, in there is a last modified date. I need the date for comparison. Have read a number of articles, and thought it was because I was not using a CloudBlockBlob, but I cannot extract the properties from it.

My code so far returns the names of the blobs:

public static void ListBlobsAnonymously()
    {
        //Get the blob from the URL - URL is in the app.config file so it can be changed easily should it need it.
        CloudBlobContainer container = new CloudBlobContainer(new Uri(ConfigurationManager.AppSettings["VOURL"]));

        //For each of the blobs, write the file name out. This will be needed for a comparison.
        foreach (IListBlobItem blobItem in container.ListBlobs())
        {
            string name = blobItem.Uri.Segments.Last();
            Console.WriteLine(name);
        }

        Console.ReadKey();
    }

This is the structure of the blobs:

<EnumerationResults ServiceEndpoint="https://test.blob.core.windows.net/" ContainerName="downloads">
<Blobs>
    <Blob>
        <Name>
        This_is_a_test
        </Name>
        <Properties>
            <Last-Modified>Tue, 01 Oct 2010 14:33:48 GMT</Last-Modified>
            <Content-Length>452</Content-Length>
            <Content-Type>application/zip</Content-Type>
            <BlobType>BlockBlob</BlobType>
        </Properties>
    </Blob>
</Blobs>
</EnumerationResults>

It is the last modified within the properties that I need to get hold of and cannot.

Body:
Try this code: (note: not supported/working on NET Core)

        CloudBlobContainer container = new CloudBlobContainer(new Uri(ConfigurationManager.AppSettings["VOURL"]));

        //For each of the blobs, write the file name out. This will be needed for a comparison.
        foreach (IListBlobItem blobItem in container.ListBlobs())
        {
            var blob = (CloudBlob)blobItem;
            if (blob != null)
            {
                string name = blobItem.Uri.Segments.Last();
                Console.WriteLine(name);
                Console.WriteLine(blob.Properties.LastModified);
            }
        }

        Console.ReadKey();

Basically you would need to cast IListBlobItem to CloudBlob and there you will have access to blob's properties.


问:
Can't bind IsBusy property
I have Page with an Activity Indicator with the following code:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.ClientSearch" Title="Search">
  <ContentPage.Content>
    <StackLayout Orientation="Vertical">
      <StackLayout.Children>
        <SearchBar x:Name="txtSearchClient" TextChanged="OnTextChanged"></SearchBar>
        <ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}" x:Name="indicadorCargando" />
        <ListView x:Name="lstClients"></ListView>
      </StackLayout.Children>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>
</code>```

In the partial class associated to this xaml, I have:

```<code>namespace MyApp
{
    public partial class ClientSearch: ContentPage
    {
        public BusquedaClientes()
        {
            InitializeComponent();
        }

        async void OnTextChanged(object sender, TextChangedEventArgs e)
        {

            if (this.txtSearchClient.Text.Length >= 3)
            {
                var list_clients = App.ClientsManager.GetTasksAsync(txtSearchClient.Text);
                this.IsBusy = true;

                var template = new DataTemplate(typeof(TextCell));

                template.SetBinding(TextCell.DetailProperty, "name_ct");
                template.SetBinding(TextCell.TextProperty, "cod_ct");

                lstClients.ItemTemplate = template;
                lstClients.ItemsSource = await list_clients;

                this.IsBusy = false;

            }
        }
    }
}
</code>```

As you can see, this.IsBusy is setting the Page property, so tried to bind to that property in the XAML. Unfortunetly it doesn't work:

```<code><ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}" x:Name="indicadorCargando" />
</code>```

How can I bind the values of the ActivityIndicator to the IsBusy page property?
I already know that setting the values like this:

```<code>this.IsBusy = true;
indicadorCargando.IsVisible=true;
indicadorCargando.IsRunning=true;
</code>```

But I don't want to do that, I want to set one value instead of three.

答: You need to give your page a name (x:Name="myPage") and then declare the binding using a reference to it using {Binding Source={x:Reference myPage}, Path=IsBusy} for the ActivityIndicator's IsVisible and IsRunning values. More info on this answer.

Title: Can't bind IsBusy property

Body:
I have Page with an Activity Indicator with the following code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.ClientSearch" Title="Search">
  <ContentPage.Content>
    <StackLayout Orientation="Vertical">
      <StackLayout.Children>
        <SearchBar x:Name="txtSearchClient" TextChanged="OnTextChanged"></SearchBar>
        <ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}" x:Name="indicadorCargando" />
        <ListView x:Name="lstClients"></ListView>
      </StackLayout.Children>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

In the partial class associated to this xaml, I have:

namespace MyApp
{
    public partial class ClientSearch: ContentPage
    {
        public BusquedaClientes()
        {
            InitializeComponent();
        }

        async void OnTextChanged(object sender, TextChangedEventArgs e)
        {

            if (this.txtSearchClient.Text.Length >= 3)
            {
                var list_clients = App.ClientsManager.GetTasksAsync(txtSearchClient.Text);
                this.IsBusy = true;

                var template = new DataTemplate(typeof(TextCell));

                template.SetBinding(TextCell.DetailProperty, "name_ct");
                template.SetBinding(TextCell.TextProperty, "cod_ct");

                lstClients.ItemTemplate = template;
                lstClients.ItemsSource = await list_clients;

                this.IsBusy = false;

            }
        }
    }
}

As you can see, this.IsBusy is setting the Page property, so tried to bind to that property in the XAML. Unfortunetly it doesn't work:

<ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}" x:Name="indicadorCargando" />

How can I bind the values of the ActivityIndicator to the IsBusy page property?
I already know that setting the values like this:

this.IsBusy = true;
indicadorCargando.IsVisible=true;
indicadorCargando.IsRunning=true;

But I don't want to do that, I want to set one value instead of three.


问:
jQuery ID Return is undefined although HTML ID is defined
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

```<code><div class="mainContent">
<div class="articleContent">
     <h1>header1</h1>
     <p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>

<div class="mainContent">
<div class="articleContent">
     <h1>header2</h1>
     <p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
</code>```

And then the JS/jQuery

```<code>function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}
</code>```

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

答:
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id

function readMore() {
  var subID = event.target.id;
  var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
  <div class="articleContent">
    <h1>header</h1>
    <p class="articlePara" id="one"></p>
  </div>
  <div class="articleFooter" id="one" onclick="readMore()">click
  </div>
</div></code>```

Body:
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

header1

para1

header2

para2

And then the JS/jQuery

function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

Body:
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id

function readMore() {
  var subID = event.target.id;
  var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
  <div class="articleContent">
    <h1>header</h1>
    <p class="articlePara" id="one"></p>
  </div>
  <div class="articleFooter" id="one" onclick="readMore()">click
  </div>
</div>


问:
Observable for mutiple responses in angular 2
So, I have this service which first calls a function from another module which basically returns an list of urls from an external api. This service then must http.get from all the urls in that list (every url returns a json object of same format) then return a single observable which I can then use in an angular component. Here's what my service code looks like:

```<code>    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Client } from 'external-api';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';

    let client = new Client();

    @Injectable()
    export class GbDataService {
      constructor(private _http: Http) {

      }

        getGBData(): Observable<any> {
        client.fetchUrls("").then(resp=> {
        resp.forEach(url => {
          //this._http.get(url).map(res => res.json);
          // Create a single observable for every http response

        });
        }).catch(function(err){
            console.log(err.message);
        });
        //return observable
      };
   }
</code>```

http.get returns and Observable<Response> type but I couldn't find a way to create and return one Observable for all http.get responses. How can this be done ? Should I create an observable array then push() all the get response I get to the array?

EDIT: It doesn't really matters to me if responses are emitted one by one or all at once BUT there must be only a single Obeservable which emits the responses of all the http.get requests.

Further Edit: This is my fetchURLs method:

```<code>  fetchURLs(): Promise<any> {
    return new Promise((resolve, reject) => {
      let _repos: Array<any>;
      //scrapeTrendingRepos() is from https://github.com/rhysd/node-github-trend
      scraper.scrapeTrendingRepos("").then(repos => {
        repos.forEach(repo => {
          let url = `https:api.github.com/repos/${repo.owner}/${repo.name}`;
          _repos.push(url);
        });
        resolve(_repos);
      }).catch(err => {
        reject(err);
      });
    })
  };
</code>```

Have I implemented Promises in fetchURLs() right??

答:
So, you make a request and get back an array of URLs that you then want to fetch all and get one response from?

Those are the types of things that RxJS excels at.

```<code>@Injectable()
    export class GbDataService {
      constructor(private _http: Http) {

      }

      getGBData(): Observable<any> {

        return Observable
          .fromPromise(client.fetchUrls())   // returns Observable<array>
          .switchMap( urls => {
            // convert your list of urls to a list of http requests
            let urlRequests = urls.map( url => http.get(url) );

            // combineLatest accepts an array of observables,
            // and emits an array of the last results of each of the observables
            // but the first emit only happens after every single observable
            // has emitted its first result

            // TLDR: combineLatest takes an array of Observables
            //       and will emit an array of those observable emissions       //       after all have emitted at least once
            return Observable.combineLatest(urlRequests);

          })
        }).catch(function(err){
            console.log(err.message);
        });
        //return observable
      };
   }
</code>```

Further info:

Read up on the combineLatest observable. In this scenario, it accomplishes what you want of waiting for all its observable arguments to emit before emitting a single array. But if your observable arguments also emit multiple times, it may not do what you expect and you might want to try a different operator like forkJoin or zip.

Additionally

You might want to use switchMap rather than flatMap - if a new request for urls to fetch comes through, switchMap will cancel any requests currently in flight before sending the new list of requests.

Further Edit

Although your fetchURLs implementation can work in its current incarnation, you can simplify your method a bit if you wish by taking advantage of how promises work. In 'Promise-land', the then handler also returns a Promise, and that second Promise will resolve with whatever value you return from your then handler (this is the basic promise chaining concept). Using that knowledge, you can simplify your method to:

```<code>fetchURLs(): Promise<any> {
  //scrapeTrendingRepos() is from https://github.com/rhysd/node-github-trend
  return scraper.scrapeTrendingRepos("").then(repos => {
     // since repos is an array, and you wish to transform each value
     // in that array to a new value, you can use Array.map
     return repos.map( repo => `https:api.github.com/repos/${repo.owner}/${repo.name}`);
  });
}
</code>```

Body:
So, I have this service which first calls a function from another module which basically returns an list of urls from an external api. This service then must http.get from all the urls in that list (every url returns a json object of same format) then return a single observable which I can then use in an angular component. Here's what my service code looks like:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Client } from 'external-api';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';

    let client = new Client();

    @Injectable()
    export class GbDataService {
      constructor(private _http: Http) {

      }

        getGBData(): Observable<any> {
        client.fetchUrls("").then(resp=> {
        resp.forEach(url => {
          //this._http.get(url).map(res => res.json);
          // Create a single observable for every http response

        });
        }).catch(function(err){
            console.log(err.message);
        });
        //return observable
      };
   }

http.get returns and Observable<Response> type but I couldn't find a way to create and return one Observable for all http.get responses. How can this be done ? Should I create an observable array then push() all the get response I get to the array?

EDIT: It doesn't really matters to me if responses are emitted one by one or all at once BUT there must be only a single Obeservable which emits the responses of all the http.get requests.

Further Edit: This is my fetchURLs method:

  fetchURLs(): Promise<any> {
    return new Promise((resolve, reject) => {
      let _repos: Array<any>;
      //scrapeTrendingRepos() is from https://github.com/rhysd/node-github-trend
      scraper.scrapeTrendingRepos("").then(repos => {
        repos.forEach(repo => {
          let url = `https:api.github.com/repos/${repo.owner}/${repo.name}`;
          _repos.push(url);
        });
        resolve(_repos);
      }).catch(err => {
        reject(err);
      });
    })
  };

Have I implemented Promises in fetchURLs() right??

Body:
So, you make a request and get back an array of URLs that you then want to fetch all and get one response from?

Those are the types of things that RxJS excels at.

@Injectable()
    export class GbDataService {
      constructor(private _http: Http) {

      }

      getGBData(): Observable<any> {

        return Observable
          .fromPromise(client.fetchUrls())   // returns Observable<array>
          .switchMap( urls => {
            // convert your list of urls to a list of http requests
            let urlRequests = urls.map( url => http.get(url) );

            // combineLatest accepts an array of observables,
            // and emits an array of the last results of each of the observables
            // but the first emit only happens after every single observable
            // has emitted its first result

            // TLDR: combineLatest takes an array of Observables
            //       and will emit an array of those observable emissions       //       after all have emitted at least once
            return Observable.combineLatest(urlRequests);

          })
        }).catch(function(err){
            console.log(err.message);
        });
        //return observable
      };
   }

Further info:

Read up on the combineLatest observable. In this scenario, it accomplishes what you want of waiting for all its observable arguments to emit before emitting a single array. But if your observable arguments also emit multiple times, it may not do what you expect and you might want to try a different operator like forkJoin or zip.

Additionally

You might want to use switchMap rather than flatMap - if a new request for urls to fetch comes through, switchMap will cancel any requests currently in flight before sending the new list of requests.

Further Edit

Although your fetchURLs implementation can work in its current incarnation, you can simplify your method a bit if you wish by taking advantage of how promises work. In 'Promise-land', the then handler also returns a Promise, and that second Promise will resolve with whatever value you return from your then handler (this is the basic promise chaining concept). Using that knowledge, you can simplify your method to:

fetchURLs(): Promise<any> {
  //scrapeTrendingRepos() is from https://github.com/rhysd/node-github-trend
  return scraper.scrapeTrendingRepos("").then(repos => {
     // since repos is an array, and you wish to transform each value
     // in that array to a new value, you can use Array.map
     return repos.map( repo => `https:api.github.com/repos/${repo.owner}/${repo.name}`);
  });
}


问:
how to add background music
The duplicate answer does not works at all

```<code>import Cocoa
    import AVFoundation

    var error: NSError?

    println("Hello, Audio!")
    var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file
    var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error)
    if midi == nil {
        if let e = error {
            println("AVMIDIPlayer failed: " + e.localizedDescription)
        }
    }
    midi.play(nil)
    while midi.playing {
        // Spin (yeah, that's bad!)
    }
</code>```

答:
The mp3 file must be in the Resources folder.

You play an mp3 with code like this (not the MIDI player):

```<code>if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
  let player = try? AVAudioPlayer(contentsOf: url)
  player?.prepareToPlay()
  player?.play()
}
</code>```

Title: how to add background music

Body:
The duplicate answer does not works at all

import Cocoa
    import AVFoundation

    var error: NSError?

    println("Hello, Audio!")
    var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file
    var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error)
    if midi == nil {
        if let e = error {
            println("AVMIDIPlayer failed: " + e.localizedDescription)
        }
    }
    midi.play(nil)
    while midi.playing {
        // Spin (yeah, that's bad!)
    }

Body:
The mp3 file must be in the Resources folder.

You play an mp3 with code like this (not the MIDI player):

if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
  let player = try? AVAudioPlayer(contentsOf: url)
  player?.prepareToPlay()
  player?.play()
}


问:
Observable pattern in Remote EJB
I have 2 applications. One 'main' and a second one with a Remote EJB. The first application calls the Remote EJB in the second one.

Now I want to implement the Observable pattern. But it doesn't seem to work cross-application.

So I want my Observable inside the second application, and my Observers in the first. When I try it, it doesn't seem to work. It only works if I make the Observable and Observers in the same application.

I got another solution, but I think it's dirty. I could use a MDB inside the second application, and publish a message on a Topic, and then consume those messages inside the first application. But then again, that seems kinda dirty.

I'm using JEE7 on a Payara 4.1.1.171 server.

Edit:
Because I figured out that triggered Events don't exit an EAR file, I'm now using the MDB method. But that still does not work.
More information, this is the package structure of the EAR file.

```<code>my-application.ear
+--- common-ejb.jar (EJB)
|       +--- MessageDrivenBean.java (Triggers the event)
+--- my-application.jar (EJB)
+--- my-application.war (WEB)
        +--- WEB-INF
                +--- lib
                |       +--- common-web.jar (Resources WEB jar)
                |           +--- SessionBean1 to receive the events
                +--- classes
                        +--- SessionBean2 to receive the events
</code>```

As you can see there are 2 session beans to receive the events, but none of the 2 actually receive them.

答:
Given a message driven bean:

```<code>@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:jboss/queue/SampleQueue")
})
public class EventListener implements MessageListener {

    @Inject
    @Any
    Event<MyEvent> loggedInEvent;

    @Override
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            try {
                ObjectMessage objectMessage = (ObjectMessage) message;
                loggedInEvent.fire(((MyEvent) objectMessage.getObject()));
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

where MyEvent is a simple POJO:

```<code>public class MyEvent implements Serializable {

    private final String payload;

    public MyEvent(String payload) {
        this.payload = payload;
    }

    public String getPayload() {
        return payload;
    }
}
</code>```

then this @SessionScoped bean:

```<code>@SessionScoped
public class EventHandler {

    public void handleEvent(@Observes MyEvent myEvent) {
        System.out.println(myEvent.getPayload());
    }
}
</code>```

prints the payload String when a MyEvent object is sent to the queue associated with the EventListener

Any number of observers can be provided.

Title: Observable pattern in Remote EJB

Body:
I have 2 applications. One 'main' and a second one with a Remote EJB. The first application calls the Remote EJB in the second one.

Now I want to implement the Observable pattern. But it doesn't seem to work cross-application.

So I want my Observable inside the second application, and my Observers in the first. When I try it, it doesn't seem to work. It only works if I make the Observable and Observers in the same application.

I got another solution, but I think it's dirty. I could use a MDB inside the second application, and publish a message on a Topic, and then consume those messages inside the first application. But then again, that seems kinda dirty.

I'm using JEE7 on a Payara 4.1.1.171 server.

Edit:
Because I figured out that triggered Events don't exit an EAR file, I'm now using the MDB method. But that still does not work.
More information, this is the package structure of the EAR file.

my-application.ear
+--- common-ejb.jar (EJB)
|       +--- MessageDrivenBean.java (Triggers the event)
+--- my-application.jar (EJB)
+--- my-application.war (WEB)
        +--- WEB-INF
                +--- lib
                |       +--- common-web.jar (Resources WEB jar)
                |           +--- SessionBean1 to receive the events
                +--- classes
                        +--- SessionBean2 to receive the events

As you can see there are 2 session beans to receive the events, but none of the 2 actually receive them.

Body:
Given a message driven bean:

@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:jboss/queue/SampleQueue")
})
public class EventListener implements MessageListener {

    @Inject
    @Any
    Event<MyEvent> loggedInEvent;

    @Override
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            try {
                ObjectMessage objectMessage = (ObjectMessage) message;
                loggedInEvent.fire(((MyEvent) objectMessage.getObject()));
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

where MyEvent is a simple POJO:

public class MyEvent implements Serializable {

    private final String payload;

    public MyEvent(String payload) {
        this.payload = payload;
    }

    public String getPayload() {
        return payload;
    }
}

then this @SessionScoped bean:

@SessionScoped
public class EventHandler {

    public void handleEvent(@Observes MyEvent myEvent) {
        System.out.println(myEvent.getPayload());
    }
}

prints the payload String when a MyEvent object is sent to the queue associated with the EventListener

Any number of observers can be provided.


问:
Sorting a map of keys and values please to order a list in ES6 with Lodash (Keeping Firebase Key: UID)?
I'm currently trying to sort a list of employees in order of names but I'm having difficulty in such.

I'm using React-Native, with ES6, Lodash and firebase.

Firebase structure appears as:

The state.employees structure appears as:

{"-KgMYnBrqXCIPqjs0n7x":{"name":"James","phone":"123766","shift":"Monday"},  "-KgRiK6qiJsoZ_HBXt7K":{"name":"Nick","phone":"123767","shift":"Tuesday"},"-KgRiM77VTOejvYPWPIp":{"name":"Henry","phone":"123","shift":"Thursday"},"-KgRiOaN14OeSjaYWb1O":{"name":"Charlie","phone":"5643","shift":"Saturday"}}

and continues with more employees each having a UID and then properties such as name, phone and shift.

Although I am able to order the list with _.orderBy provided by Lodash, it appears that when doing so the UID as the key provided by firebase is removed when applied say before _.map.

This is what I currently have which orders but the UID is removed, the _.map works fine keeping the UID with the properties but is unordered.

```<code>const mapStateToProps = state => {
    const sortedEmployees = _.orderBy(
        state.employees,
        [employee => employee.name.toLowerCase()]
    );
    const employees = _.map(sortedEmployees, (val, uid) => {
        return { ...val, uid };
    });

    return { employees };
};
</code>```

Thanks very much

答:
_.orderBy(collection, [iteratees=[_.identity]], [orders]) https://lodash.com/docs/4.17.4#orderBy

It seems when lodash maps over collection of type Object, it omits its key.
One way to fix would be to convert the collection of object from firebase response to an array . Ex:

```<code>const arrWithKeys = Object.keys(state.employees).map((key) => {
    return {
      key,
      ...state.employees[key]
    }
});
</code>```

and then use

```<code>const sortedEmployees = _.orderBy(
        arrWithKeys,
        [employee => employee.name.toLowerCase()]
    );
</code>```

You can also use firebase sorting in your firebase query

https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data

Body:
I'm currently trying to sort a list of employees in order of names but I'm having difficulty in such.

I'm using React-Native, with ES6, Lodash and firebase.

Firebase structure appears as:

The state.employees structure appears as:

{"-KgMYnBrqXCIPqjs0n7x":{"name":"James","phone":"123766","shift":"Monday"},  "-KgRiK6qiJsoZ_HBXt7K":{"name":"Nick","phone":"123767","shift":"Tuesday"},"-KgRiM77VTOejvYPWPIp":{"name":"Henry","phone":"123","shift":"Thursday"},"-KgRiOaN14OeSjaYWb1O":{"name":"Charlie","phone":"5643","shift":"Saturday"}}

and continues with more employees each having a UID and then properties such as name, phone and shift.

Although I am able to order the list with _.orderBy provided by Lodash, it appears that when doing so the UID as the key provided by firebase is removed when applied say before _.map.

This is what I currently have which orders but the UID is removed, the _.map works fine keeping the UID with the properties but is unordered.

const mapStateToProps = state => {
    const sortedEmployees = _.orderBy(
        state.employees,
        [employee => employee.name.toLowerCase()]
    );
    const employees = _.map(sortedEmployees, (val, uid) => {
        return { ...val, uid };
    });

    return { employees };
};

Thanks very much

Body:
_.orderBy(collection, [iteratees=[_.identity]], [orders]) https://lodash.com/docs/4.17.4#orderBy

It seems when lodash maps over collection of type Object, it omits its key.
One way to fix would be to convert the collection of object from firebase response to an array . Ex:

const arrWithKeys = Object.keys(state.employees).map((key) => {
    return {
      key,
      ...state.employees[key]
    }
});

and then use

const sortedEmployees = _.orderBy(
        arrWithKeys,
        [employee => employee.name.toLowerCase()]
    );

You can also use firebase sorting in your firebase query

https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data


问:
Update buffer and reset the locking-mode back to original one
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

```<code>DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.
</code>```

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

答:
You can't actually unlock a record like that when you're in a transaction. If you try, the exclusive lock becomes a limbo lock until the transaction ends and the changes are committed to the database. This is to prevent data integrity problems. If you're looking at the _Lock-Flags field, the limbo lock will be an "L". You can also use Promon to check the lock table status.

The transaction may be scoped to different procedures, depending on how you lock and update records. You can see if you're in a transaction by sticking this line in your code:

```<code>MESSAGE TRANSACTION VIEW-AS ALERT-BOX.
</code>```

Here's the OpenEdge documentation on record locking and transaction scoping:
https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/gsabl/handling-data-and-locking-records.html#

Body:
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

Body:
You can't actually unlock a record like that when you're in a transaction. If you try, the exclusive lock becomes a limbo lock until the transaction ends and the changes are committed to the database. This is to prevent data integrity problems. If you're looking at the _Lock-Flags field, the limbo lock will be an "L". You can also use Promon to check the lock table status.

The transaction may be scoped to different procedures, depending on how you lock and update records. You can see if you're in a transaction by sticking this line in your code:

MESSAGE TRANSACTION VIEW-AS ALERT-BOX.

Here's the OpenEdge documentation on record locking and transaction scoping:
https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/gsabl/handling-data-and-locking-records.html#


问:
Bulk insert from Excel to SQLite without TXT or CSV file
I have a problem and I hope to get some input from any of you.

Basically, I need to write a code in VBA which enables me to take a table of data from excel to sqlite.

I have managed to do it using this code:

Sub Scrivi()
    Dim objConnection As Object, objRecordset As Object
    Dim strDatabase As String

    Set objConnection = CreateObject("ADODB.Connection")

    strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

    Query = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code'));"
    riga = 3
    colonna = 1
    While Not (IsNull(ActiveSheet.Cells(row, column).Value) Or IsEmpty(ActiveSheet.Cells(row, column).Value))
        Query = Query & "insert into FUND values('" & Cells(row, column) & "','" & Cells(row, column + 1) & "','" & Cells(row, column + 2) & "');"
        row = row + 1
    Wend

    objConnection.Open strDatabase
    objConnection.Execute Query
    objConnection.Close
End Sub
```

Now I would like to change the iterative part in which I say row = row + 1 with a sort of bulk insert in which the program takes the whole table instead of doing it row by row.

I do not want a creation of csv/txt file if it is possible.

Thank you very much, any input would be appreciated.

答:
A very basic level solution can be through first building the complete query for bulk insert and then execute the query in one go.

For Example -

insert into FUND values(val1, val2);
insert into FUND values(val3, val4);

can be replaced with -
insert into FUND values(val1, val2),(val3, val4)

Body:
I have a problem and I hope to get some input from any of you.

Basically, I need to write a code in VBA which enables me to take a table of data from excel to sqlite.

I have managed to do it using this code:

Sub Scrivi()
    Dim objConnection As Object, objRecordset As Object
    Dim strDatabase As String

    Set objConnection = CreateObject("ADODB.Connection")

    strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

    Query = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code'));"
    riga = 3
    colonna = 1
    While Not (IsNull(ActiveSheet.Cells(row, column).Value) Or IsEmpty(ActiveSheet.Cells(row, column).Value))
        Query = Query & "insert into FUND values('" & Cells(row, column) & "','" & Cells(row, column + 1) & "','" & Cells(row, column + 2) & "');"
        row = row + 1
    Wend

    objConnection.Open strDatabase
    objConnection.Execute Query
    objConnection.Close
End Sub

Now I would like to change the iterative part in which I say row = row + 1 with a sort of bulk insert in which the program takes the whole table instead of doing it row by row.

I do not want a creation of csv/txt file if it is possible.

Thank you very much, any input would be appreciated.


问:
resizing multidimensional vector
How to resize multidimensional vector such as:

```<code>  vector <vector <vector <custom_type> > > array;
</code>```

For example, I need array[3][5][10]?

答:
I did it))</p>

```<code>array.resize(3);
for (int i = 0; i < 3; i++)
{
    array[i].resize(5);
    for (int j = 0; j < 5; j++)
    {
       array[i][j].resize(10);
    }
}
</code>```

Title: resizing multidimensional vector

Body:
How to resize multidimensional vector such as:

  vector <vector <vector <custom_type> > > array;

For example, I need array[3][5][10]?

Body:
I did it))

array.resize(3);
for (int i = 0; i < 3; i++)
{
    array[i].resize(5);
    for (int j = 0; j < 5; j++)
    {
       array[i][j].resize(10);
    }
}


问:
DataAnnotations - Disallow Numbers, or only allow given strings
Is it possible to use ASP.NET MVC 2's DataAnnotations to only allow characters (no number), or even provide a whitelist of allowed strings? Example?</p>

答:
You can write your own validator that has better performance than a regular expression.

Here I wrote a whitelist validator for int properties:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Utils
{
    /// <summary>
    /// Define an attribute that validate a property againts a white list
    /// Note that currently it only supports int type
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class WhiteListAttribute : ValidationAttribute
    {
        /// <summary>
        /// The White List
        /// </summary>
        public IEnumerable<int> WhiteList
        {
            get;
        }

        /// <summary>
        /// The only constructor
        /// </summary>
        /// <param name="whiteList"></param>
        public WhiteListAttribute(params int[] whiteList)
        {
            WhiteList = new List<int>(whiteList);
        }

        /// <summary>
        /// Validation occurs here
        /// </summary>
        /// <param name="value">Value to be validate</param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            return WhiteList.Contains((int)value);
        }

        /// <summary>
        /// Get the proper error message
        /// </summary>
        /// <param name="name">Name of the property that has error</param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            return $"{name} must have one of these values: {String.Join(",", WhiteList)}";
        }

    }
}
</code>```

Sample Use:

```<code>[WhiteList(2, 4, 5, 6)]
public int Number { get; set; }
</code>```

Body:
You can write your own validator that has better performance than a regular expression.

Here I wrote a whitelist validator for int properties:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Utils
{
    /// <summary>
    /// Define an attribute that validate a property againts a white list
    /// Note that currently it only supports int type
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class WhiteListAttribute : ValidationAttribute
    {
        /// <summary>
        /// The White List
        /// </summary>
        public IEnumerable<int> WhiteList
        {
            get;
        }

        /// <summary>
        /// The only constructor
        /// </summary>
        /// <param name="whiteList"></param>
        public WhiteListAttribute(params int[] whiteList)
        {
            WhiteList = new List<int>(whiteList);
        }

        /// <summary>
        /// Validation occurs here
        /// </summary>
        /// <param name="value">Value to be validate</param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            return WhiteList.Contains((int)value);
        }

        /// <summary>
        /// Get the proper error message
        /// </summary>
        /// <param name="name">Name of the property that has error</param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            return $"{name} must have one of these values: {String.Join(",", WhiteList)}";
        }

    }
}

Sample Use:

[WhiteList(2, 4, 5, 6)]
public int Number { get; set; }


问:
webpack error warning in png svg deprecated
I have a very strange error. I got this exact same here mentioned here

Webpack 2: WARNING in .png, .svg, .. DEPRECATED. Configure optipng's optimizationLevel option in it's own options. (optipng.optimizationLevel)

Ii impleted the solution and now my webpack looks like this

https://codepaste.net/8owse4

But now i get this error

```<code>/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:60
    throw new Error("Element from loaders list should have one of the fields 'loader' or 'loaders'");
    ^
</code>```

Error: Element from loaders list should have one of the fields 'loader' or 'loaders'

So, I am in kind of loop. I am using webpack 2. I understand I have to reconfigure webpack . But, its kind of loop. Its just not working. Can someone help me out.

答:
Looking over the migration guide for Webpack 2 I think that error is coming from module.loaders needing to be module.rules.
https://webpack.js.org/guides/migrating/

I took a pass at migrating your config file.

```<code>var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './src/app.js'
    },
    output: {
        filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map'
    },
    devtool: '#source-map',
    //loaders
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: '/node_modules/',
                loader: 'babel-loader',
                options: {
                    presets: ['stage-0', 'react', 'es2015'],
                    plugins: ['transform-decorators-legacy', 'transform-class-properties']
                }
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(eot|svg|ttf|woff2?)$/,
                loader: 'file?name=public/fonts/[name].[ext]'
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'assets/[name].[ext]'
                        }
                    },
                    {
                        loader: 'image-webpack-loader',
                        options: {
                            mozjpeg: {
                                progressive: true
                            },
                            gifsicle: {
                                interlaced: true
                            },
                            optipng: {
                                optimizationLevel: 7
                            }
                        }
                    }
                ]
            }
        ]
    }
};
</code>```

Body:
I have a very strange error. I got this exact same here mentioned here

Webpack 2: WARNING in .png, .svg, .. DEPRECATED. Configure optipng's optimizationLevel option in it's own options. (optipng.optimizationLevel)

Ii impleted the solution and now my webpack looks like this

https://codepaste.net/8owse4

But now i get this error

/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:60
    throw new Error("Element from loaders list should have one of the fields 'loader' or 'loaders'");
    ^

Error: Element from loaders list should have one of the fields 'loader' or 'loaders'

So, I am in kind of loop. I am using webpack 2. I understand I have to reconfigure webpack . But, its kind of loop. Its just not working. Can someone help me out.

Body:
Looking over the migration guide for Webpack 2 I think that error is coming from module.loaders needing to be module.rules.
https://webpack.js.org/guides/migrating/

I took a pass at migrating your config file.

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './src/app.js'
    },
    output: {
        filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map'
    },
    devtool: '#source-map',
    //loaders
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: '/node_modules/',
                loader: 'babel-loader',
                options: {
                    presets: ['stage-0', 'react', 'es2015'],
                    plugins: ['transform-decorators-legacy', 'transform-class-properties']
                }
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(eot|svg|ttf|woff2?)$/,
                loader: 'file?name=public/fonts/[name].[ext]'
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'assets/[name].[ext]'
                        }
                    },
                    {
                        loader: 'image-webpack-loader',
                        options: {
                            mozjpeg: {
                                progressive: true
                            },
                            gifsicle: {
                                interlaced: true
                            },
                            optipng: {
                                optimizationLevel: 7
                            }
                        }
                    }
                ]
            }
        ]
    }
};


问:
Joining three tables w/user input
I have three tables, A, B, C. Table B has foreign keys into both A & C. A & C don't have keys into each other.

I'm trying to write a query where I get every hit from a column in Table C whose primary key (foreign key in B) matches a primary key from Table A (also a foreign key in B). A wrinkle is that I am trying to get this info based on a user input, which will be a separate column in Table A.

Example:

```<code>TABLE A
-------
aID    aName
1      Squeakers
2      Formations
3      Hutsis
4      Pms

TABLE B
-------
bID    aID    cID
1      1      27930
2      1      21405
3      1      24013
4      2      21111
5      1      34100
6      1      20841
7      4      30001

TABLE C
-------
cID      cName
21405    Silver Flyer
27930    Babs McGee
30001    Jimmy McGill
24013    Fletcher Mason
21111    Spike Fester
34100    Hope Sisco
20841    Ellis Traeger
</code>```

So I want a user to put in ‘Squeakers’ and then get something that looks like:

```<code>Squeakers – Babs McGee, Silver Flyer, Fletcher Mason, Hope Sisco, Ellis Trager
</code>```

I've been stuck on this for multiple days and can't figure out the syntax. I'm not sure if I need a sub-query or if it's not all INNER JOINS?

答:
You can use JOIN and GROUP_CONCAT() to join all tables and get all cName in one row.

Try this:

```<code>SELECT GROUP_CONCAT(C.cName) AS cNames
FROM TableA A
INNER JOIN TableB B ON A.aID = B.aID
INNER JOIN TableC C ON B.cID = C.cID
WHERE A.aName = 'Squeakers';
</code>```

Title: Joining three tables w/user input

Body:
I have three tables, A, B, C. Table B has foreign keys into both A & C. A & C don't have keys into each other.

I'm trying to write a query where I get every hit from a column in Table C whose primary key (foreign key in B) matches a primary key from Table A (also a foreign key in B). A wrinkle is that I am trying to get this info based on a user input, which will be a separate column in Table A.

Example:

TABLE A
-------
aID    aName
1      Squeakers
2      Formations
3      Hutsis
4      Pms

TABLE B
-------
bID    aID    cID
1      1      27930
2      1      21405
3      1      24013
4      2      21111
5      1      34100
6      1      20841
7      4      30001

TABLE C
-------
cID      cName
21405    Silver Flyer
27930    Babs McGee
30001    Jimmy McGill
24013    Fletcher Mason
21111    Spike Fester
34100    Hope Sisco
20841    Ellis Traeger

So I want a user to put in ‘Squeakers’ and then get something that looks like:

Squeakers – Babs McGee, Silver Flyer, Fletcher Mason, Hope Sisco, Ellis Trager

I've been stuck on this for multiple days and can't figure out the syntax. I'm not sure if I need a sub-query or if it's not all INNER JOINS?

Body:
You can use JOIN and GROUP_CONCAT() to join all tables and get all cName in one row.

Try this:

SELECT GROUP_CONCAT(C.cName) AS cNames
FROM TableA A
INNER JOIN TableB B ON A.aID = B.aID
INNER JOIN TableC C ON B.cID = C.cID
WHERE A.aName = 'Squeakers';


问:
Is there a way to retrieve single row from database as key value only in laravel
can i retrieve single row from database like this in Laravel</p>

```<code>["name"=>"jhon",
"age"=>"18"
]
</code>```

答:
You can also use Eloquent Collection methods to transform it however you want.</p>

```<code>$people = User::where('name', 'John Smith')->get()->map(function ($person) {
    return [
        'id'   => $person->id,
        'name' => $person->name
    ];
});
</code>```

Body:
can i retrieve single row from database like this in Laravel

["name"=>"jhon",
"age"=>"18"
]

Body:
You can also use Eloquent Collection methods to transform it however you want.

$people = User::where('name', 'John Smith')->get()->map(function ($person) {
    return [
        'id'   => $person->id,
        'name' => $person->name
    ];
});