问:
Ninject: No Matching bindings are available
I am facing the same issue that many have faced before: the dreaded no matching binding.

Here is my registration logic

```<code>    static Bootstrapper()
    {
        Container = new StandardKernel();

        var dialogService = new DialogService();
        var mainWindow = new MainWindow(Messenger.Default, dialogService);
        dialogService.Intialize(mainWindow.DialogContainer);

        Container.Bind<MainWindow>().ToConstant(mainWindow);
        Container.Bind<IDialogService>().ToConstant(dialogService);
        Container.Bind<ILogger>().ToMethod((ctx) => LogManager.GetLogger("Main"));
        Container.Bind<IMessenger>().ToConstant(Messenger.Default);
        Container.Bind<IEntityService>().To<EntityService>();
        Container.Bind<EntityMasterDetailViewModel>().To<EntityMasterDetailViewModel>().InSingletonScope();
        Container.Bind<MainViewModel>().To<MainViewModel>().InSingletonScope();
    }
</code>```

And the issue is raised when resolving EntityMasterDetailViewModel

```<code>    public EntityMasterDetailViewModel(
        IDialogService dialog,
        IEntityService service)
    {
        _service = service;
        _dialog = dialog;
    }
</code>```

That is the only constructor on that class. I also eliminated the possibility of having multiple container(using readonly static).

I can't figure out what is wrong with the registration of the class. All of its dependency have been defined in the container.

Right now I would get the following error:

```<code>  Error activating IDialogService
  No matching bindings are available, and the type is not self-bindable.
  Activation path:
  2) Injection of dependency IDialogService into parameter dialog of
  constructor of type EntityMasterDetailViewModel
  1) Request for EntityMasterDetailViewModel
</code>```

Can anyone spot anything wrong?

Cheers,

EDIT 1

I can resolve both dependencies: Container.Get<IDialogService>() and Container.Get<IEntityService>() both returns the correct instance. So it must be the way I register EntityMasterDetailViewModel. I tried a few alternatives but none worked:

```<code>     Container.Bind<EntityMasterDetailViewModel>().ToSelf().InSingletonScope();
     Container.Bind<EntityMasterDetailViewModel>().ToMethod(_ => Container.Get<Entity<asterDetailViewModel>()).InSingletonScope();
</code>```

答:
Thank you for your comments, they gave me a hint on what went wrong: I was using static constructor incorrectly, thus the kernel was not initialized properly while calls to Get<> were issued.

Really what I wanted to implement was a singleton. So I switched things around for the correct pattern. This time, all the registrations/bindings happened before the first call to Get<>(); and I no longer get the exception/error.

Body:
I am facing the same issue that many have faced before: the dreaded no matching binding.

Here is my registration logic

    static Bootstrapper()
    {
        Container = new StandardKernel();

        var dialogService = new DialogService();
        var mainWindow = new MainWindow(Messenger.Default, dialogService);
        dialogService.Intialize(mainWindow.DialogContainer);

        Container.Bind<MainWindow>().ToConstant(mainWindow);
        Container.Bind<IDialogService>().ToConstant(dialogService);
        Container.Bind<ILogger>().ToMethod((ctx) => LogManager.GetLogger("Main"));
        Container.Bind<IMessenger>().ToConstant(Messenger.Default);
        Container.Bind<IEntityService>().To<EntityService>();
        Container.Bind<EntityMasterDetailViewModel>().To<EntityMasterDetailViewModel>().InSingletonScope();
        Container.Bind<MainViewModel>().To<MainViewModel>().InSingletonScope();
    }

And the issue is raised when resolving EntityMasterDetailViewModel

    public EntityMasterDetailViewModel(
        IDialogService dialog,
        IEntityService service)
    {
        _service = service;
        _dialog = dialog;
    }

That is the only constructor on that class. I also eliminated the possibility of having multiple container(using readonly static).

I can't figure out what is wrong with the registration of the class. All of its dependency have been defined in the container.

Right now I would get the following error:

  Error activating IDialogService
  No matching bindings are available, and the type is not self-bindable.
  Activation path:
  2) Injection of dependency IDialogService into parameter dialog of
  constructor of type EntityMasterDetailViewModel
  1) Request for EntityMasterDetailViewModel

Can anyone spot anything wrong?

Cheers,

EDIT 1

I can resolve both dependencies: Container.Get<IDialogService>() and Container.Get<IEntityService>() both returns the correct instance. So it must be the way I register EntityMasterDetailViewModel. I tried a few alternatives but none worked:

     Container.Bind<EntityMasterDetailViewModel>().ToSelf().InSingletonScope();
     Container.Bind<EntityMasterDetailViewModel>().ToMethod(_ => Container.Get<Entity<asterDetailViewModel>()).InSingletonScope();


来源: stackexchange

问:
perl6 User-defined comparison function in set opertions
Perl6 documentation indicated that when comparing two items in a set, === is used. This is quote from perl6 documentation:

Objects/values of any type are allowed as set elements. Within a Set,
  every element is guaranteed to be unique (in the sense that no two
  elements would compare positively with the === operator)

I am wondering if it is possible to use a user-defined function instead of ===? E.g., How can I use ~~ instead of === in determining whether 2 elements in a set are "equal".

The problem I am trying to solve is this: set A has some first names and some last names in any order but all lower case and no punctuation, and set B has a number of first names and last names mixed in any order, and there may be punctuation attached to the names and may be upper or lower cases. I want to know if a person in set A (represented as a subset of A with one specific first and last name) appears in set B. In this case, I cannot use === because of the letter cases and punctuation in set B.

If I can use ~~ instead of ===, the problem will be much simpler because I only need to determine if a subset of A is also a subset of B using ~~. This is similar to a "permutation match" problem I mentioned before.

Thank you very much !

答:
There are a couple ways, and I'll start with the easy/slow way. I'll use the == operator, but you can use any operation. If you want to iterate over the list/set, you can use first with whatever match logic you like, then check for .defined to confirm that you got a match. (If you want to be really careful or if your list contains undefined items, you should use the :p adverb so your output is a key/value pair, and that will be defined if and only if some matching element was found.)

For an example of sloppy matching using this technique, I'll search for a number in a list and set of IntStr:

```<code>say 4 ∈ ("3", "4"); # False, because the list doesn't contain the integer 4
say ("3", "4").first(* == 4, :p).defined; # True
say set("3", "4").keys.first(* == 4, :p).defined; # True
</code>```

You would have to benchmark to know whether this is as fast as checking set membership in a more conventional way. For a large set, the conventional ways should be faster, since hash lookup can be used. In some programming languages, iteration is faster than hashing until the list gets really big.

If you don't need to get the matching element, you can use junctions, which will do multiple checks in parallel:

```<code>say so ("3", "4").any() == 4; # True
</code>```

And you can use junctions to do subset testing as well, but since this is an O(m*n) operation (despite being auto-threaded), don't expect high performance when comparing two very large sets.

```<code>say so (2, 3).all() == ('1', '2', '3').any(); # True
say so (2, 3, 4).all() == ('1', '2', '3').any(); # False
</code>```

I used lists instead of sets above, since if you're not using the standard operators/methods, sets offer no speed or API advantage.

ContentLicense: CC BY-SA 3.0

Body:
There are a couple ways, and I'll start with the easy/slow way. I'll use the == operator, but you can use any operation. If you want to iterate over the list/set, you can use first with whatever match logic you like, then check for .defined to confirm that you got a match. (If you want to be really careful or if your list contains undefined items, you should use the :p adverb so your output is a key/value pair, and that will be defined if and only if some matching element was found.)

For an example of sloppy matching using this technique, I'll search for a number in a list and set of IntStr:

say 4 ∈ ("3", "4"); # False, because the list doesn't contain the integer 4
say ("3", "4").first(* == 4, :p).defined; # True
say set("3", "4").keys.first(* == 4, :p).defined; # True

You would have to benchmark to know whether this is as fast as checking set membership in a more conventional way. For a large set, the conventional ways should be faster, since hash lookup can be used. In some programming languages, iteration is faster than hashing until the list gets really big.

If you don't need to get the matching element, you can use junctions, which will do multiple checks in parallel:

say so ("3", "4").any() == 4; # True

And you can use junctions to do subset testing as well, but since this is an O(m*n) operation (despite being auto-threaded), don't expect high performance when comparing two very large sets.

say so (2, 3).all() == ('1', '2', '3').any(); # True
say so (2, 3, 4).all() == ('1', '2', '3').any(); # False

I used lists instead of sets above, since if you're not using the standard operators/methods, sets offer no speed or API advantage.


问:
Traversing an object in javascript and convert it in specific format
I have the following object structure:

```<code>{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}
</code>```

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

```<code>const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");
</code>```

My expected output should be

```<code>[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]
</code>```

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output

答:
You should pass both the path and the accumulated array acc to the recursive call of getFinalNode:

const getFinalNode = function(data, acc = [], path = "") {         // default values for acc and path, so we won't bother ourselves with that
    for(let key in data) {                                         // for each key in the object/array data
        if(data.hasOwnProperty(key)) {                             // if this is an own property
            if(data[key] && typeof(data[key]) === "object") {      // if the value of the current property is an object/array (not null: typeof null === "object")
                getFinalNode(data[key], acc, path + "/" + key);    // then traverse it, passing acc to add to what we already have
            } else {                                               // otherwise
                acc.push({                                         // make a leaf object and push it to the accumulator acc
                    path: path.slice(1) + "/" + key,               // slice to remove the first "/" from path
                    name: key,
                    value: data[key]
                });
            }
        }
    }
    return acc;
}

let data = {"a":{"b":"abc","c":[{"d":"pqr","e":true},{"f":1,"e":["xyz",1]}]}};

let result = getFinalNode(data);
console.log(result);```

Body:
I have the following object structure:

{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");

My expected output should be

[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output


问:
Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
Migration error on Laravel 5.4 with php artisan make:auth

[Illuminate\Database\QueryException]                                                                                SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter tabl    e users add unique users_email_unique(email))

[PDOException]                                                                                SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

答:
In order to avoid changing anything in your code, simply update your MySQL server to at least 5.7.7

Reference this for more info : https://laravel-news.com/laravel-5-4-key-too-long-error


问:
Convert JSON formated String to JsonObject with Jayrock
I have a request parameter in my ASP.NET app. that is in JSON format, and I was wondering if there is a good (quick and easy) way to convert a JSON string to a Jayrocks JsonObject, so I can easily extract key-value pairs without the need to manually parse the string?</p>

答:
Assuming json is the variable containing JSON text, use Jayrock.Json.Conversion.JsonConvert.Import(json). What you will get back in return is either a JsonObject, JsonArray, JsonNumber, System.String, System.Boolean or a null reference depending on the root JSON value in the source JSON text. If you know it is going to be a JSON object for sure then you can safely cast the return value or use JsonConvert.Import<JsonObject>(json).

I would discourage working against JsonObject directly unless you particularly depend on one of its features. You should just pretend the JSON object you get back is a dictionary; either IDictionary or IDictionary<string, object>. With the latest version for .NET Framework 4, you can also work with a JsonObject as a dynamic object.

ContentLicense: CC BY-SA 2.5


问:
Change a column only if a certain condition is met, otherwise don't modify it
Sample dataframe:

```<code>set.seed(1)
df <- data.frame(x = runif(10),
                 y = runif(10),
                 group = factor(sample(LETTERS[1:10], 10, replace = TRUE)))
</code>```

I want to set x equal to y if group == "A", otherwise I don't want to modify it. For now I found this solution:

```<code>df %<>% mutate(x =  ifelse(group == "A", y, x))
</code>```

Is this a good solution or are there better/faster ways?

答:
I think that is a good solution

You could alternately use dplyr's if_else.

There is also case_when in dplyr but that seems overkill here.

Also

```<code>df %>% mutate(x = y * (A == "group") + x * (A != "group")
</code>```

but I would not use that approach here.

case_when and if_else are dplyr functions so if you were thinking of using this code with a database backend then they would more likely work than non-dplyr functions.

Update: I had been thinking about replace as well but in this situation it does not work as nicely. You would have to write:

```<code>df %>% mutate(x = replace(x, group == "A", y[group =="A"]))
</code>```

which seems quite ugly.

Body:
Sample dataframe:

set.seed(1)
df <- data.frame(x = runif(10),
                 y = runif(10),
                 group = factor(sample(LETTERS[1:10], 10, replace = TRUE)))

I want to set x equal to y if group == "A", otherwise I don't want to modify it. For now I found this solution:

df %<>% mutate(x =  ifelse(group == "A", y, x))

Is this a good solution or are there better/faster ways?

Body:
I think that is a good solution

You could alternately use dplyr's if_else.

There is also case_when in dplyr but that seems overkill here.

Also

df %>% mutate(x = y * (A == "group") + x * (A != "group")

but I would not use that approach here.

case_when and if_else are dplyr functions so if you were thinking of using this code with a database backend then they would more likely work than non-dplyr functions.

Update: I had been thinking about replace as well but in this situation it does not work as nicely. You would have to write:

df %>% mutate(x = replace(x, group == "A", y[group =="A"]))

which seems quite ugly.


问:
JS FileSaver non interactive
I have an array of file to save by using a loop and i generate the name of each file. I want to save file directly (in non interactive way) without asking me to confirm. How can i do ?
Here is my code for saving file</p>

```<code>var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');

var xhr = new XMLHttpRequest();

xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);

xhr.onreadystatechange = function () {
    if (xhr.readyState == xhr.DONE) {
        var filesaver = require('file-saver');
        filesaver.saveAs(xhr.response, nameFile); // nameFile the name of file to be saved
    }
};
xhr.send(); //Request is sent
</code>```

答:
Finally, i find a solution, instead of saving file, i write it by creating a new one.</p>

```<code>for (var i = 0; i < tabForm.length; i++) {

    var imgData = $('#affichageqr')[0].childNodes[1].childNodes[0].src;

    var data = imgData.replace(/^data:image\/\w+;base64,/, '');

    fs.writeFile(qrcode.getNomQRCode()+'.jpeg', data, {encoding: 'base64'}, function(err){
      if (err) {
        console.log('err', err);
      }
     console.log('success');
    });
  }
</code>```

Title: JS FileSaver non interactive

Body:
I have an array of file to save by using a loop and i generate the name of each file. I want to save file directly (in non interactive way) without asking me to confirm. How can i do ?
Here is my code for saving file

var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');

var xhr = new XMLHttpRequest();

xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);

xhr.onreadystatechange = function () {
    if (xhr.readyState == xhr.DONE) {
        var filesaver = require('file-saver');
        filesaver.saveAs(xhr.response, nameFile); // nameFile the name of file to be saved
    }
};
xhr.send(); //Request is sent

Body:
Finally, i find a solution, instead of saving file, i write it by creating a new one.

for (var i = 0; i < tabForm.length; i++) {

    var imgData = $('#affichageqr')[0].childNodes[1].childNodes[0].src;

    var data = imgData.replace(/^data:image\/\w+;base64,/, '');

    fs.writeFile(qrcode.getNomQRCode()+'.jpeg', data, {encoding: 'base64'}, function(err){
      if (err) {
        console.log('err', err);
      }
     console.log('success');
    });
  }


问:
404 while trying to make dockerized nginx serve static files mounted in a volume
I'm struggling to setup nginx inside a docker container. I basically have two containers:

a php:7-apache container that serves a dynamic website, including its static contents.

a nginx container, with a volume mounted inside it as a /home/www-data/static-content folder (I do this in my docker-compose.yml), to try to serve a static website (unrelated to the one served by the apache container).

I want to use the domain dynamic.localhost to serve my dynamic website, and static.localhost to serve my static website only made up of static files.

I have the following Dockerfile for my nginx container:

```<code>########## BASE #########

FROM nginx:stable

########## CONFIGURATION ##########

ARG DEBIAN_FRONTEND=noninteractive

ENV user www-data

COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./site.conf /etc/nginx/conf.d/default.conf

RUN touch /var/run/nginx.pid && \
    chown -R ${user}:${user} /var/run/nginx.pid && \
    chown -R www-data:www-data /var/cache/nginx

RUN chown -R ${user} /home/${user}/ && \
    chgrp -R ${user} /home/${user}/

USER ${user}
</code>```

As you see I'm using two configuration files for nginx: nginx.conf and site.conf.
Here is nginx.conf (it's not important because there is nothing special in it but if I'm doing something wrong just let me know):

```<code>worker_processes auto;
error_log /var/log/nginx/error.log debug;
pid       /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    sendfile on;
    keepalive_timeout 65;
    include /etc/nginx/conf.d/*.conf;
}
</code>```

And here is the file site.conf that I have been failing miserably at writing correctly for days now:

```<code>server {
    listen 8080;
    server_name static.localhost;
    root /home/www-data/static-content;

    location / {
        try_files $uri =404;
    }
}

server {
    listen 8080;
    server_name dynamic.localhost;

    location / {
        proxy_pass http://dynamic;
        proxy_redirect off;
        proxy_set_header Host $host:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Port 8080;
        proxy_set_header X-Forwarded-Host $host:8080;
    }
}
</code>```

(http://dynamic passes the request to the apache container that I name "dynamic").

So basically I keep getting 404 for whatever file I try to access in my static-content directory. E.g.:

static.localhost:8080/index.html should serve /home/www-data/static-content/index.html but I get 404 instead.

static.localhost:8080/css/style.css should serve /home/www-data/static-content/css/style.css but I get 404 too.

I tried various things, like writing try_files /home/www-data/static-content/$uri, but I didn't get any result. I read some parts of nginx documentation and searched on Stack Overflow but nothing that I found helped me. If I made a stupid mistake I apologize, but the only thing that I care about now is to get this to work, and to understand what I'm doing wrong.

Thanks

答:
I solved my problems by simply not using a volume for the static files but copying them in the container. I suspect it's a problem of permissions with the way the volume is mounted by docker-compose and the nginx process running as non-root.
It's not a perfect solution since I have to give up on using a volume but it'll do.</p>

Body:
I'm struggling to setup nginx inside a docker container. I basically have two containers:

a php:7-apache container that serves a dynamic website, including its static contents.

a nginx container, with a volume mounted inside it as a /home/www-data/static-content folder (I do this in my docker-compose.yml), to try to serve a static website (unrelated to the one served by the apache container).

I want to use the domain dynamic.localhost to serve my dynamic website, and static.localhost to serve my static website only made up of static files.

I have the following Dockerfile for my nginx container:

########## BASE #########

FROM nginx:stable

########## CONFIGURATION ##########

ARG DEBIAN_FRONTEND=noninteractive

ENV user www-data

COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./site.conf /etc/nginx/conf.d/default.conf

RUN touch /var/run/nginx.pid && \
    chown -R ${user}:${user} /var/run/nginx.pid && \
    chown -R www-data:www-data /var/cache/nginx

RUN chown -R ${user} /home/${user}/ && \
    chgrp -R ${user} /home/${user}/

USER ${user}

As you see I'm using two configuration files for nginx: nginx.conf and site.conf.
Here is nginx.conf (it's not important because there is nothing special in it but if I'm doing something wrong just let me know):

worker_processes auto;
error_log /var/log/nginx/error.log debug;
pid       /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    sendfile on;
    keepalive_timeout 65;
    include /etc/nginx/conf.d/*.conf;
}

And here is the file site.conf that I have been failing miserably at writing correctly for days now:

server {
    listen 8080;
    server_name static.localhost;
    root /home/www-data/static-content;

    location / {
        try_files $uri =404;
    }
}

server {
    listen 8080;
    server_name dynamic.localhost;

    location / {
        proxy_pass http://dynamic;
        proxy_redirect off;
        proxy_set_header Host $host:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Port 8080;
        proxy_set_header X-Forwarded-Host $host:8080;
    }
}

(http://dynamic passes the request to the apache container that I name "dynamic").

So basically I keep getting 404 for whatever file I try to access in my static-content directory. E.g.:

static.localhost:8080/index.html should serve /home/www-data/static-content/index.html but I get 404 instead.

static.localhost:8080/css/style.css should serve /home/www-data/static-content/css/style.css but I get 404 too.

I tried various things, like writing try_files /home/www-data/static-content/$uri, but I didn't get any result. I read some parts of nginx documentation and searched on Stack Overflow but nothing that I found helped me. If I made a stupid mistake I apologize, but the only thing that I care about now is to get this to work, and to understand what I'm doing wrong.

Thanks


问:
Create a program to ask a number and print all divisors
Below is my code:

```<code>num= int(input("Please enter number"))
lista= []

for i in range(1,100):
    if num%i ==0:
        lista.append(i)
print(i)
</code>```

But when I run the same, I get the below output:

```<code>Please enter number24
99

Process finished with exit code 0
</code>```

According to the above logic, my understanding is that the loop will iterate for 99 times because of the range given, and if the remainder is zero for "i", then it should be appended on the list. Not sure where and why my logic is wrong.

答:
You are printing just i, instead you need to print the complete list at end of loop.

You are iterating in the range of [1, 100) only for the divisors, however, to find all divisors with this naive approach, you would ideally need to iterate over range of [1, num). For example, 1000 is a divisor for 2000, but your approach would miss the case.

Instead of lista, you can use list_divisors as the variable name as it is more readable.

So your code becomes:

```<code>num = int(input("Please enter number"))
list_divisors = []

for i in range(1, num):
    if num % i ==0:
        list_divisors.append(i)
print(list_divisors)
</code>```

Body:
Below is my code:

num= int(input("Please enter number"))
lista= []

for i in range(1,100):
    if num%i ==0:
        lista.append(i)
print(i)

But when I run the same, I get the below output:

Please enter number24
99

Process finished with exit code 0

According to the above logic, my understanding is that the loop will iterate for 99 times because of the range given, and if the remainder is zero for "i", then it should be appended on the list. Not sure where and why my logic is wrong.

Body:
You are printing just i, instead you need to print the complete list at end of loop.

You are iterating in the range of [1, 100) only for the divisors, however, to find all divisors with this naive approach, you would ideally need to iterate over range of [1, num). For example, 1000 is a divisor for 2000, but your approach would miss the case.

Instead of lista, you can use list_divisors as the variable name as it is more readable.

So your code becomes:

num = int(input("Please enter number"))
list_divisors = []

for i in range(1, num):
    if num % i ==0:
        list_divisors.append(i)
print(list_divisors)


问:
AWS CLI S3 cp Not Recognizing Quoted Source and Target in Shell Script
New to shell scripting.  Trying to use shell script on RHEL 6.9 linux server to upload a file with whitespace in filename to AWS S3 with aws cli.  I have tried single and double quotes and have been reading aws cli links like http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html

Here is a simple version of my script with the problem:

```<code>#!/bin/bash
profile=" --profile XXXXXXX"
sourcefile=" '/home/my_login/data/batch4/Test File (1).zip'"
targetobject=" 's3://my-bucket/TestFolder/batch4/Test File (1).zip'"
service=" s3"
action=" cp"
encrypt=" --sse"
func="aws"
awsstring=$func$profile$service$action$sourcefile$targetobject$encrypt
echo $awsstring
$awsstring
</code>```

When I run I get:

```<code>$ ./s3copy.sh
aws --profile XXXXXXX s3 cp '/home/my_login/data/batch4/Test File (1).zip' 's3://my-bucket/TestFolder/batch4/Test File (1).zip' --sse

Unknown options: (1).zip','s3://my-bucket/TestFolder/batch4/Test,File,(1).zip'
</code>```

When I execute the $awsstring value from command line, it works:

```<code>$ aws --profile XXXXXXX s3 cp '/home/my_login/data/batch4/Test File (1).zip' 's3://my-bucket/TestFolder/batch4/Test File (1).zip' --sse
upload: data/batch4/Test File (1).zip to s3://my-bucket/TestFolder/batch4/Test File (1).zip
</code>```

aws cli does not seem to recognize the quotes in the shell script.  I need to quote the file names in my script, because I have white space in them.

Question: Why does the string execute correctly from the command line, but not from within the shell script?

答:
Use eval $awsstring. I faced similar issue. You can look at my answer - https://stackoverflow.com/a/47111888/2396539

On second thought having space in file name is not desirable and if you can control it , avoid it in the 1st place.

Body:
New to shell scripting.  Trying to use shell script on RHEL 6.9 linux server to upload a file with whitespace in filename to AWS S3 with aws cli.  I have tried single and double quotes and have been reading aws cli links like http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html

Here is a simple version of my script with the problem:

#!/bin/bash
profile=" --profile XXXXXXX"
sourcefile=" '/home/my_login/data/batch4/Test File (1).zip'"
targetobject=" 's3://my-bucket/TestFolder/batch4/Test File (1).zip'"
service=" s3"
action=" cp"
encrypt=" --sse"
func="aws"
awsstring=$func$profile$service$action$sourcefile$targetobject$encrypt
echo $awsstring
$awsstring

When I run I get:

$ ./s3copy.sh
aws --profile XXXXXXX s3 cp '/home/my_login/data/batch4/Test File (1).zip' 's3://my-bucket/TestFolder/batch4/Test File (1).zip' --sse

Unknown options: (1).zip','s3://my-bucket/TestFolder/batch4/Test,File,(1).zip'

When I execute the $awsstring value from command line, it works:

$ aws --profile XXXXXXX s3 cp '/home/my_login/data/batch4/Test File (1).zip' 's3://my-bucket/TestFolder/batch4/Test File (1).zip' --sse
upload: data/batch4/Test File (1).zip to s3://my-bucket/TestFolder/batch4/Test File (1).zip

aws cli does not seem to recognize the quotes in the shell script.  I need to quote the file names in my script, because I have white space in them.

Question: Why does the string execute correctly from the command line, but not from within the shell script?


问:
Call program from powershell.exe command and manipulate parameters
I'm trying to call an EXE file program that accepts command line parameters from PowerShell. One of the parameters I'm required to send is based on the string length of the parameters.

For example,

```<code>app.exe /param1:"SampleParam" /paramLen:"SampleParam".length
</code>```

When I run the above, or for example:

```<code>notepad.exe "SampleParam".length
</code>```

Notepad opens with the value 11 as expected.

I would like to achieve the same result when calling PowerShell from cmd / task scheduler.

For example,

```<code>powershell notepad.exe "SampleParam".length
</code>```

But when I do that I get "SampleParam".length literally instead of the "SampleParam".length calculated value.

The expected result was:

running notepad.exe 11

答:
Use the -Command parameter for powershell.exe:

```<code>powershell -Command "notepad.exe 'SampleParam'.length"
</code>```

Be careful with the "'s since they can be picked up by the Windows command processor. This will also work:

```<code>powershell -Command notepad.exe 'SampleParam'.length
</code>```

But this will not:

```<code>powershell -Command notepad.exe "SampleParam".length
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to call an EXE file program that accepts command line parameters from PowerShell. One of the parameters I'm required to send is based on the string length of the parameters.

For example,

app.exe /param1:"SampleParam" /paramLen:"SampleParam".length

When I run the above, or for example:

notepad.exe "SampleParam".length

Notepad opens with the value 11 as expected.

I would like to achieve the same result when calling PowerShell from cmd / task scheduler.

For example,

powershell notepad.exe "SampleParam".length

But when I do that I get "SampleParam".length literally instead of the "SampleParam".length calculated value.

The expected result was:

running notepad.exe 11

Body:
Use the -Command parameter for powershell.exe:

powershell -Command "notepad.exe 'SampleParam'.length"

Be careful with the "'s since they can be picked up by the Windows command processor. This will also work:

powershell -Command notepad.exe 'SampleParam'.length

But this will not:

powershell -Command notepad.exe "SampleParam".length


问:
cxGrid new record on last field Enter
I'm struggling to make a TcxGrid to append a new record whenever the user presses Enter key on last field of the current record, however I didn't find any property that might help me achieve this.

I tried setting the OnKeyDown event of the grid view(TcxGridDBTableView), with the following code

```<code>if Key = VK_RETURN then
  if PaymentViewBetragNetto.Focused then
    PaymentView.DataController.AppendRecord;
</code>```

however the code is not executed for some reason...

Any idea on how to append record on last field OnEnter event would be highly appreciated.

Thank you.

答:
Why not simple:</p>
```<code>View.OptionsBehavior.FocusCellOnCycle = True,
View.OptionBehavior.FocusFirstCellOnNewRecord = True,
View.OptionBehavior.GotoNextCellOnEnter = True,
View.OptionData.Appending = True
</code>```

Title: cxGrid new record on last field Enter

Body:
I'm struggling to make a TcxGrid to append a new record whenever the user presses Enter key on last field of the current record, however I didn't find any property that might help me achieve this.

I tried setting the OnKeyDown event of the grid view(TcxGridDBTableView), with the following code

if Key = VK_RETURN then
  if PaymentViewBetragNetto.Focused then
    PaymentView.DataController.AppendRecord;

however the code is not executed for some reason...

Any idea on how to append record on last field OnEnter event would be highly appreciated.

Thank you.

Body:
Why not simple:

View.OptionsBehavior.FocusCellOnCycle = True,
View.OptionBehavior.FocusFirstCellOnNewRecord = True,
View.OptionBehavior.GotoNextCellOnEnter = True,
View.OptionData.Appending = True


问:
JSON Parsing in Swift 3
Has anyone been able to find a way to parse through JSON files in Swift 3? I have been able to get the data to return but I am unsuccessful when it comes to breaking the data down into specific fields. I would post sample code but I've gone through so many different methods unsuccessfully and haven't saved any. The basic format I want to parse through is something like this. Thanks in advance.</p>

```<code>{
  "Language": {

    "Field":[
          {
          "Number":"976",
          "Name":"Test"
          },
          {
          "Number":"977",
          "Name":"Test"
          }
       ]
   }
}
</code>```

答:
JSON Parsing in swift 4 using Decodable Protocol :

I create a mocky file using your json object :

http://www.mocky.io/v2/5a280c282f0000f92c0635e6

Here is the code to parse the JSON :

Model Creation :

```<code>import UIKit

struct Item : Decodable {
// Properties must be the same name as specified in JSON , else it will return nil
var Number : String
var Name : String
}

struct Language : Decodable {
 var Field : [Item]
}

struct Result : Decodable {
 var Language : Language
}
</code>```

You can use optional in the model if you are uncertain that something might be missing in JSON file.

This is the parsing Logic :

```<code>class ViewController: UIViewController {

let url = "http://www.mocky.io/v2/5a280c282f0000f92c0635e6"

private func parseJSON() {

    guard let url = URL(string: url) else { return }

    let session = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        guard let result = try? JSONDecoder().decode(Result.self, from: data) else { return }
        print("\n\nResult : \(result)")
    }
    session.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    parseJSON()
}
}
</code>```

The Print Output :

```<code> Result : Result(Language: JSON_Parsing.Language(Field: [JSON_Parsing.Item(Number: "976", Name: "Test"), JSON_Parsing.Item(Number: "977", Name: "Test")]))
</code>```

This the github Project link. You can check.

Title: JSON Parsing in Swift 3

Body:
Has anyone been able to find a way to parse through JSON files in Swift 3? I have been able to get the data to return but I am unsuccessful when it comes to breaking the data down into specific fields. I would post sample code but I've gone through so many different methods unsuccessfully and haven't saved any. The basic format I want to parse through is something like this. Thanks in advance.

{
  "Language": {

    "Field":[
          {
          "Number":"976",
          "Name":"Test"
          },
          {
          "Number":"977",
          "Name":"Test"
          }
       ]
   }
}

Body:
JSON Parsing in swift 4 using Decodable Protocol :

I create a mocky file using your json object :

http://www.mocky.io/v2/5a280c282f0000f92c0635e6

Here is the code to parse the JSON :

Model Creation :

import UIKit

struct Item : Decodable {
// Properties must be the same name as specified in JSON , else it will return nil
var Number : String
var Name : String
}

struct Language : Decodable {
 var Field : [Item]
}

struct Result : Decodable {
 var Language : Language
}

You can use optional in the model if you are uncertain that something might be missing in JSON file.

This is the parsing Logic :

class ViewController: UIViewController {

let url = "http://www.mocky.io/v2/5a280c282f0000f92c0635e6"

private func parseJSON() {

    guard let url = URL(string: url) else { return }

    let session = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        guard let result = try? JSONDecoder().decode(Result.self, from: data) else { return }
        print("\n\nResult : \(result)")
    }
    session.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    parseJSON()
}
}

The Print Output :

 Result : Result(Language: JSON_Parsing.Language(Field: [JSON_Parsing.Item(Number: "976", Name: "Test"), JSON_Parsing.Item(Number: "977", Name: "Test")]))

This the github Project link. You can check.


问:
Java remote debugging - how can I keep debugger listening?
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

```<code>-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y
</code>```

Is it possible to keep the debugger listening?

答:
When setting up your run configuration, did you select the "Listen" Debugger mode?  The command line arguments you show look like the normal "Attach" settings, whereas the arguments for "Listen" look like this:
-agentlib:jdwp=transport=dt_socket,server=n,address=yourhost.yourdomain:5005, suspend=y,onthrow=<FQ exception class name>,onuncaught=<y/n>  (Specifically, your arguments are missing the address for the application - your CLI program - to connect to IDEA at on start-up.)

I read a post that suggests the "onthrow" argument may not be necessary for general debugging, but I haven't tried it myself.

Body:
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y

Is it possible to keep the debugger listening?


问:
Javascript syntax error in IE11 for sort function
I am sorting an Array with Javascript and it is working fine in Chrome, Firefox, Safari but in IE11 I am getting a syntax error. Anyone know what could be causing this? Here's my sort function:</p>

```<code>arr.sort((a, b) => b - a);
</code>```

答:
Internet Explorer 11 does not support the ES2015 feature Arrow Functions.

Either use the function syntax or incorporate a transpiler such as Babel or TypeScript into your toolchain.

Your code as transpiled by Babel

Your code as transpiled by TypeScript

Body:
I am sorting an Array with Javascript and it is working fine in Chrome, Firefox, Safari but in IE11 I am getting a syntax error. Anyone know what could be causing this? Here's my sort function:

arr.sort((a, b) => b - a);


问:
Obtaining JSON data with foreach in PHP
A site contains monthly data in a JSON format. This can be queried like so:

```<code>http://www.example.com?startdate=1-1-1985&enddate=31-1-1985
</code>```

I want to be able to run a script that will obtain the specific data I am looking for, starting from today's month, then work backward until null data is returned. Each month's value needs to add up. So far, this is what I've got:

```<code>//Build base URL:
$userid=$_GET['userid'];
$startdate=/*Beginning of today's month*/;
$enddate=/*End of today's month*/;
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;

//Set JSON variables:
$get=file_get_contents($url);
$json=json_decode($get);

//Set loop variables:
$value=0;
$month=0;

/*For each month from today backwards{
    $number=$json->integer;
    if($number!=null){
        $value=$value+$number;
        $month=$month+1;
    }else{
        break;
    }
}
echo $value;
echo $month;
*/
</code>```

The part I'm having problems with is the beginning of the fourth part. How do I run a loop that starts with the range of today's month, obtain $number, then repeat with the previous month, until it reaches a month that returns null?

答:
You could use the DateTime object and it's associated methods ( specifically sub in this case ) to count backwards by subtracting 1month at a time. An array stores the months/dates and the url is constructed using the variable counter $i

Initially this has a maximum backwards range of 20years ( which I guessed would be more than enough ) but it's easy to change.

```<code>$df='Y-m-d';
$userid=$_GET['userid'];

$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1M');

$ts=date( $df, strtotime( date('Y-m-1') ) );
$tf=date( $df, strtotime( date('Y-m-1'). ' - 20 years') );

$start=new DateTime( $ts, $timezone );
$end=new DateTime( $tf, $timezone );

$dates=array();
$i=0;

while( $start->sub( $interval ) > $end ){
    $dates[]=$start->format( $df );
    if( $i > 1 ){

        $startdate=$dates[ $i - 1 ];
        $enddate=$dates[ $i ];
        $url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
        echo $url,'<br />';

        /* uncomment when happy with mechanism */
        /*

        $data=file_get_contents( $url );
        if( $data ) ) {
            $json=json_decode( $data );
            #process.....
            break;
        }
        */
    }
    $i++;
}
</code>```

A snippet of the output

```<code>http://www.example.com?userid=bobodaclown&startdate=2017-10-01&enddate=2017-09-01
http://www.example.com?userid=bobodaclown&startdate=2017-09-01&enddate=2017-08-01
http://www.example.com?userid=bobodaclown&startdate=2017-08-01&enddate=2017-07-01
http://www.example.com?userid=bobodaclown&startdate=2017-07-01&enddate=2017-06-01
http://www.example.com?userid=bobodaclown&startdate=2017-06-01&enddate=2017-05-01
http://www.example.com?userid=bobodaclown&startdate=2017-05-01&enddate=2017-04-01
http://www.example.com?userid=bobodaclown&startdate=2017-04-01&enddate=2017-03-01
</code>```

Title: Obtaining JSON data with foreach in PHP

Body:
A site contains monthly data in a JSON format. This can be queried like so:

http://www.example.com?startdate=1-1-1985&enddate=31-1-1985

I want to be able to run a script that will obtain the specific data I am looking for, starting from today's month, then work backward until null data is returned. Each month's value needs to add up. So far, this is what I've got:

//Build base URL:
$userid=$_GET['userid'];
$startdate=/*Beginning of today's month*/;
$enddate=/*End of today's month*/;
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;

//Set JSON variables:
$get=file_get_contents($url);
$json=json_decode($get);

//Set loop variables:
$value=0;
$month=0;

/*For each month from today backwards{
    $number=$json->integer;
    if($number!=null){
        $value=$value+$number;
        $month=$month+1;
    }else{
        break;
    }
}
echo $value;
echo $month;
*/

The part I'm having problems with is the beginning of the fourth part. How do I run a loop that starts with the range of today's month, obtain $number, then repeat with the previous month, until it reaches a month that returns null?

Body:
You could use the DateTime object and it's associated methods ( specifically sub in this case ) to count backwards by subtracting 1month at a time. An array stores the months/dates and the url is constructed using the variable counter $i

Initially this has a maximum backwards range of 20years ( which I guessed would be more than enough ) but it's easy to change.

$df='Y-m-d';
$userid=$_GET['userid'];

$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1M');

$ts=date( $df, strtotime( date('Y-m-1') ) );
$tf=date( $df, strtotime( date('Y-m-1'). ' - 20 years') );

$start=new DateTime( $ts, $timezone );
$end=new DateTime( $tf, $timezone );

$dates=array();
$i=0;

while( $start->sub( $interval ) > $end ){
    $dates[]=$start->format( $df );
    if( $i > 1 ){

        $startdate=$dates[ $i - 1 ];
        $enddate=$dates[ $i ];
        $url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
        echo $url,'<br />';

        /* uncomment when happy with mechanism */
        /*

        $data=file_get_contents( $url );
        if( $data ) ) {
            $json=json_decode( $data );
            #process.....
            break;
        }
        */
    }
    $i++;
}

A snippet of the output

http://www.example.com?userid=bobodaclown&startdate=2017-10-01&enddate=2017-09-01
http://www.example.com?userid=bobodaclown&startdate=2017-09-01&enddate=2017-08-01
http://www.example.com?userid=bobodaclown&startdate=2017-08-01&enddate=2017-07-01
http://www.example.com?userid=bobodaclown&startdate=2017-07-01&enddate=2017-06-01
http://www.example.com?userid=bobodaclown&startdate=2017-06-01&enddate=2017-05-01
http://www.example.com?userid=bobodaclown&startdate=2017-05-01&enddate=2017-04-01
http://www.example.com?userid=bobodaclown&startdate=2017-04-01&enddate=2017-03-01


问:
WPF DataGrid DataBinding is not displayed
I have a DataGrid in my current WPF Application which I would like to bind to a ViewModel that holds a ObservableCollection. The user can enter search values in some TextBoxes and after enter has been hit I am performing an query to our database that retunrs a table of records. From these records I am populate the data for the ObservableCollection. I am now struggeling now that the datagrid is not displaying the data.

I have read a howl bunch of posts about the binding but I am still missing something I think.

Product.cs

```<code>public class Product : InotifyPropertyChanged, IEditableObject
{
    public string Title { get; set; } = "";

    //public Product()
    //{

    //}
    private ProductViewModel _productViewModel = new ProductViewModel();
    public ProductViewModel productViewModel { get { return _productViewModel; } set { _productViewModel = value; } }

    public DataTable ProductsTable { get; set; }

    public void GetProducts(string filter)
    {
        //< --doing some stuff to fill the table-->

        foreach (DataRow row in ProductsTable.Rows)
        {
            productViewModel.Products.Add(new Product
            {

                Title = (string)row["TITLE"],

            });
        }
    }
}
</code>```

ProductViewModel.cs

```<code>public class ProductViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private Product _SelectedProduct;
    private ObservableCollection<Product> _Products = new ObservableCollection<Product>();
    public ObservableCollection<Product> Products { get { return _Products; } set { _Products = value; } }

    public ProductViewModel()
    {
    }

    public void NotifyPropertyChanged(string propertyName)
    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

ProductWindow.xaml

```<code><DataGrid
    Name="ProductsGrid"
    AutoGenerateColumns="False"
    ItemsSource="{Binding Products, Mode=TwoWay, NotifyOnSourceUpdated=True}"
    SelectedItem="{Binding SelectedProduct, Mode=TwoWay}"
    CanUserAddRows="False" SelectionUnit="FullRow"
    VerticalAlignment="Stretch"
    Grid.Row="0"
    Margin="10,10,10,10"
    >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Title}" Header="Title"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

ProductWindow.xaml.cs

```<code>    public partial class ProductWindow : Page
{
    public object DialogResult { get; private set; }
    //public ProductViewModel ProductViewModel;
    public ProductWindow()
    {

        InitializeComponent();

        DataContext = new ProductViewModel();//stackflow
        //var ProductViewModel = products.ProductViewModel;
        //ProductsGrid.DataContext = new ProductViewModel();

    }

    public ProductViewModel ViewModel => DataContext as ProductViewModel;

    private void OnKeydownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            var tb = sender as TextBox;
            Product products = new Product();
            string filter = "";//performing some ifelse to create filter
            products.GetProducts(filter);
            //ProductsGrid.DataContext = products.ProductsTable;
            //ProductsGrid.DataContext = products.productViewModel;

        }
        else if (e.Key == Key.Escape)
        {
            ProductsGrid.DataContext = null;
            foreach (TextBox tb in FindVisualChildren<TextBox>(this))
            {
                // do something with tb here
                tb.Text = "";
            }
        }
    }
</code>```

}

答:
If DataContext is a ProductViewModel, and the Products collection of that ProductViewModel is populated, you will see rows in your DataGrid. I've tested that. It appears that the viewmodel you're giving it may not have any rows.

That said, there's a problem with your design:

Product creates a ProductViewModel. ProductViewModel creates a collection of Product. Each Product, as I just said, creates a ProductViewModel. Which creates a collection of Product. They keep creating each other until you get a StackOverflowException. If you're not seeing that, you must be calling GetProducts() from somewhere else.

But there's no need for Product to own a copy of ProductViewModel. That's like adding a car to each wheel on your car.

So let's do this instead: ProductViewModel owns a collection of Product. Just that. And we'll call GetProducts() to make sure we get some items in the grid. Your binding is fine. You just weren't populating the collection.

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new ProductViewModel();
    }

    //  Now you can call ViewModel.GetProducts(filterString) from an event handler.
    //  It would be more "correct" to use a Command, but let's take one step at a time.
    public ProductViewModel ViewModel => DataContext as ProductViewModel;
}
</code>```

Viewmodels

```<code>//  You didn't include any implementation of IEditableObject. I presume
//  you can add that back in to this version of the class.
public class Product : INotifyPropertyChanged, IEditableObject
{
    //  You weren't raising PropertyChanged here, or anywhere at all.
    //  In every setter on a viewmodel, you need to do that.
    private string _title = "";
    public string Title {
        get => _title;
        set
        {
            if (_title != value)
            {
                _title = value;
                NotifyPropertyChanged(nameof(Title));
            }
        }
    }

    public Product()
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class ProductViewModel : INotifyPropertyChanged
{
    public ProductViewModel()
    {
        GetProducts("");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private Product _SelectedProduct;

    public Product SelectedProduct
    {
        get { return _SelectedProduct; }
        set
        {
            if (value != _SelectedProduct)
            {
                _SelectedProduct = value;
                NotifyPropertyChanged(nameof(SelectedProduct));
            }
        }
    }

    public DataTable ProductsTable { get; set; }

    public void GetProducts(string filter)
    {
        //< --doing some stuff to fill the table-->

        Products.Clear();

        foreach (DataRow row in ProductsTable.Rows)
        {
            Products.Add(new Product
            {
                Title = (string)row["TITLE"],
            });
        }
    }

    private ObservableCollection<Product> _Products = new ObservableCollection<Product>();
    //  This setter MUST raise PropertyChanged. See the Title property above for example.
    public ObservableCollection<Product> Products { get { return _Products; } private set { _Products = value; } }

    public void NotifyPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Update

Here's the problem: You create a new Product, which creates its own ProductsViewModel. Nothing is bound to any property of that viewmodel. You fill its collection and the DataGrid doesn't know or care, because you bound its ItemsSource to a property of a different object.

So use my suggestions above, particularly the ViewModel property of the window. I just made a change in ProductsViewModel.GetProducts() that you need to copy: Now it calls Products.Clear() before populating the collection.

```<code>    if (e.Key == Key.Enter)
    {
        var tb = sender as TextBox;

        //  Don't create this
        //Product products = new Product();

        string filter = "";//performing some ifelse to create filter
        ViewModel.GetProducts(filter);

    }
    else if (e.Key == Key.Escape)
    {
        //  Setting the DataContext to null breaks everything. Never do that.
        //ProductsGrid.DataContext = null;

        //  Instead, just clear the collection. It's an ObservableCollection so it will
        //  notify the DataGrid that it was cleared.
        ViewModel.Products.Clear();

        foreach (TextBox tb in FindVisualChildren<TextBox>(this))
        {
            // do something with tb here
            tb.Text = "";
        }
    }
</code>```

Body:
I have a DataGrid in my current WPF Application which I would like to bind to a ViewModel that holds a ObservableCollection. The user can enter search values in some TextBoxes and after enter has been hit I am performing an query to our database that retunrs a table of records. From these records I am populate the data for the ObservableCollection. I am now struggeling now that the datagrid is not displaying the data.

I have read a howl bunch of posts about the binding but I am still missing something I think.

Product.cs

public class Product : InotifyPropertyChanged, IEditableObject
{
    public string Title { get; set; } = "";

    //public Product()
    //{

    //}
    private ProductViewModel _productViewModel = new ProductViewModel();
    public ProductViewModel productViewModel { get { return _productViewModel; } set { _productViewModel = value; } }

    public DataTable ProductsTable { get; set; }

    public void GetProducts(string filter)
    {
        //< --doing some stuff to fill the table-->

        foreach (DataRow row in ProductsTable.Rows)
        {
            productViewModel.Products.Add(new Product
            {

                Title = (string)row["TITLE"],

            });
        }
    }
}

ProductViewModel.cs

public class ProductViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private Product _SelectedProduct;
    private ObservableCollection<Product> _Products = new ObservableCollection<Product>();
    public ObservableCollection<Product> Products { get { return _Products; } set { _Products = value; } }

    public ProductViewModel()
    {
    }

    public void NotifyPropertyChanged(string propertyName)
    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

ProductWindow.xaml

<DataGrid
    Name="ProductsGrid"
    AutoGenerateColumns="False"
    ItemsSource="{Binding Products, Mode=TwoWay, NotifyOnSourceUpdated=True}"
    SelectedItem="{Binding SelectedProduct, Mode=TwoWay}"
    CanUserAddRows="False" SelectionUnit="FullRow"
    VerticalAlignment="Stretch"
    Grid.Row="0"
    Margin="10,10,10,10"
    >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Title}" Header="Title"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

ProductWindow.xaml.cs

    public partial class ProductWindow : Page
{
    public object DialogResult { get; private set; }
    //public ProductViewModel ProductViewModel;
    public ProductWindow()
    {

        InitializeComponent();

        DataContext = new ProductViewModel();//stackflow
        //var ProductViewModel = products.ProductViewModel;
        //ProductsGrid.DataContext = new ProductViewModel();

    }

    public ProductViewModel ViewModel => DataContext as ProductViewModel;

    private void OnKeydownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            var tb = sender as TextBox;
            Product products = new Product();
            string filter = "";//performing some ifelse to create filter
            products.GetProducts(filter);
            //ProductsGrid.DataContext = products.ProductsTable;
            //ProductsGrid.DataContext = products.productViewModel;

        }
        else if (e.Key == Key.Escape)
        {
            ProductsGrid.DataContext = null;
            foreach (TextBox tb in FindVisualChildren<TextBox>(this))
            {
                // do something with tb here
                tb.Text = "";
            }
        }
    }

}

Body:
If DataContext is a ProductViewModel, and the Products collection of that ProductViewModel is populated, you will see rows in your DataGrid. I've tested that. It appears that the viewmodel you're giving it may not have any rows.

That said, there's a problem with your design:

Product creates a ProductViewModel. ProductViewModel creates a collection of Product. Each Product, as I just said, creates a ProductViewModel. Which creates a collection of Product. They keep creating each other until you get a StackOverflowException. If you're not seeing that, you must be calling GetProducts() from somewhere else.

But there's no need for Product to own a copy of ProductViewModel. That's like adding a car to each wheel on your car.

So let's do this instead: ProductViewModel owns a collection of Product. Just that. And we'll call GetProducts() to make sure we get some items in the grid. Your binding is fine. You just weren't populating the collection.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new ProductViewModel();
    }

    //  Now you can call ViewModel.GetProducts(filterString) from an event handler.
    //  It would be more "correct" to use a Command, but let's take one step at a time.
    public ProductViewModel ViewModel => DataContext as ProductViewModel;
}

Viewmodels

//  You didn't include any implementation of IEditableObject. I presume
//  you can add that back in to this version of the class.
public class Product : INotifyPropertyChanged, IEditableObject
{
    //  You weren't raising PropertyChanged here, or anywhere at all.
    //  In every setter on a viewmodel, you need to do that.
    private string _title = "";
    public string Title {
        get => _title;
        set
        {
            if (_title != value)
            {
                _title = value;
                NotifyPropertyChanged(nameof(Title));
            }
        }
    }

    public Product()
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class ProductViewModel : INotifyPropertyChanged
{
    public ProductViewModel()
    {
        GetProducts("");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private Product _SelectedProduct;

    public Product SelectedProduct
    {
        get { return _SelectedProduct; }
        set
        {
            if (value != _SelectedProduct)
            {
                _SelectedProduct = value;
                NotifyPropertyChanged(nameof(SelectedProduct));
            }
        }
    }

    public DataTable ProductsTable { get; set; }

    public void GetProducts(string filter)
    {
        //< --doing some stuff to fill the table-->

        Products.Clear();

        foreach (DataRow row in ProductsTable.Rows)
        {
            Products.Add(new Product
            {
                Title = (string)row["TITLE"],
            });
        }
    }

    private ObservableCollection<Product> _Products = new ObservableCollection<Product>();
    //  This setter MUST raise PropertyChanged. See the Title property above for example.
    public ObservableCollection<Product> Products { get { return _Products; } private set { _Products = value; } }

    public void NotifyPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Update

Here's the problem: You create a new Product, which creates its own ProductsViewModel. Nothing is bound to any property of that viewmodel. You fill its collection and the DataGrid doesn't know or care, because you bound its ItemsSource to a property of a different object.

So use my suggestions above, particularly the ViewModel property of the window. I just made a change in ProductsViewModel.GetProducts() that you need to copy: Now it calls Products.Clear() before populating the collection.

    if (e.Key == Key.Enter)
    {
        var tb = sender as TextBox;

        //  Don't create this
        //Product products = new Product();

        string filter = "";//performing some ifelse to create filter
        ViewModel.GetProducts(filter);

    }
    else if (e.Key == Key.Escape)
    {
        //  Setting the DataContext to null breaks everything. Never do that.
        //ProductsGrid.DataContext = null;

        //  Instead, just clear the collection. It's an ObservableCollection so it will
        //  notify the DataGrid that it was cleared.
        ViewModel.Products.Clear();

        foreach (TextBox tb in FindVisualChildren<TextBox>(this))
        {
            // do something with tb here
            tb.Text = "";
        }
    }


问:
Multiple rows out of a single record
lets say that e.g if i did SELECT * FROM X i'd get

```<code>A1, A2, A3, A4, A5, A6, A7
</code>```

is it possible to do a query that for each record returns

```<code>A1, A2, A3
A1, A2, A4
A1, A2, A5
A1, A2, A6
A1, A2, A7
</code>```

????

My actual problem ( and this is just additional information, not required to answer the question ) --> i have a db about football matches so i have players etc but the table matches are like this:

```<code>homeplayer1 (fk)
homeplayer2 (fk)
.
.
.
homeplayerN (fk)
</code>```

and same for away players but i'm working on a multidimiensional db implementation that requires to have only one player associated per match so it'd be 22 records per match to fit the 22 players.

I'm using postgresql.

答:
```<code> select a1, a2,
        unnest(array[a3,a4,a5,a6,a7])
   from X
</code>```

Test on sqlfiddle.com

Title: Multiple rows out of a single record

Body:
lets say that e.g if i did SELECT * FROM X i'd get

A1, A2, A3, A4, A5, A6, A7

is it possible to do a query that for each record returns

A1, A2, A3
A1, A2, A4
A1, A2, A5
A1, A2, A6
A1, A2, A7

????

My actual problem ( and this is just additional information, not required to answer the question ) --> i have a db about football matches so i have players etc but the table matches are like this:

homeplayer1 (fk)
homeplayer2 (fk)
.
.
.
homeplayerN (fk)

and same for away players but i'm working on a multidimiensional db implementation that requires to have only one player associated per match so it'd be 22 records per match to fit the 22 players.

I'm using postgresql.

Body:
 select a1, a2,
        unnest(array[a3,a4,a5,a6,a7])
   from X

Test on sqlfiddle.com


问:
Having a struct as an attribute of a core data entity
In my core data model, I have an entity for which its attribute is a struct. Here's the struct

```<code>struct Range: NSCoding {
    let minValue: Int
    let maxValue: Int

/* implementations of
    required init?(coder: NSCoder)
   and
     func encode(with aCoder: NSCoder)
*/
}
</code>```

For brevity sake, let's imagine an entity like so:

```<code> Question
    -title: String
    -range: Range
</code>```

I know that the range attribute needs to be a Transformable in the data model.

When trying to assign Range as the class of the transformable, I get the Property cannot be marked @NSManaged because its type cannot be represented in Objective-C error

What is the correct setup?

More specifically, what's the correct values for the following attributes in the Xcode editor?

Value Tranformer

Custom Class (I tried to set it as Range)

Module (currently set to 'current module')

Thanks!

答:
I would save minValue and maxValue as Int32 in the entity

```<code>@NSManaged var minValue: Int32
@NSManaged var maxValue: Int32
</code>```

use a simple version if the struct (since NSCoding doesn't support structs anyway)

```<code>struct Range {
    let min: Int
    let max: Int
}
</code>```

and a computed property in the NSManagedObject (sub)class to map both attributes to a Range object

```<code>var range : Range {
    get { return Range(min: Int(minValue), max: Int(maxValue)) }
    set {
        minValue = Int32(newValue.min)
        maxValue = Int32(newValue.max)
    }
}
</code>```

or forget the struct and use a real Range

```<code>var range : Range<Int> {
    get { return Range<Int>(uncheckedBounds: (Int(minValue), Int(maxValue))) }
    set {
        minValue = Int32(newValue.lowerBound)
        maxValue = Int32(newValue.upperBound)
    }
}
</code>```

Consider that Range<T> uses the half-open type: 0..<3 contains 0, 1 and 2

Edit

If the range is supposed to be optional then you could identify a valid range if maxValue > minValue for example

```<code>var range : Range<Int>? {
    get {
        guard maxValue > minValue else { return nil }
        return Range<Int>(uncheckedBounds: (Int(minValue), Int(maxValue))) }
    set {
        if let value = newValue {
            minValue = Int32(value.lowerBound)
            maxValue = Int32(value.upperBound)
        }  else {
            minValue = 0
            maxValue = 0
        }
    }
}
</code>```

Body:
In my core data model, I have an entity for which its attribute is a struct. Here's the struct

struct Range: NSCoding {
    let minValue: Int
    let maxValue: Int

/* implementations of
    required init?(coder: NSCoder)
   and
     func encode(with aCoder: NSCoder)
*/
}

For brevity sake, let's imagine an entity like so:

 Question
    -title: String
    -range: Range

I know that the range attribute needs to be a Transformable in the data model.

When trying to assign Range as the class of the transformable, I get the Property cannot be marked @NSManaged because its type cannot be represented in Objective-C error

What is the correct setup?

More specifically, what's the correct values for the following attributes in the Xcode editor?

Value Tranformer

Custom Class (I tried to set it as Range)

Module (currently set to 'current module')

Thanks!

Body:
I would save minValue and maxValue as Int32 in the entity

@NSManaged var minValue: Int32
@NSManaged var maxValue: Int32

use a simple version if the struct (since NSCoding doesn't support structs anyway)

struct Range {
    let min: Int
    let max: Int
}

and a computed property in the NSManagedObject (sub)class to map both attributes to a Range object

var range : Range {
    get { return Range(min: Int(minValue), max: Int(maxValue)) }
    set {
        minValue = Int32(newValue.min)
        maxValue = Int32(newValue.max)
    }
}

or forget the struct and use a real Range

var range : Range<Int> {
    get { return Range<Int>(uncheckedBounds: (Int(minValue), Int(maxValue))) }
    set {
        minValue = Int32(newValue.lowerBound)
        maxValue = Int32(newValue.upperBound)
    }
}

Consider that Range<T> uses the half-open type: 0..<3 contains 0, 1 and 2

Edit

If the range is supposed to be optional then you could identify a valid range if maxValue > minValue for example

var range : Range<Int>? {
    get {
        guard maxValue > minValue else { return nil }
        return Range<Int>(uncheckedBounds: (Int(minValue), Int(maxValue))) }
    set {
        if let value = newValue {
            minValue = Int32(value.lowerBound)
            maxValue = Int32(value.upperBound)
        }  else {
            minValue = 0
            maxValue = 0
        }
    }
}


问:
c++ malloc and two-dimension array not reserving enough memory
I need to creat a 2 dimension array with malloc, so that I can return it's pointer with a function. In this function I also allocate integers (by getpixel() function) into this array. I do it this way:

```<code>int **tab;
tab = (int**)malloc((600) * sizeof(int));

for (int i = 0; i<600; i++)
{
    tab[i] = (int*)malloc((800) * sizeof(int*));
}

for (int i = 0; i<600; i++)
{
    for (int j = 0; j<800; j++)
    {
        tab[i][j] = getpixel(i, j);
    }
}
</code>```

This array works of course in most of the cases, when I check it, it has the values I expected inside. However, it stops working, when I get to a bigger Y. So eg. when I want to check array tab[799][599], I can't, because there is an error about exception, I can't copy it directly, because I have the other language than English verion, but it goes something like that:

"The unsupported exception in 0x00E71C05 w bgi.exe: 0xC0000005: violation of rules of access when reading from the location 0x0000095C."

I think it means, that mallock() didn't reserve enought memory for me. But how can I make array big enough then? Or is this any other problem?

答:
Your malloc is wrong, it needs to be like:

```<code>int **tab;
tab = (int**)malloc((800) * sizeof(int*));

for (int i = 0; i<800; i++)
{
    tab[i] = (int*)malloc((600) * sizeof(int));
}
</code>```

If you want your array to be 800x600. If you want it to be 600x800 just swap the values.

Body:
I need to creat a 2 dimension array with malloc, so that I can return it's pointer with a function. In this function I also allocate integers (by getpixel() function) into this array. I do it this way:

int **tab;
tab = (int**)malloc((600) * sizeof(int));

for (int i = 0; i<600; i++)
{
    tab[i] = (int*)malloc((800) * sizeof(int*));
}

for (int i = 0; i<600; i++)
{
    for (int j = 0; j<800; j++)
    {
        tab[i][j] = getpixel(i, j);
    }
}

This array works of course in most of the cases, when I check it, it has the values I expected inside. However, it stops working, when I get to a bigger Y. So eg. when I want to check array tab[799][599], I can't, because there is an error about exception, I can't copy it directly, because I have the other language than English verion, but it goes something like that:

"The unsupported exception in 0x00E71C05 w bgi.exe: 0xC0000005: violation of rules of access when reading from the location 0x0000095C."

I think it means, that mallock() didn't reserve enought memory for me. But how can I make array big enough then? Or is this any other problem?

Body:
Your malloc is wrong, it needs to be like:

int **tab;
tab = (int**)malloc((800) * sizeof(int*));

for (int i = 0; i<800; i++)
{
    tab[i] = (int*)malloc((600) * sizeof(int));
}

If you want your array to be 800x600. If you want it to be 600x800 just swap the values.


问:
AWS RDS DB Parameter Group in CloudFormation
I'm trying to create a custom DBParameterGroup as part of the CloudFormation stack to launch SQL instance using below resource definition -

```<code>CustomDBParameterGroup:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: !Join [' ', ['Custom Option Group for application - ', !Ref AppName, !Ref EnvironmentType]]
      Family: sqlserver-ee-13.0
      Parameters:
        remote_access: 0
</code>```

When I launch the stack, I get the error -

Invalid / Unsupported DB Parameter: remote_access

What is the correct parameter attribute key/value combination to
  disable remote access in the parameter group? Unable to find this in
  AWS documentation. Appreciate if anyone can help.

Thanks!

答:
I found the answer. Change the remote_access to remote access (with a space) and the custom DBParameterGroup will be created with the set value of 0.

```<code>CustomDBParameterGroup:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: !Join [' ', ['Custom Option Group for application - ', !Ref AppName, !Ref EnvironmentType]]
      Family: sqlserver-ee-13.0
      Parameters:
        remote access: 0
</code>```

Body:
I'm trying to create a custom DBParameterGroup as part of the CloudFormation stack to launch SQL instance using below resource definition -

CustomDBParameterGroup:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: !Join [' ', ['Custom Option Group for application - ', !Ref AppName, !Ref EnvironmentType]]
      Family: sqlserver-ee-13.0
      Parameters:
        remote_access: 0

When I launch the stack, I get the error -

Invalid / Unsupported DB Parameter: remote_access

What is the correct parameter attribute key/value combination to
  disable remote access in the parameter group? Unable to find this in
  AWS documentation. Appreciate if anyone can help.

Thanks!

Body:
I found the answer. Change the remote_access to remote access (with a space) and the custom DBParameterGroup will be created with the set value of 0.

CustomDBParameterGroup:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: !Join [' ', ['Custom Option Group for application - ', !Ref AppName, !Ref EnvironmentType]]
      Family: sqlserver-ee-13.0
      Parameters:
        remote access: 0


问:
Laravel NotFoundHttpException No query results for model
I have error NotFoundHttpException No query results for model [App\ThreadForum]

My web.php :

```<code>Route::get('/threads','ThreadForumController@index');
Route::post('/threads','ThreadForumController@store');
Route::get('/threads/create','ThreadForumController@create');
Route::get('/threads/{thread}','ThreadForumController@show')->name('threads.show');
</code>```

My model:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class ThreadForum extends Model
{
    protected $fillable = [
        'user_id','title','body'
    ];

    public  function  path(){
        return route('threads.show',$this->id);
    }
    public function  replies(){
        return $this->hasMany('App\Reply');
    }

    public function creator(){
        return $this->belongsTo('App\User', 'user_id');
    }

    public  function  addReply($reply){
        $this->replies()->create($reply);

    }
}
</code>```

My controller:

```<code>namespace App\Http\Controllers;

use App\ThreadForum;
use Illuminate\Http\Request;

class ThreadForumController extends Controller
{
    public function  __construct()
    {
        $this->middleware('auth')->only('store');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $threads = ThreadForum::all();
        return view('threads.index', compact('threads'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('threads.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        dd('store');
        /*$thread = ThreadForum::create([
            'user_id'=>auth()->id(),
            'title'=>$request['title'],
            'body'=>$request['body']
        ]);
        redirect($thread->path());*/
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function show(ThreadForum $thread)
    {
        return view('threads.show',compact('thread'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function edit(ThreadForum $threadForum)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, ThreadForum $threadForum)
    {

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function destroy(ThreadForum $threadForum)
    {
        //
    }

}
</code>```

All functions work well, but when I run post('/threads') for store new record  I get error.
I tried use dd('store') for debugging, but I dont see this text, only error.
How can I fix it?
Thanks.

答:
I cannot comment, but to dump you have to use dd($request) not dd($store)

EDIT: I think that problem is in show method. You use  compact, but there's no any variable above it. So you cannot pass anything to view.

Body:
I have error NotFoundHttpException No query results for model [App\ThreadForum]

My web.php :

Route::get('/threads','ThreadForumController@index');
Route::post('/threads','ThreadForumController@store');
Route::get('/threads/create','ThreadForumController@create');
Route::get('/threads/{thread}','ThreadForumController@show')->name('threads.show');

My model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class ThreadForum extends Model
{
    protected $fillable = [
        'user_id','title','body'
    ];

    public  function  path(){
        return route('threads.show',$this->id);
    }
    public function  replies(){
        return $this->hasMany('App\Reply');
    }

    public function creator(){
        return $this->belongsTo('App\User', 'user_id');
    }

    public  function  addReply($reply){
        $this->replies()->create($reply);

    }
}

My controller:

namespace App\Http\Controllers;

use App\ThreadForum;
use Illuminate\Http\Request;

class ThreadForumController extends Controller
{
    public function  __construct()
    {
        $this->middleware('auth')->only('store');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $threads = ThreadForum::all();
        return view('threads.index', compact('threads'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('threads.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        dd('store');
        /*$thread = ThreadForum::create([
            'user_id'=>auth()->id(),
            'title'=>$request['title'],
            'body'=>$request['body']
        ]);
        redirect($thread->path());*/
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function show(ThreadForum $thread)
    {
        return view('threads.show',compact('thread'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function edit(ThreadForum $threadForum)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, ThreadForum $threadForum)
    {

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\ThreadForum  $threadForum
     * @return \Illuminate\Http\Response
     */
    public function destroy(ThreadForum $threadForum)
    {
        //
    }

}

All functions work well, but when I run post('/threads') for store new record  I get error.
I tried use dd('store') for debugging, but I dont see this text, only error.
How can I fix it?
Thanks.


问:
Need a regular expression in python to separate the signal definitions
The string which contains the signal definitons is of the form,

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)

I want to separate signal definition and put them in a list. Something like below,

```<code>signalDefList = [
    'signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
    'signal_b=super:mario|repp:ver',
    'signal_c=semi:six_sig',
    'signal_d=(1=last:end|start:twist;0=demo:test)'
]
</code>```

Can anybody help me with this?

答:
Code

See regex in use here

```<code>;(?=signal)
</code>```

Replacement: \n

Usage

See code in use here

```<code>import re

r = r";(?=signal)"
s = "signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)"
print re.split(r,s)
</code>```

Output:

```<code>['signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)', 'signal_b=super:mario|repp:ver', 'signal_c=semi:six_sig', 'signal_d=(1=last:end|start:twist;0=demo:test)']
</code>```

Results

Input

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)

Output

```<code>signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)
signal_b=super:mario|repp:ver
signal_c=semi:six_sig
signal_d=(1=last:end|start:twist;0=demo:test)
</code>```

Explanation

; Match the semicolon character ; literally

(?=signal) Positive lookahead ensuring what follows is signal literally

Body:
The string which contains the signal definitons is of the form,

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)

I want to separate signal definition and put them in a list. Something like below,

signalDefList = [
    'signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
    'signal_b=super:mario|repp:ver',
    'signal_c=semi:six_sig',
    'signal_d=(1=last:end|start:twist;0=demo:test)'
]

Can anybody help me with this?

Body:
Code

See regex in use here

;(?=signal)

Replacement: \n

Usage

See code in use here

import re

r = r";(?=signal)"
s = "signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)"
print re.split(r,s)

Output:

['signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)', 'signal_b=super:mario|repp:ver', 'signal_c=semi:six_sig', 'signal_d=(1=last:end|start:twist;0=demo:test)']

Results

Input

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)

Output

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)
signal_b=super:mario|repp:ver
signal_c=semi:six_sig
signal_d=(1=last:end|start:twist;0=demo:test)

Explanation

; Match the semicolon character ; literally

(?=signal) Positive lookahead ensuring what follows is signal literally


问:
Unwanted box shadow appearing on website and responsive break
I am currently updating/working on this web page "https://www.emergencydentalservice.com/emergency-dentist-by-city" and their is an unwanted box shadow appearing in the body that I can not determine from where or why. On top of the unwanted shadow the site also seems to break after 768px and I can't figure out why. Any help would be greatly appreciated, thank you all. Image of the site breaking after 768px</p>

答:
For the shadow issue:
#inside-main still has a box-shadow property on it from eds_main.css.

Though you didn't really specify which shadows you do and don't want... as there are multiple on the page.

Inspect Element / Dev Tools is your friend. Makes it easy to hunt down properties you may be overlooking.


问:
An efficient algorithm to count the number of integer grids
Consider a square 3 by 3 grid of non-negative integers.  For each row i the sum of the integers is set to be r_i.  Similarly for each column j the sum of integers in that column is set to be c_j.  An instance of the problem is therefore described by 6 non-negative integers.

Is there an efficient algorithm to count how many different
  assignments of integers to the grid there are given the row and column
  sum constraints?

Clearly one could enumerate all possible matrices of non-negative integers with values up to sum r_i and check the constraints for each, but that would be insanely slow.

Example

Say the row constraints are 1 2 3 and the column constraints are 3 2 1. The possible integer grids are:

```<code>┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
</code>```

In practice my main interest is when the total sum of the grid will be at most 100 but a more general solution would be very interesting.

答:
I don't know of a matching algorithm, but I don't think it would be that difficult to work one out.  Given any one solution, you can derive another solution by selecting four corners of a rectangular region of your grid, increasing two diagonal corners by some value and decreasing the other two by that same value.  The range for that value will be constrained by the lowest value of each diagonal pair.  If you determine the size of all such ranges, you should be able to multiply them together to determine the total possible solutions.

Assuming you described your grid like a familiar spreadsheet alphabetically for columns, and numerically for rows, you could describe all possible regions in the following list:

A1:B2, A1:B3, A1:C2, A1:C3, B1:C2, B1:C3, A2:B3, A2:C3, B2:C3

For each region, we tabulate a range based on the lowest value from each diagonal corner pair.  You can incrementally reduce either pair until a member reaches zero because there's no upper bound for the other pair.

Selecting the first solution of your example, we can derive all other possible solutions using this technique.

```<code>   A B C
  ┌─────┐
1 │0 0 1│ sum=1
2 │0 2 0│ sum=2
3 │3 0 0│ sum=3
  └─────┘
   3 2 1 = sums

A1:B2 - 1 solution (0,0,0,2)
A1:C2 - 1 solution (0,1,0,0)
A1:B3   1 solution (0,0,3,0)
A1:C3   2 solutions (0,1,3,0), (1,0,2,1)
B1:C2   2 solutions (0,1,2,0), (1,0,1,1)
B1:C3   1 solution (0,1,0,0)
A2:B3   3 solutions (0,2,3,0), (1,1,2,1), (2,0,1,2)
A2:C3   1 solution (0,0,3,0)
B2:C3   1 solution (2,0,0,0)
</code>```

Multiply all solution counts together and you get 2*2*3=12 solutions.

Body:
Consider a square 3 by 3 grid of non-negative integers.  For each row i the sum of the integers is set to be r_i.  Similarly for each column j the sum of integers in that column is set to be c_j.  An instance of the problem is therefore described by 6 non-negative integers.

Is there an efficient algorithm to count how many different
  assignments of integers to the grid there are given the row and column
  sum constraints?

Clearly one could enumerate all possible matrices of non-negative integers with values up to sum r_i and check the constraints for each, but that would be insanely slow.

Example

Say the row constraints are 1 2 3 and the column constraints are 3 2 1. The possible integer grids are:

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

In practice my main interest is when the total sum of the grid will be at most 100 but a more general solution would be very interesting.

Body:
I don't know of a matching algorithm, but I don't think it would be that difficult to work one out.  Given any one solution, you can derive another solution by selecting four corners of a rectangular region of your grid, increasing two diagonal corners by some value and decreasing the other two by that same value.  The range for that value will be constrained by the lowest value of each diagonal pair.  If you determine the size of all such ranges, you should be able to multiply them together to determine the total possible solutions.

Assuming you described your grid like a familiar spreadsheet alphabetically for columns, and numerically for rows, you could describe all possible regions in the following list:

A1:B2, A1:B3, A1:C2, A1:C3, B1:C2, B1:C3, A2:B3, A2:C3, B2:C3

For each region, we tabulate a range based on the lowest value from each diagonal corner pair.  You can incrementally reduce either pair until a member reaches zero because there's no upper bound for the other pair.

Selecting the first solution of your example, we can derive all other possible solutions using this technique.

   A B C
  ┌─────┐
1 │0 0 1│ sum=1
2 │0 2 0│ sum=2
3 │3 0 0│ sum=3
  └─────┘
   3 2 1 = sums

A1:B2 - 1 solution (0,0,0,2)
A1:C2 - 1 solution (0,1,0,0)
A1:B3   1 solution (0,0,3,0)
A1:C3   2 solutions (0,1,3,0), (1,0,2,1)
B1:C2   2 solutions (0,1,2,0), (1,0,1,1)
B1:C3   1 solution (0,1,0,0)
A2:B3   3 solutions (0,2,3,0), (1,1,2,1), (2,0,1,2)
A2:C3   1 solution (0,0,3,0)
B2:C3   1 solution (2,0,0,0)

Multiply all solution counts together and you get 2*2*3=12 solutions.