问:
Reading specific chunks pandas / not reading all chunks in pandas
I am trying to use accordingly to this question and answer reading a large csv file by chunks and processing it. Since I'm not native with python I got an optimization problem and looking for a better solution here.

What my code does:

I read in the line count of my csv with

```<code>with open(file) as f:
    row_count = sum(1 for line in f)
</code>```

afterwards I "slice" my data in 30 equal sized chunks and process it accordingly to the linked answer with a for loop and pd.read_csv(file, chunksize). Since plotting 30 graphs in one is pretty unclear, I plot it every 5 steps with modulo (which may be variated). For this I use an external counter.

```<code>chunksize = row_count // 30
counter = 0
for chunk in pd.read_csv(file, chunksize=chunksize):
    df = chunk
    print(counter)
    if ((counter % 5) == 0 | (counter == 0):
        plt.plot(df["Variable"])
    counter = counter +1
plt.show()
</code>```

Now to my question:

It seems like, this loop reads the chunk size in before processing the loop, which is reasonable. I can see this, since the print(counter) steps are also fairly slow. Since I read a few million rows of a csv, it takes some time every step. Is there a way to skip the not wanted chunks in the for loop, before reading it in? I was trying out something like:

```<code>wanted_plts <- [1,5,10,15,20,25,30]
for i in wanted_plts:
   for chunk[i] in pd.read_csv(file, chunksize=chunksize):
   .
   .
</code>```

I think I have understanding issues how I can manipulate this syntax of the for loop range. There should be an elegant way to fix this.

Also: i found the .get_chunk(x) by pandas but this seems to create just one chunk of size x.

Another attempt by me is trying to subset the reader object of pd.read_csv like pd.read_csv()[0,1,2] but it seems that's not possible too.

Amendment: I'm aware plotting a lot of data in matplotlib is slow. I preprocess it earlier, but for making this code readable I removed all unnecessary parts.

答:
As far as I know, pandas does not provide any support for skipping chunks of file. At least I never found anything about it in the documentation.

In general, skipping lines from file (not reading them at all) is difficult unless you know in advance how many lines you want to skip and how many characters you have in each of those lines. In this case you can try to play with IO and seek to move the stream position to the exact place you need the next iteration.

But it does not seem your case.

I think the best thing you can do to improve efficiency is to read the lines using standard IO, and convert to a dataframe only the lines you need / want to plot.

Consider for example the following custom iterator.

When instantiated, it saves the header (first line). Each iteration it reads a chunk of lines from the file and then skip the following n*chunksize lines. It returns the header line followed by the read lines, wrapped in a io.StringIO object (so it's a stream and can be fed directly to pandas.read_csv).

```<code>import io
from itertools import islice

class DfReaderChunks:
    def __init__(self, filename, chunksize, n):
        self.fo = open(filename)
        self.chs = chunksize
        self.skiplines = self.chs * n
        self.header = next(self.fo)

    def getchunk(self):
        ll = list(islice(self.fo, self.chs))
        if len(ll) == 0:
            raise StopIteration
        dd = list(islice(self.fo, self.skiplines))
        return self.header + ''.join(ll)

    def __iter__(self):
        return self

    def __next__(self):
        return io.StringIO(self.getchunk())

    def close(self):
        self.fo.close()

    def __del__(self):
        self.fo.close()
</code>```

Using this class, your can read from your file:

```<code>reader = DfReaderChunks(file, chunksize, 4)
for dfst in reader:
    df = pd.read_csv(dfst)
    print(df) #here I print to stdout, you can plot
reader.close()
</code>```

which is "equivalent" to your setup:

```<code>for chunk in pd.read_csv(file, chunksize=chunksize):
    df = chunk
    if (counter % 5 == 0):
        print(df) #again I print, you can plot
    counter += 1
</code>```

I tested the time used by both the above snippets using a dataframe of 39 Mb (100000 rows or random numbers).

On my machine, the former takes 0.458 seconds, the latter 0.821 seconds.

The only drawback is that the former snippet loses track of the row index (it's a new dataframe each time, so index always start from 0) but the printed chunks are the same.

Body:
I am trying to use accordingly to this question and answer reading a large csv file by chunks and processing it. Since I'm not native with python I got an optimization problem and looking for a better solution here.

What my code does:

I read in the line count of my csv with

with open(file) as f:
    row_count = sum(1 for line in f)

afterwards I "slice" my data in 30 equal sized chunks and process it accordingly to the linked answer with a for loop and pd.read_csv(file, chunksize). Since plotting 30 graphs in one is pretty unclear, I plot it every 5 steps with modulo (which may be variated). For this I use an external counter.

chunksize = row_count // 30
counter = 0
for chunk in pd.read_csv(file, chunksize=chunksize):
    df = chunk
    print(counter)
    if ((counter % 5) == 0 | (counter == 0):
        plt.plot(df["Variable"])
    counter = counter +1
plt.show()

Now to my question:

It seems like, this loop reads the chunk size in before processing the loop, which is reasonable. I can see this, since the print(counter) steps are also fairly slow. Since I read a few million rows of a csv, it takes some time every step. Is there a way to skip the not wanted chunks in the for loop, before reading it in? I was trying out something like:

wanted_plts <- [1,5,10,15,20,25,30]
for i in wanted_plts:
   for chunk[i] in pd.read_csv(file, chunksize=chunksize):
   .
   .

I think I have understanding issues how I can manipulate this syntax of the for loop range. There should be an elegant way to fix this.

Also: i found the .get_chunk(x) by pandas but this seems to create just one chunk of size x.

Another attempt by me is trying to subset the reader object of pd.read_csv like pd.read_csv()[0,1,2] but it seems that's not possible too.

Amendment: I'm aware plotting a lot of data in matplotlib is slow. I preprocess it earlier, but for making this code readable I removed all unnecessary parts.

Body:
As far as I know, pandas does not provide any support for skipping chunks of file. At least I never found anything about it in the documentation.

In general, skipping lines from file (not reading them at all) is difficult unless you know in advance how many lines you want to skip and how many characters you have in each of those lines. In this case you can try to play with IO and seek to move the stream position to the exact place you need the next iteration.

But it does not seem your case.

I think the best thing you can do to improve efficiency is to read the lines using standard IO, and convert to a dataframe only the lines you need / want to plot.

Consider for example the following custom iterator.

When instantiated, it saves the header (first line). Each iteration it reads a chunk of lines from the file and then skip the following n*chunksize lines. It returns the header line followed by the read lines, wrapped in a io.StringIO object (so it's a stream and can be fed directly to pandas.read_csv).

import io
from itertools import islice

class DfReaderChunks:
    def __init__(self, filename, chunksize, n):
        self.fo = open(filename)
        self.chs = chunksize
        self.skiplines = self.chs * n
        self.header = next(self.fo)

    def getchunk(self):
        ll = list(islice(self.fo, self.chs))
        if len(ll) == 0:
            raise StopIteration
        dd = list(islice(self.fo, self.skiplines))
        return self.header + ''.join(ll)

    def __iter__(self):
        return self

    def __next__(self):
        return io.StringIO(self.getchunk())

    def close(self):
        self.fo.close()

    def __del__(self):
        self.fo.close()

Using this class, your can read from your file:

reader = DfReaderChunks(file, chunksize, 4)
for dfst in reader:
    df = pd.read_csv(dfst)
    print(df) #here I print to stdout, you can plot
reader.close()

which is "equivalent" to your setup:

for chunk in pd.read_csv(file, chunksize=chunksize):
    df = chunk
    if (counter % 5 == 0):
        print(df) #again I print, you can plot
    counter += 1

I tested the time used by both the above snippets using a dataframe of 39 Mb (100000 rows or random numbers).

On my machine, the former takes 0.458 seconds, the latter 0.821 seconds.

The only drawback is that the former snippet loses track of the row index (it's a new dataframe each time, so index always start from 0) but the printed chunks are the same.


来源: stackexchange

问:
Print spooler concept / API & Channels: issue passing jobs to a queue from serveHTTP
Got some help here already that made me move forward in this concept I'm trying, but it still isn't quite working and I hit a conflict that I can't seem to get around.

I have tried here to illustrate what I want in a flowchart - please note that the client can be many clients that will send in with printjobs therefore we cannot reply on the worker to be processing our job at that moment, but for most it will (peak times it won't as the processing job of printing can take time).

```<code>type QueueElement struct {
    jobid string
    rw   http.ResponseWriter
  doneChan chan struct{}
}

type GlobalVars struct {
    db   *sql.DB
    wg   sync.WaitGroup
    jobs chan QueueElement
}

func (gv *GlobalVars) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        fmt.Printf ("incoming\r\n")

            doneC := make(chan struct{}, 1) //Buffered channel in order not to block the worker routine
            newPrintJob := QueueElement{
                    doneChan: doneC,
                    jobid:    "jobid",
            }

            gv.jobs <- newPrintJob
            func(doneChan chan struct{},w http.ResponseWriter) {

                  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
                    defer cancel()
                    select {
                    //If this triggers first, then this waiting goroutine would exit
                    //and nobody would be listeding the 'doneChan'. This is why it has to be buffered.
                    case <-ctx.Done():
                            fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
                            fmt.Printf ("took longer than 5 secs\r\n")
                    case <-doneChan:
                            fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
                            fmt.Printf ("instant\r\n")
                    }
            }(doneC,w)

    default:
            fmt.Fprintf(w, "No such Api")
    }
}

func worker(jobs <-chan QueueElement) {
    for {
            job := <-jobs
            processExec ("START /i /b try.cmd")
            fmt.Printf ("job done")
        //  processExec("START /i /b processAndPrint.exe -" + job.jobid)
            job.doneChan <- struct{}{}

    }
}

func main() {
      db, err := sql.Open("sqlite3", "jobs.sqlite")
      if err := db.Ping(); err != nil {
        log.Fatal(err)
    }

      db.SetMaxOpenConns(1) // prevents locked database error
      _, err = db.Exec(setupSQL)
      if err != nil {
          log.Fatal(err)
      }

    // create a GlobalVars instance
    gv := GlobalVars{
        db  :   db,
        jobs: make(chan QueueElement),
    }
    go worker (gv.jobs)
    // create an http.Server instance and specify our job manager as
    // the handler for requests.
    server := http.Server{
        Handler: &gv,
        Addr : ":8888",
    }
    // start server and accept connections.
    log.Fatal(server.ListenAndServe())
}
</code>```

The above code is of the serveHTTP and the worker with help from here, initially the func inside the ServeHTTP was a go routine and it's here the whole conflict arises for me - the concept is that in the serveHTTP it spawns a process that will get reply from the worker if the worker were able to process the job in time, within 5 seconds.

If the job was able to finish in 1 second, I want to reply back instantly after that 1 second to the client, if it takes 3 I want to reply after 3, if it takes more than 5 I will send reply back after 5 seconds (if the job takes 13 seconds I still want to reply after 5 seconds). That the client has to poll on the job from now on - but the conflict is:

a) When ServeHTTP exits - then the ResponseWriter closes - and to be able to reply back to the client, we have to write the answer to the ResponseWriter.

b) if I block serveHTTP (like in the code example below where I don't call the func as a go routine) then it affects not only that single API call but it seems that all others after that will be affected, so the first call in will be served correctly in time but the calls that would be coming in at the same time after the first will be sequentially delayed by the blocking operation.

c) if I don't block it ex - and change it to a go routine :

```<code>    gv.jobs <- newPrintJob
    go func(doneChan chan struct{},w http.ResponseWriter) {
</code>```

Then there's no delay - can call in many APIs - but problem is here serveHTTP exists right away and thereby kills ResponseWriter and then I'm not able to reply back to the client.

I am not sure how I can get around this conflict where I don't cause any blockage to serveHTTP so I can handle all requests parallel, but still able to reply back to the ResponseWriter in question.

Is there any way of preventing serveHTTP of shutting down a responsewriter even though the function exits?

答: select statement should be outside the goroutine function and blocks request till the end of the job execution or reaching timeout.

ContentLicense: CC BY-SA 4.0

Body:
Got some help here already that made me move forward in this concept I'm trying, but it still isn't quite working and I hit a conflict that I can't seem to get around.

I have tried here to illustrate what I want in a flowchart - please note that the client can be many clients that will send in with printjobs therefore we cannot reply on the worker to be processing our job at that moment, but for most it will (peak times it won't as the processing job of printing can take time).

type QueueElement struct {
    jobid string
    rw   http.ResponseWriter
  doneChan chan struct{}
}

type GlobalVars struct {
    db   *sql.DB
    wg   sync.WaitGroup
    jobs chan QueueElement
}

func (gv *GlobalVars) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        fmt.Printf ("incoming\r\n")

            doneC := make(chan struct{}, 1) //Buffered channel in order not to block the worker routine
            newPrintJob := QueueElement{
                    doneChan: doneC,
                    jobid:    "jobid",
            }

            gv.jobs <- newPrintJob
            func(doneChan chan struct{},w http.ResponseWriter) {

                  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
                    defer cancel()
                    select {
                    //If this triggers first, then this waiting goroutine would exit
                    //and nobody would be listeding the 'doneChan'. This is why it has to be buffered.
                    case <-ctx.Done():
                            fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
                            fmt.Printf ("took longer than 5 secs\r\n")
                    case <-doneChan:
                            fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
                            fmt.Printf ("instant\r\n")
                    }
            }(doneC,w)

    default:
            fmt.Fprintf(w, "No such Api")
    }
}

func worker(jobs <-chan QueueElement) {
    for {
            job := <-jobs
            processExec ("START /i /b try.cmd")
            fmt.Printf ("job done")
        //  processExec("START /i /b processAndPrint.exe -" + job.jobid)
            job.doneChan <- struct{}{}

    }
}

func main() {
      db, err := sql.Open("sqlite3", "jobs.sqlite")
      if err := db.Ping(); err != nil {
        log.Fatal(err)
    }

      db.SetMaxOpenConns(1) // prevents locked database error
      _, err = db.Exec(setupSQL)
      if err != nil {
          log.Fatal(err)
      }

    // create a GlobalVars instance
    gv := GlobalVars{
        db  :   db,
        jobs: make(chan QueueElement),
    }
    go worker (gv.jobs)
    // create an http.Server instance and specify our job manager as
    // the handler for requests.
    server := http.Server{
        Handler: &gv,
        Addr : ":8888",
    }
    // start server and accept connections.
    log.Fatal(server.ListenAndServe())
}

The above code is of the serveHTTP and the worker with help from here, initially the func inside the ServeHTTP was a go routine and it's here the whole conflict arises for me - the concept is that in the serveHTTP it spawns a process that will get reply from the worker if the worker were able to process the job in time, within 5 seconds.

If the job was able to finish in 1 second, I want to reply back instantly after that 1 second to the client, if it takes 3 I want to reply after 3, if it takes more than 5 I will send reply back after 5 seconds (if the job takes 13 seconds I still want to reply after 5 seconds). That the client has to poll on the job from now on - but the conflict is:

a) When ServeHTTP exits - then the ResponseWriter closes - and to be able to reply back to the client, we have to write the answer to the ResponseWriter.

b) if I block serveHTTP (like in the code example below where I don't call the func as a go routine) then it affects not only that single API call but it seems that all others after that will be affected, so the first call in will be served correctly in time but the calls that would be coming in at the same time after the first will be sequentially delayed by the blocking operation.

c) if I don't block it ex - and change it to a go routine :

    gv.jobs <- newPrintJob
    go func(doneChan chan struct{},w http.ResponseWriter) {

Then there's no delay - can call in many APIs - but problem is here serveHTTP exists right away and thereby kills ResponseWriter and then I'm not able to reply back to the client.

I am not sure how I can get around this conflict where I don't cause any blockage to serveHTTP so I can handle all requests parallel, but still able to reply back to the ResponseWriter in question.

Is there any way of preventing serveHTTP of shutting down a responsewriter even though the function exits?


问:
picasso error. image URL COMES from database but not set in picasso image
Picasso.with(context).load(Image.get(position)).into(new Target() {@Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from{Log.d("abhinav1", "onBitmapLoaded: "+bitmap); r.setBackground(new BitmapDrawable(bitmap));}@Override public void onBitmapFailed(Drawable errorDrawable{}@Override public void onPrepareLoad(Drawable placeHolderDrawable) {
}});</p>

答:
In your onBitmapLoaded method, you can use

```<code>   @Override
     public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom >from) {
         Log.d("abhinav1", "onBitmapLoaded: "+bitmap);
         r.setBackground(new BitmapDrawable(context.getResources(), bitmap));
     }
</code>```

please pass the Resources in the BitmapDrawable constructor.

ContentLicense: CC BY-SA 3.0

Body:
In your onBitmapLoaded method, you can use

   @Override
     public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom >from) {
         Log.d("abhinav1", "onBitmapLoaded: "+bitmap);
         r.setBackground(new BitmapDrawable(context.getResources(), bitmap));
     }

please pass the Resources in the BitmapDrawable constructor.


问:
Reading/writing config struct in Cap'nProto
I have a C++ embedded app and I would like to create a web interface to configure it.

My plan is to describe the configuration structs in Cap'nProto then use the generated code on C++ and Javascript side.

A config scenario would be the following:

web app asks for the actual config (Javascript)

native app serves the actual config - serialization/write (C++)

web app displays the actual config after deserialization/read (Javascript)

user can modify the config in the web app - HOW? (Javascript)

web app sends back the new config - serialization/write (Javascript)

native app uses the new config after deserialization/read (C++)

native app can modify the config - HOW? (C++)

4 and 7 are the tricky parts, because as far as I understand the API I can only deserialize a reader that is read only, however I would like to modify and re-serialize it later.

My questions are the followings:

Is the described scenario the best approach to do what I want or I should do something totally different?

Can I de-serialize a builder? Or somehow transform a reader into a builder (without copying)

Should I use the generated C++ / Javascript structs as a direct source of configuration (actual code <-> Cap'nProto structs) or I should introduce "native" structs to interact with (actual code <-> "native" structs <->(serialize/deserialize) Cap'nProto structs)

答:
To answer your second question, you can initialize a Builder from a Reader, like:

```<code>fooBulider.setBar(someBarReader);
</code>```

Or for the top-level MessageReader/MessageBuilder:

```<code>messageBuilder.setRoot<RootType>(messageReader.getRoot<RootType>());
</code>```

This does require a copy, but for your use case, that copy is probably not a big deal. Configs usually aren't multi-gigabyte files nor performance-sensitive.

In theory, it is also possible to create a MessageBuilder that is directly initialized from existing message data which it then modifies in-place. However, there are some major caveats with this. See:

https://github.com/capnproto/capnproto/blob/3aa2b2aa02edb1c160b154ad74c08c929a02512a/c++/src/capnp/message.h#L168-L187

Regarding your other two questions, it's really up to you. There are legitimate arguments both ways and it'll really come down to the specific use case and your personal taste.

Body:
To answer your second question, you can initialize a Builder from a Reader, like:

fooBulider.setBar(someBarReader);

Or for the top-level MessageReader/MessageBuilder:

messageBuilder.setRoot<RootType>(messageReader.getRoot<RootType>());

This does require a copy, but for your use case, that copy is probably not a big deal. Configs usually aren't multi-gigabyte files nor performance-sensitive.

In theory, it is also possible to create a MessageBuilder that is directly initialized from existing message data which it then modifies in-place. However, there are some major caveats with this. See:

https://github.com/capnproto/capnproto/blob/3aa2b2aa02edb1c160b154ad74c08c929a02512a/c++/src/capnp/message.h#L168-L187

Regarding your other two questions, it's really up to you. There are legitimate arguments both ways and it'll really come down to the specific use case and your personal taste.


问:
Simple jQuery page not working
```<code>  …
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div id ="iAmNew">id="iAmNew"</div>
  <script>
    $(#iAmNew).style("border", "4px dotted blue");
  </script>
  …
</code>```

答: Use $("#iAmNew").css("border", "4px dotted blue");

Title: Simple jQuery page not working

Body:
  …

id="iAmNew"

  …


问:
Volley request returns data twice
As the title implies, my Volley request returns data twice and I tried all the solutions I can find including this and this

This is my code just in case I did something else wrong.

```<code>JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        dataCallback.onSuccess(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dataCallback.onError(error);
                    }
                }
        ) {
            @Override
            public Map<String, String> getHeaders() {

                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("trakt-api-version", "2");
                headers.put("trakt-api-key", client_id);
                return headers;
            }
        };
        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
                0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(jsonArrayRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

答:
You have implement retry policy in your code, that give you twice response</p>

```<code> //try after comment or remove below line
  jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
            0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
</code>```

Title: Volley request returns data twice

Body:
As the title implies, my Volley request returns data twice and I tried all the solutions I can find including this and this

This is my code just in case I did something else wrong.

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        dataCallback.onSuccess(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dataCallback.onError(error);
                    }
                }
        ) {
            @Override
            public Map<String, String> getHeaders() {

                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("trakt-api-version", "2");
                headers.put("trakt-api-key", client_id);
                return headers;
            }
        };
        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
                0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(jsonArrayRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

Body:
You have implement retry policy in your code, that give you twice response

 //try after comment or remove below line
  jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
            0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


问:
AttributeError: 'file' object has no attribute '_committed' - django
I need to create a record with a one-to-one relationship and another field, the model of the one-to-one relationship has a filefield, when I create it, it throws me the error of the title.

This is my code.
Models

```<code>class Proyecto(models.Model):
    user = models.CharField(max_length=50)
    nombre_p = models.CharField(max_length=50)
    descripcion_p = models.CharField(max_length=50)
    file_arff = models.FileField(upload_to='arff')

    def __unicode__(self):
        return str(self.file_arff)

class Escenario(models.Model):
    proyecto = models.ForeignKey(Proyecto)
    file_txt = models.FileField(upload_to='txt/')
</code>```

View

```<code>id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
escenario = Escenario(proyecto=id_proyecto, file_txt=file_txt)
            escenario.save()

</code>```

throw me this error :  AttributeError: 'file' object has no attribute '_committed'

答:
models

```<code>class Escenario(models.Model):
    proyecto = models.ForeignKey(Proyecto, related_name="xxxxx")
    file_txt = models.FileField(upload_to='txt/',  null=True, blank=True)
</code>```

views

```<code>id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
obj = Poyecto.objects.filter(id=id_proyecto)
file_txt = None #Or you can add a file here that you want to attach to the modal.
if file_txt = None:
     instance = Escenario.objects.create(proyecto=obj)
else:
     instance = Escenario.objects.create(proyecto=obj, file_txt=file_txt)
for x in obj:
       instance.xxxxx.add(x)
</code>```

Body:
I need to create a record with a one-to-one relationship and another field, the model of the one-to-one relationship has a filefield, when I create it, it throws me the error of the title.

This is my code.
Models

class Proyecto(models.Model):
    user = models.CharField(max_length=50)
    nombre_p = models.CharField(max_length=50)
    descripcion_p = models.CharField(max_length=50)
    file_arff = models.FileField(upload_to='arff')

    def __unicode__(self):
        return str(self.file_arff)

class Escenario(models.Model):
    proyecto = models.ForeignKey(Proyecto)
    file_txt = models.FileField(upload_to='txt/')

View

id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
escenario = Escenario(proyecto=id_proyecto, file_txt=file_txt)
            escenario.save()

throw me this error :  AttributeError: 'file' object has no attribute '_committed'

Body:
models

class Escenario(models.Model):
    proyecto = models.ForeignKey(Proyecto, related_name="xxxxx")
    file_txt = models.FileField(upload_to='txt/',  null=True, blank=True)

views

id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
obj = Poyecto.objects.filter(id=id_proyecto)
file_txt = None #Or you can add a file here that you want to attach to the modal.
if file_txt = None:
     instance = Escenario.objects.create(proyecto=obj)
else:
     instance = Escenario.objects.create(proyecto=obj, file_txt=file_txt)
for x in obj:
       instance.xxxxx.add(x)


问:
.NET Core 2.1 Npgsql.EntityFrameworkCore.PostgreSQL Code-First
I create a project in which I would like to connect to an SQLite provider for testing purposes, and use PostgreSQL on production.

```<code>protected override void OnConfiguring(DbContextOptionsBuilder opt)
{
 #if DEBUG
  opt.UseSqlite("Data Source=blogging.db");
 #endif
 #if !DEBUG
  opt.UseNpgsql("Host=localhost;Database=xxxx;Username=xxxxx;Password=xxxxx");
 #endif
}
</code>```

I would like to use the code-first strategy. For SQLite - no problem:

```<code>dotnet ef migrations add InitialCreate
dotnet ef database update
</code>```

In conclusion, is there a similar solution for PostgeSQL (OpenSource)?

答:
I'm working with postgreSQL just like you are saying.

I use this 2 nugget packages:

Npgsql;

Npgsql.EntityFrameworkCore.PostgreSQL

And I just add this to your Startup.cs -> ConfigureServices:

```<code>options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
</code>```

And this to appsettings.json

```<code>"ConnectionStrings": {

       "DefaultConnection": "Server=localhost;Port=5432;Database=postgresTest;User Id=postgres;Password=xyz;"
 }
</code>```

And then I just add a Migration and Update the DB:

dotnet ef migrations add MigrationTest

dotnet ef database update

Then everything work fine. I hope that this can help you :)

Body:
I create a project in which I would like to connect to an SQLite provider for testing purposes, and use PostgreSQL on production.

protected override void OnConfiguring(DbContextOptionsBuilder opt)
{
 #if DEBUG
  opt.UseSqlite("Data Source=blogging.db");
 #endif
 #if !DEBUG
  opt.UseNpgsql("Host=localhost;Database=xxxx;Username=xxxxx;Password=xxxxx");
 #endif
}

I would like to use the code-first strategy. For SQLite - no problem:

dotnet ef migrations add InitialCreate
dotnet ef database update

In conclusion, is there a similar solution for PostgeSQL (OpenSource)?

Body:
I'm working with postgreSQL just like you are saying.

I use this 2 nugget packages:

Npgsql;

Npgsql.EntityFrameworkCore.PostgreSQL

And I just add this to your Startup.cs -> ConfigureServices:

options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

And this to appsettings.json

"ConnectionStrings": {

       "DefaultConnection": "Server=localhost;Port=5432;Database=postgresTest;User Id=postgres;Password=xyz;"
 }

And then I just add a Migration and Update the DB:

dotnet ef migrations add MigrationTest

dotnet ef database update

Then everything work fine. I hope that this can help you :)


答:
It doesn't work because you used a non-existant jQuery method, .style() instead of .css(). Try:

```<code>$('#iAmNew').css("border", "4px dotted blue");
</code>```

And, basically, 'what Adam said' (in comments):

And he forgot the quotes around the selector (just pointing it out).

If you want to use the native JavaScript style you should use:

```<code>document.getElementById('iAmNew').style.border = '4px dotted blue';
</code>```

Reference:

css().

Title: Simple jQuery page not working

Body:
  …

id="iAmNew"

  …

Body:
It doesn't work because you used a non-existant jQuery method, .style() instead of .css(). Try:

$('#iAmNew').css("border", "4px dotted blue");

And, basically, 'what Adam said' (in comments):

And he forgot the quotes around the selector (just pointing it out).

If you want to use the native JavaScript style you should use:

document.getElementById('iAmNew').style.border = '4px dotted blue';

Reference:

css().


问:
How to get the number of rows in a database table with Flutter SQFlite
How do I get the row count of a database table in Flutter. I am using the SQFlite plugin.

I assume that it is similar to Android, but Android has DatabaseUtils.queryNumEntries(db, TABLE_NAME). Does SQFlite have something similar?

I am answering the question to the best of my knowledge below, but I would be glad for a better answer if there is one.

答:
You can also use </p>

```<code>List<Map> list = await db.rawQuery('SELECT * FROM table_name');
int count = list.length;
</code>```

Body:
You can also use

List<Map> list = await db.rawQuery('SELECT * FROM table_name');
int count = list.length;


问:
Transactions in the Repository Pattern
How do I encapsulate the saving of more than one entity in a transactional manner using the repository pattern?  For example, what if I wanted to add an order and update the customer status based on that order creation, but only do so if the order completed successfully?  Keep in mind that for this example, orders are not a collection inside the customer.  They are their own entity.

This is just a contrived example, so I don’t really care whether orders should or should not be inside the customer object or even in the same bounded context.  I don’t really care what underlying technology will be used (nHibernate, EF, ADO.Net, Linq, etc.)  I just want to see what some calling code might look like in this admittedly contrived example of an all or nothing operation.

答:
You can add a transaction parameter to the end of methods that you want to run in a transaction and give it a default value of null. Thus, if you don't want to run the method in an existing transaction then leave off the end parameter or explicitly pass null.

Inside these methods you can check the parameter for null to determine whether to  create a new transaction or else use one passed in. This logic can be pushed to a base class.

This keeps your methods purer than when using a context based solution.

```<code>void Update(int itemId, string text, IDbTransaction trans = null) =>
   RunInTransaction(ref trans, () =>
   {
      trans.Connection.Update("...");
   });

void RunInTransaction(ref IDbTransaction transaction, Action f)
{
    if (transaction == null)
    {
        using (var conn = DatabaseConnectionFactory.Create())
        {
            conn.Open();

            using (transaction = conn.BeginTransaction())
            {
                f();

                transaction.Commit();
            }
        }
    }
    else
    {
        f();
    }
}

Update(1, "Hello World!");
Update(1, "Hello World!", transaction);
</code>```

Then you can have a transaction runner for your service layer...

```<code>public class TransactionRunner : ITransactionRunner
{
    readonly IDatabaseConnectionFactory databaseConnectionFactory;

    public TransactionRunner(IDatabaseConnectionFactory databaseConnectionFactory) =>
        this.databaseConnectionFactory = databaseConnectionFactory;

    public void RunInTransaction(Action<IDbTransaction> f)
    {
        using (var conn = databaseConnectionFactory.Create())
        {
            conn.Open();

            using (var transaction = conn.BeginTransaction())
            {
                f(transaction);

                transaction.Commit();
            }
        }
    }

    public async Task RunInTransactionAsync(Func<IDbTransaction, Task> f)
    {
        using (var conn = databaseConnectionFactory.Create())
        {
            conn.Open();

            using (var transaction = conn.BeginTransaction())
            {
                await f(transaction);

                transaction.Commit();
            }
        }
    }
}
</code>```

And a service method might look like this...

```<code>void MyServiceMethod(int itemId, string text1, string text2) =>
   transactionRunner.RunInTransaction(trans =>
   {
      repos.UpdateSomething(itemId, text1, trans);
      repos.UpdateSomethingElse(itemId, text2, trans);
   });
</code>```

Which is easy to mock for unit testing...

```<code>public class MockTransactionRunner : ITransactionRunner
{
    public void RunInTransaction(Action<IDbTransaction> f) => f(null);
    public Task RunInTransactionAsync(Func<IDbTransaction, Task> f) => f(null);
}
</code>```

OwnerDisplayName: Charles Graham

ContentLicense: CC BY-SA 2.5

Title: Transactions in the Repository Pattern

Body:
You can add a transaction parameter to the end of methods that you want to run in a transaction and give it a default value of null. Thus, if you don't want to run the method in an existing transaction then leave off the end parameter or explicitly pass null.

Inside these methods you can check the parameter for null to determine whether to  create a new transaction or else use one passed in. This logic can be pushed to a base class.

This keeps your methods purer than when using a context based solution.

void Update(int itemId, string text, IDbTransaction trans = null) =>
   RunInTransaction(ref trans, () =>
   {
      trans.Connection.Update("...");
   });

void RunInTransaction(ref IDbTransaction transaction, Action f)
{
    if (transaction == null)
    {
        using (var conn = DatabaseConnectionFactory.Create())
        {
            conn.Open();

            using (transaction = conn.BeginTransaction())
            {
                f();

                transaction.Commit();
            }
        }
    }
    else
    {
        f();
    }
}

Update(1, "Hello World!");
Update(1, "Hello World!", transaction);

Then you can have a transaction runner for your service layer...

public class TransactionRunner : ITransactionRunner
{
    readonly IDatabaseConnectionFactory databaseConnectionFactory;

    public TransactionRunner(IDatabaseConnectionFactory databaseConnectionFactory) =>
        this.databaseConnectionFactory = databaseConnectionFactory;

    public void RunInTransaction(Action<IDbTransaction> f)
    {
        using (var conn = databaseConnectionFactory.Create())
        {
            conn.Open();

            using (var transaction = conn.BeginTransaction())
            {
                f(transaction);

                transaction.Commit();
            }
        }
    }

    public async Task RunInTransactionAsync(Func<IDbTransaction, Task> f)
    {
        using (var conn = databaseConnectionFactory.Create())
        {
            conn.Open();

            using (var transaction = conn.BeginTransaction())
            {
                await f(transaction);

                transaction.Commit();
            }
        }
    }
}

And a service method might look like this...

void MyServiceMethod(int itemId, string text1, string text2) =>
   transactionRunner.RunInTransaction(trans =>
   {
      repos.UpdateSomething(itemId, text1, trans);
      repos.UpdateSomethingElse(itemId, text2, trans);
   });

Which is easy to mock for unit testing...

public class MockTransactionRunner : ITransactionRunner
{
    public void RunInTransaction(Action<IDbTransaction> f) => f(null);
    public Task RunInTransactionAsync(Func<IDbTransaction, Task> f) => f(null);
}


问:
I'm trying to understand how substring call is working in this code?
I know how substring works, but I was trying to understand how it works in the code below. The goal was to find the longest common prefix in an array of strings. The string input was {flower, flow, fleece}. It looks like substring is just taking the entire word of flower, when it's not 0, each time, as 0 to length-1 is going to give the entire word.

```<code> public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    return prefix;
}
</code>```

The output is fl. I'm just trying to understand why.

答:
Whilst this isn't directly what you are asking about, it is worth mentioning that using indexOf and substring is not a good way to approach this.

strs[i].indexOf(prefix) != 0 is an inefficient way to check if a string starts with something. This is because if it finds the string doesn't start with prefix, it keeps on searching for an occurrence at other positions - and it doesn't matter if it appears there.

A more efficient check would be !strs[i].startsWith(prefix): as soon as it finds the string doesn't start with the prefix, it stops.

Then, using substring to chop a character off the end of the string is inefficient too: each time it chops off one character, it creates a new string, and then you check again; but you might have to chop off lots of individual characters before you find a matching prefix.

You can avoid the "creating objects" bit of this, by using strs[i].regionMatches(0, prefix, 0, someLength), where someLength is an int that starts off at prefix.length(), and you decrement until regionMatches returns true. But this is still inefficient in that you are decrementing it one at a time.

It's easier if you do it the other way: start with someLength at zero, and increment it until either:

It equals the length of prefix: someLength >= prefix.length()

It equals the length of strs[i]: someLength >= strs[i].length()

The corresponding chars at that position don't match: prefix.charAt(someLength) != strs[i].charAt(someLength)

This is basically what startsWith does, but by doing it "yourself", you find out the position where the strings differ.

Then, use prefix = prefix.substring(0, someLength); to chop it in one go. Or don't chop it at all: you can simply store the length of the common prefix, and do the substring once, at the end.

The code would look something like:

```<code>public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    int prefixLength = strs[0].length();
    for (int i = 1; i < strs.length; i++) {
        int s = 0;
        while (s < prefixLength
            && s < strs[i].length()
            && strs[0].charAt(s) == strs[i].charAt(s)) {
          ++s;
        }
        prefixLength = s;
    }
    return strs[0].substring(0, prefixLength);
}
</code>```

Body:
I know how substring works, but I was trying to understand how it works in the code below. The goal was to find the longest common prefix in an array of strings. The string input was {flower, flow, fleece}. It looks like substring is just taking the entire word of flower, when it's not 0, each time, as 0 to length-1 is going to give the entire word.

 public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    return prefix;
}

The output is fl. I'm just trying to understand why.

Body:
Whilst this isn't directly what you are asking about, it is worth mentioning that using indexOf and substring is not a good way to approach this.

strs[i].indexOf(prefix) != 0 is an inefficient way to check if a string starts with something. This is because if it finds the string doesn't start with prefix, it keeps on searching for an occurrence at other positions - and it doesn't matter if it appears there.

A more efficient check would be !strs[i].startsWith(prefix): as soon as it finds the string doesn't start with the prefix, it stops.

Then, using substring to chop a character off the end of the string is inefficient too: each time it chops off one character, it creates a new string, and then you check again; but you might have to chop off lots of individual characters before you find a matching prefix.

You can avoid the "creating objects" bit of this, by using strs[i].regionMatches(0, prefix, 0, someLength), where someLength is an int that starts off at prefix.length(), and you decrement until regionMatches returns true. But this is still inefficient in that you are decrementing it one at a time.

It's easier if you do it the other way: start with someLength at zero, and increment it until either:

It equals the length of prefix: someLength >= prefix.length()

It equals the length of strs[i]: someLength >= strs[i].length()

The corresponding chars at that position don't match: prefix.charAt(someLength) != strs[i].charAt(someLength)

This is basically what startsWith does, but by doing it "yourself", you find out the position where the strings differ.

Then, use prefix = prefix.substring(0, someLength); to chop it in one go. Or don't chop it at all: you can simply store the length of the common prefix, and do the substring once, at the end.

The code would look something like:

public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    int prefixLength = strs[0].length();
    for (int i = 1; i < strs.length; i++) {
        int s = 0;
        while (s < prefixLength
            && s < strs[i].length()
            && strs[0].charAt(s) == strs[i].charAt(s)) {
          ++s;
        }
        prefixLength = s;
    }
    return strs[0].substring(0, prefixLength);
}


问:
How to do Convert Latitude/Longitude To Address
I wrote some code this codes worked but only get latitude and longitude
but ı want  convert latitude and longitude from Street adress.

<!DOCTYPE html>

  <title>location</title>

```

答:
Try this for Google Reverse Geocoding:

Reverse geocoding Example


问:
The place where to execute custom code while migration
Guys please advice. I'm release new version of software and there were some braking changes, to order properly update from previous version i need to execute custom code on applying certain migration.
Update steps are:
1. Get all records from one table
2. Foreach thought them and create appropriate record in other tables
I prefer to use my "Manager" from business logic layer(core)

I don't know yet how to implements this. Please give me advice or code sample would be better.
So far I see 3 places where I can put these logic.
1. Migration file itself. in EF layer.
2. Migrator project.
3. Seed file in EF layer.

答: According to @Avin Kavish recommendation I've created method in Migrator project with additional flag "-migrateToV2" and create method which use my manager from core to update data properly. Thanks. </p>


问:
CSV Import to MySQL Table with image copy
Wondering if anyone would be so kind to help me with a addition to this script i have found online:

```<code>    if(isset($_POST['SUBMIT']))
{
     $fname = $_FILES['sel_file']['name'];

     $chk_ext = explode(".",$fname);

     if(strtolower($chk_ext[1]) == "csv")
     {

         $filename = $_FILES['sel_file']['tmp_name'];
         $handle = fopen($filename, "r");

         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
         {
            $sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
            mysql_query($sql) or die(mysql_error());
         }

         fclose($handle);
         echo "Successfully Imported";
     }
     else
     {
         echo "Invalid File";
     }
}

<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>

    Import File : <input type='text' name='sel_file' size='20'>
    <input type='submit' name='submit' value='submit'>

</form>
</code>```

i have a csv which i want to import a bunch of data and this piece of code i have found online should do the trick but i have a couple of extra things i need to apply and hoping someone would be willing to write additional code to this for this to work.

i have 2 fields in the csv container image paths from another url:

image: http://blag.com/images.jpg
images: http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg

i am wanting to grab the image from the external url and upload it to a path on the site itself and then set the local image path and image name in the database

the images part contains multiple images which i need to do the same but apply to another field with those on them but would need to be able to display those additional images on the page but not sure if possible with that ; seperator in the database but guess you guys will know if its possible to fectha dn display but thats something ele i guess

if someone would be so kind to help me adapt that code so i can do that would be awesome as need to import a lot of data tonight :)

Thanks in advanced!

答:
I wouldn't use php for this task.  For importing the csv data I would use mysqlimport as it is much more efficient and less error prone then rolling your own php solution.  For retrieving the images and storing them locally you could easily write a ruby or perl or even a bash script with curl to fetch the image and place them in the correct directory.

If this is part of another tool written in PHP then I would = look to using a system command to execute the mysqlimport on the local file.  Then I would use the curl facility to grab the images and place them in the appropriate directory.

Body:
Wondering if anyone would be so kind to help me with a addition to this script i have found online:

    if(isset($_POST['SUBMIT']))
{
     $fname = $_FILES['sel_file']['name'];

     $chk_ext = explode(".",$fname);

     if(strtolower($chk_ext[1]) == "csv")
     {

         $filename = $_FILES['sel_file']['tmp_name'];
         $handle = fopen($filename, "r");

         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
         {
            $sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
            mysql_query($sql) or die(mysql_error());
         }

         fclose($handle);
         echo "Successfully Imported";
     }
     else
     {
         echo "Invalid File";
     }
}

<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>

    Import File : <input type='text' name='sel_file' size='20'>
    <input type='submit' name='submit' value='submit'>

</form>

i have a csv which i want to import a bunch of data and this piece of code i have found online should do the trick but i have a couple of extra things i need to apply and hoping someone would be willing to write additional code to this for this to work.

i have 2 fields in the csv container image paths from another url:

image: http://blag.com/images.jpg
images: http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg

i am wanting to grab the image from the external url and upload it to a path on the site itself and then set the local image path and image name in the database

the images part contains multiple images which i need to do the same but apply to another field with those on them but would need to be able to display those additional images on the page but not sure if possible with that ; seperator in the database but guess you guys will know if its possible to fectha dn display but thats something ele i guess

if someone would be so kind to help me adapt that code so i can do that would be awesome as need to import a lot of data tonight :)

Thanks in advanced!


问:
How to change 1,000,000.00 into 1.000.000,00 with ASP classic?
I want to change number 1,000,000.00 into 1.000.000,00 with ASP classic. Please help

```<code>a=1000000
response.write formatnumber(a,0)
</code>```

It shows

```<code>1,000,000
</code>```

答:
Thank you for helping me.

I add strreverse() function to your example Public Function

```<code>Public Function Format(sValue, sMask)
    Dim iPlaceHolder
    Dim sTempValue
    Dim sResult

    sTempValue = CStr(strreverse(sValue))
    sResult = sMask
    Do Until InStr(sResult, "#") = 0
        iPlaceHolder = InStr(sResult, "#")
        sResult = Replace(sResult, "#", Left(sTempValue, 1), 1, 1)
        sTempValue = Mid(sTempValue, 2)
        If Len(sTempValue) = 0 Then sResult = Left(sResult, iPlaceHolder)
    Loop
    Format = strreverse(sResult)
End Function
</code>```

response.write format(a, "###.###.###.###.###")&",00"

output: 1.000.000,00

Body:
I want to change number 1,000,000.00 into 1.000.000,00 with ASP classic. Please help

a=1000000
response.write formatnumber(a,0)

It shows

1,000,000

Body:
Thank you for helping me.

I add strreverse() function to your example Public Function

Public Function Format(sValue, sMask)
    Dim iPlaceHolder
    Dim sTempValue
    Dim sResult

    sTempValue = CStr(strreverse(sValue))
    sResult = sMask
    Do Until InStr(sResult, "#") = 0
        iPlaceHolder = InStr(sResult, "#")
        sResult = Replace(sResult, "#", Left(sTempValue, 1), 1, 1)
        sTempValue = Mid(sTempValue, 2)
        If Len(sTempValue) = 0 Then sResult = Left(sResult, iPlaceHolder)
    Loop
    Format = strreverse(sResult)
End Function

response.write format(a, "###.###.###.###.###")&",00"

output: 1.000.000,00


问:
Delete all the nodes from a list that respect a condition influenced by another list
I am studying the lists and I came across this exercise which asks me to do the following steps:

Define a function that, given two lists of integers L1 and L2, and an integer n>0, eliminate from the first list the nodes for which the sum of the contents of L1 and L2 in the corresponding position (with respect to the original positions) is a multiple of n. If L2 ends, consider only the content of L1 instead of the sum.

I tried to analyze the problem with a single list and in this case I had no problems, but in this specific case I couldn't figure out how to proceed.

my problem is that I can't understand how properly build the various cases (L1 must be always != NULL, so I have: L1 != NULL && L2 != NULL or L1 != NULL && L2 == NULL).

Can someone explain to me the procedure to be performed and where am I wrong?

This is my attempt:

```<code>    struct data
    {
       int d;
       struct data *next;
    };

    typedef struct data Nodo;
    typedef Nodo *LIST;

    void function(LIST *l1, LIST l2, int n)
    {
      LIST p, head_1, head_2;

        while((*l1 != NULL && l2 != NULL)&&((*l1)->d + l2->d) % n == 0)
        {
           p = *l1;
           *l1 = (*l1)->next;
           free(p);
        }

        while((*l1 != NULL) && ((*l1)->d + l2->d) % n == 0)
        {
            p = *l1;
            *l1 = (*l1)->next;
            free(p);
        }

        if (*l1 != NULL)
        {
           head_1 = *l1;
           head_2 = l2;

           while(head_1->next != NULL)
           {
              if (((head_1->next->d + head_2->next->d) % n) == 0)
              {
                p = head_1->next;
                head_1->next = head_1->next->next;
                free(p);
              }
              else
              {
                head_1 = head_1->next;
                head_2 = head_2->next;
              }
           }
         }
      }
</code>```

Example:

L1: 4->4->11->3->4->8->7->NULL

L2: 5->1->5->1->5

OUTPUT(L1): 4->4->4->7->NULL

答:
You have a problem of logic with the consecutive loops :

```<code>while((*l1 != NULL && l2 != NULL)&&((*l1)->d + l2->d) % n == 0) {
  ...
}
while((*l1 != NULL) && ((*l1)->d + l2->d) % n == 0){
  ...
}
</code>```

if the sum of the elements are not a multiple of n you need to move to the next element, but you do not do

Out of that to hide a pointer with a typedef like you do with typedef Nodo *LIST; is dangerous and is a good way to introduce problem, I recommend you to never do that.

You can do that :

```<code>void removeIf(Nodo ** l1, Nodo * l2, int n)
{
  while ((*l1 != NULL) && (l2 !=  NULL)) {
    if ((((*l1)->d + l2->d) % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }

    l2 = l2->next;
  }

  // case where l2 is shorter than l1
  while (*l1 != NULL) {
    if (((*l1)->d % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }
  }
}
</code>```

Making a full program for

L1: 4->4->11->3->4->8->7

L2: 5->1->5->1->5

N : 2

```<code>#include <stdio.h>
#include <stdlib.h>

struct data {
  int d;
  struct data *next;
};

typedef struct data Nodo;

void removeIf(Nodo ** l1, Nodo * l2, int n)
{
  while ((*l1 != NULL) && (l2 !=  NULL)) {
    if ((((*l1)->d + l2->d) % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }

    l2 = l2->next;
  }

  // case where l2 is shorter than l1
  while (*l1 != NULL) {
    if (((*l1)->d % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }
  }
}

Nodo * make(int v, Nodo * n)
{
  Nodo * r = malloc(sizeof(Nodo));

  r->d = v;
  r->next = n;
  return r;
}

void del(Nodo ** pl)
{
  while (*pl != NULL) {
    Nodo * n = *pl;

    *pl = (*pl)->next;
    free(n);
  }
}

int main()
{
  Nodo * l1 = make(4, make(4, make(11, make(3, make(4, make(8, make(7, NULL)))))));
  Nodo * l2 = make(5, make(1, make(5, make(1, make(5, NULL)))));

  removeIf(&l1, l2, 2);

  /* show result */
  for (Nodo * l = l1; l != NULL; l = l->next)
    printf("%d ", l->d);
  putchar('\n');

  /* free resources */
  del(&l1);
  del(&l2);

  return 0;
}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra ll.c
pi@raspberrypi:/tmp $ ./a.out
4 4 4 7
pi@raspberrypi:/tmp $
</code>```

Execution under valgrind :

```<code>pi@raspberrypi:/tmp $ valgrind ./a.out
==3758== Memcheck, a memory error detector
==3758== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3758== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3758== Command: ./a.out
==3758==
4 4 4 7
==3758==
==3758== HEAP SUMMARY:
==3758==     in use at exit: 0 bytes in 0 blocks
==3758==   total heap usage: 13 allocs, 13 frees, 1,120 bytes allocated
==3758==
==3758== All heap blocks were freed -- no leaks are possible
==3758==
==3758== For counts of detected and suppressed errors, rerun with: -v
==3758== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $
</code>```

Body:
I am studying the lists and I came across this exercise which asks me to do the following steps:

Define a function that, given two lists of integers L1 and L2, and an integer n>0, eliminate from the first list the nodes for which the sum of the contents of L1 and L2 in the corresponding position (with respect to the original positions) is a multiple of n. If L2 ends, consider only the content of L1 instead of the sum.

I tried to analyze the problem with a single list and in this case I had no problems, but in this specific case I couldn't figure out how to proceed.

my problem is that I can't understand how properly build the various cases (L1 must be always != NULL, so I have: L1 != NULL && L2 != NULL or L1 != NULL && L2 == NULL).

Can someone explain to me the procedure to be performed and where am I wrong?

This is my attempt:

    struct data
    {
       int d;
       struct data *next;
    };

    typedef struct data Nodo;
    typedef Nodo *LIST;

    void function(LIST *l1, LIST l2, int n)
    {
      LIST p, head_1, head_2;

        while((*l1 != NULL && l2 != NULL)&&((*l1)->d + l2->d) % n == 0)
        {
           p = *l1;
           *l1 = (*l1)->next;
           free(p);
        }

        while((*l1 != NULL) && ((*l1)->d + l2->d) % n == 0)
        {
            p = *l1;
            *l1 = (*l1)->next;
            free(p);
        }

        if (*l1 != NULL)
        {
           head_1 = *l1;
           head_2 = l2;

           while(head_1->next != NULL)
           {
              if (((head_1->next->d + head_2->next->d) % n) == 0)
              {
                p = head_1->next;
                head_1->next = head_1->next->next;
                free(p);
              }
              else
              {
                head_1 = head_1->next;
                head_2 = head_2->next;
              }
           }
         }
      }

Example:

L1: 4->4->11->3->4->8->7->NULL

L2: 5->1->5->1->5

OUTPUT(L1): 4->4->4->7->NULL

Body:
You have a problem of logic with the consecutive loops :

while((*l1 != NULL && l2 != NULL)&&((*l1)->d + l2->d) % n == 0) {
  ...
}
while((*l1 != NULL) && ((*l1)->d + l2->d) % n == 0){
  ...
}

if the sum of the elements are not a multiple of n you need to move to the next element, but you do not do

Out of that to hide a pointer with a typedef like you do with typedef Nodo *LIST; is dangerous and is a good way to introduce problem, I recommend you to never do that.

You can do that :

void removeIf(Nodo ** l1, Nodo * l2, int n)
{
  while ((*l1 != NULL) && (l2 !=  NULL)) {
    if ((((*l1)->d + l2->d) % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }

    l2 = l2->next;
  }

  // case where l2 is shorter than l1
  while (*l1 != NULL) {
    if (((*l1)->d % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }
  }
}

Making a full program for

L1: 4->4->11->3->4->8->7

L2: 5->1->5->1->5

N : 2

#include <stdio.h>
#include <stdlib.h>

struct data {
  int d;
  struct data *next;
};

typedef struct data Nodo;

void removeIf(Nodo ** l1, Nodo * l2, int n)
{
  while ((*l1 != NULL) && (l2 !=  NULL)) {
    if ((((*l1)->d + l2->d) % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }

    l2 = l2->next;
  }

  // case where l2 is shorter than l1
  while (*l1 != NULL) {
    if (((*l1)->d % n) == 0) {
      /* cell must be removed */
      Nodo * rm = *l1;

      *l1 = (*l1)->next;
      free(rm);
    }
    else {
      /* cell not removed */
      l1 = &(*l1)->next;
    }
  }
}

Nodo * make(int v, Nodo * n)
{
  Nodo * r = malloc(sizeof(Nodo));

  r->d = v;
  r->next = n;
  return r;
}

void del(Nodo ** pl)
{
  while (*pl != NULL) {
    Nodo * n = *pl;

    *pl = (*pl)->next;
    free(n);
  }
}

int main()
{
  Nodo * l1 = make(4, make(4, make(11, make(3, make(4, make(8, make(7, NULL)))))));
  Nodo * l2 = make(5, make(1, make(5, make(1, make(5, NULL)))));

  removeIf(&l1, l2, 2);

  /* show result */
  for (Nodo * l = l1; l != NULL; l = l->next)
    printf("%d ", l->d);
  putchar('\n');

  /* free resources */
  del(&l1);
  del(&l2);

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra ll.c
pi@raspberrypi:/tmp $ ./a.out
4 4 4 7
pi@raspberrypi:/tmp $

Execution under valgrind :

pi@raspberrypi:/tmp $ valgrind ./a.out
==3758== Memcheck, a memory error detector
==3758== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3758== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3758== Command: ./a.out
==3758==
4 4 4 7
==3758==
==3758== HEAP SUMMARY:
==3758==     in use at exit: 0 bytes in 0 blocks
==3758==   total heap usage: 13 allocs, 13 frees, 1,120 bytes allocated
==3758==
==3758== All heap blocks were freed -- no leaks are possible
==3758==
==3758== For counts of detected and suppressed errors, rerun with: -v
==3758== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $


问:
How many times is (+ 1) computed here?
On my functional programming exam, I had the following question:

How many times is (+ 1) function computed in the following code?

```<code>(map (+ 1) [1 .. 10]) !! 5
</code>```

where the index function is defined like this:

```<code>(h:_) !! 0 = h
(_:t) !! x = t !! (x-1)
</code>```

I would say 6 times, but the correct answer seems to be 1, and I cannot understand why. I could not find a good enough explanation of lazy evaluation in Haskell, so I would like to know what is the correct answer and why. Thank you in advance!

答:
many times is (+ 1) function computed in the following code?

It is calculated only once. map does not force to calculate f xi on the elements in the result list. These calculations are postponed (just like everything else in Haskell), only when we need to calculate the value of a specific item, we do that.

map is specified in chapter 9 of the Haskell'10 report as:

```<code>-- Map and append
map :: (a -> b) -> [a] -> [b]
map f []     = []
map f (x:xs) = f x : map f xs</code>```

There are no seq, bang patterns, etc. here to force evaluation of f x, so the map function will indeed "yield" an f x, but without evaluating f x, it is postponed until it is necessary (and it might happen that we are not interested in some of these values, and thus can save some CPU cycles).

We can take a look how Haskell will evaluate this:

```<code>   (!!) (map (+ 1) [1 .. 10]) 5
-> (!!) ((+1) 1 : map (+1) [2..10]) 5
-> (!!) (map (+1) [2..10]) 4
-> (!!) ((+1) 1 : map (+1) [3..10]) 4
-> (!!) (map (+1) [3..10]) 3
-> (!!) ((+1) 1 : map (+1) [4..10]) 3
-> (!!) (map (+1) [4..10]) 2
-> (!!) ((+1) 1 : map (+1) [5..10]) 2
-> (!!) (map (+1) [5..10]) 1
-> (!!) ((+1) 1 : map (+1) [6..10]) 1
-> (!!) (map (+1) [6..10]) 0
-> (!!) ((+1) 6 : map (+1) [7..10]) 0
-> (+1) 6
-> 7
</code>```

This is because map f [x1, x2, ..., xn] eventually maps to a list [f x1, f x2, ..., f xn], but it does not compute f xi of the elements, that computation is postponed until we actually would need the value in that list, and do something with it (like priting it).

This can result in a significant performance boost, given f is an expensive function, and we only need the value of a small amount of elements in the list.

Title: How many times is (+ 1) computed here?

Body:
On my functional programming exam, I had the following question:

How many times is (+ 1) function computed in the following code?

(map (+ 1) [1 .. 10]) !! 5

where the index function is defined like this:

(h:_) !! 0 = h
(_:t) !! x = t !! (x-1)

I would say 6 times, but the correct answer seems to be 1, and I cannot understand why. I could not find a good enough explanation of lazy evaluation in Haskell, so I would like to know what is the correct answer and why. Thank you in advance!

Body:
many times is (+ 1) function computed in the following code?

It is calculated only once. map does not force to calculate f xi on the elements in the result list. These calculations are postponed (just like everything else in Haskell), only when we need to calculate the value of a specific item, we do that.

map is specified in chapter 9 of the Haskell'10 report as:

-- Map and append
map :: (a -> b) -> [a] -> [b]
map f []     = []
map f (x:xs) = f x : map f xs

There are no seq, bang patterns, etc. here to force evaluation of f x, so the map function will indeed "yield" an f x, but without evaluating f x, it is postponed until it is necessary (and it might happen that we are not interested in some of these values, and thus can save some CPU cycles).

We can take a look how Haskell will evaluate this:

   (!!) (map (+ 1) [1 .. 10]) 5
-> (!!) ((+1) 1 : map (+1) [2..10]) 5
-> (!!) (map (+1) [2..10]) 4
-> (!!) ((+1) 1 : map (+1) [3..10]) 4
-> (!!) (map (+1) [3..10]) 3
-> (!!) ((+1) 1 : map (+1) [4..10]) 3
-> (!!) (map (+1) [4..10]) 2
-> (!!) ((+1) 1 : map (+1) [5..10]) 2
-> (!!) (map (+1) [5..10]) 1
-> (!!) ((+1) 1 : map (+1) [6..10]) 1
-> (!!) (map (+1) [6..10]) 0
-> (!!) ((+1) 6 : map (+1) [7..10]) 0
-> (+1) 6
-> 7

This is because map f [x1, x2, ..., xn] eventually maps to a list [f x1, f x2, ..., f xn], but it does not compute f xi of the elements, that computation is postponed until we actually would need the value in that list, and do something with it (like priting it).

This can result in a significant performance boost, given f is an expensive function, and we only need the value of a small amount of elements in the list.


问:
Simple Mysql table join problem
I'm designing a website to teach myself how to use table joins in mysql and have got stuck pretty early on. (The numbers are Wii friend codes, if that helps you make sense of this!)

I have 3 tables:

users:

```<code>id, firstname, surname
</code>```

games:

```<code>id, title
</code>```

numbers:

```<code>number, users_id, game_id
</code>```

The number is a unique code that belongs to the user and associates with a game.

I'm trying to get out a list of numbers for a specific game along with the names of the users they belong to.

I'm running the query:

```<code>SELECT firstname, surname, number FROM games, users, numbers WHERE numbers.game_id = games.id AND games.title = 'foogame'
</code>```

for instance, to get out all the numbers belonging to foogame. However, this returns any user who doesn't have a code for this game with a random code from another user. How do I make this query only return the users who actually have a code for that game?

答:
To follow up on Tom's answer... If you are new to MySQL, I'd suggest breaking it down in steps and be very clear on what is being grabbed from where. You can treat it as a join of two tables in which the 3rd then hops in. You can also use brackets which allow some separation when you come back to it a few months later. </p>

```<code>SELECT firstname, surname, number
    FROM
    (
        (users u INNER JOIN numbers n ON(n.user_id = u.id) )
        INNER JOIN games g ON(n.game_id = g.id)
    )
    WHERE g.title = 'foogame'
</code>```

OwnerDisplayName: Rich Bradshaw

Title: Simple Mysql table join problem

Body:
I'm designing a website to teach myself how to use table joins in mysql and have got stuck pretty early on. (The numbers are Wii friend codes, if that helps you make sense of this!)

I have 3 tables:

users:

id, firstname, surname

games:

id, title

numbers:

number, users_id, game_id

The number is a unique code that belongs to the user and associates with a game.

I'm trying to get out a list of numbers for a specific game along with the names of the users they belong to.

I'm running the query:

SELECT firstname, surname, number FROM games, users, numbers WHERE numbers.game_id = games.id AND games.title = 'foogame'

for instance, to get out all the numbers belonging to foogame. However, this returns any user who doesn't have a code for this game with a random code from another user. How do I make this query only return the users who actually have a code for that game?

Body:
To follow up on Tom's answer... If you are new to MySQL, I'd suggest breaking it down in steps and be very clear on what is being grabbed from where. You can treat it as a join of two tables in which the 3rd then hops in. You can also use brackets which allow some separation when you come back to it a few months later.

SELECT firstname, surname, number
    FROM
    (
        (users u INNER JOIN numbers n ON(n.user_id = u.id) )
        INNER JOIN games g ON(n.game_id = g.id)
    )
    WHERE g.title = 'foogame'

OwnerDisplayName: Paulo


问:
jQuery form submit: Any way to know what element triggered the submit?
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

```<code>$('form').submit(function() {
    ...code done here to validate form fields
});
</code>```

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

答:
well this will only fire if the type of the input button is like so:

```<code><input type='submit' ...
</code>```

so make sure the cancel button does not have type='submit' and it should work

Body:
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

$('form').submit(function() {
    ...code done here to validate form fields
});

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

Body:
well this will only fire if the type of the input button is like so:

<input type='submit' ...

so make sure the cancel button does not have type='submit' and it should work


问:
Python selenium: DevTools listening on ws://127.0.0.1
Today I got this message on the console when running selenium using the chromedriver. How do I suppress this?

```<code>DevTools listening on ws://127.0.0.1:12740/devtools/browser/97101fe4-3b1f-42b0-b5c8-373cc18040b6
</code>```

Relevant code:

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path='c:/bin/chromedriver233')
</code>```

I get the same message using version 2.30 of chromedriver.

I have not previously received this message. The only change I've made is updating chrome to Version 62.0.3202.94 (Official Build) (64-bit)

Python 3.6.3 64, selenium 3.4.3, Windows 7 64.

EDIT: I posted a question to the Chrome product forum at https://productforums.google.com/forum/#!topic/chrome/Dlk2j_JpmxE;context-place=forum/chrome

答:
I had the same issue, did a bit of digging and finally found a working solution. This should remove the DevTools message popping up:

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(executable_path='<path-to-chrome>', options=options)
```

As per the solution from this chromium issue.

Body:
Today I got this message on the console when running selenium using the chromedriver. How do I suppress this?

DevTools listening on ws://127.0.0.1:12740/devtools/browser/97101fe4-3b1f-42b0-b5c8-373cc18040b6

Relevant code:

from selenium import webdriver
driver = webdriver.Chrome(executable_path='c:/bin/chromedriver233')

I get the same message using version 2.30 of chromedriver.

I have not previously received this message. The only change I've made is updating chrome to Version 62.0.3202.94 (Official Build) (64-bit)

Python 3.6.3 64, selenium 3.4.3, Windows 7 64.

EDIT: I posted a question to the Chrome product forum at https://productforums.google.com/forum/#!topic/chrome/Dlk2j_JpmxE;context-place=forum/chrome

Body:
I had the same issue, did a bit of digging and finally found a working solution. This should remove the DevTools message popping up:

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(executable_path='<path-to-chrome>', options=options)

As per the solution from this chromium issue.


问:
Is it possible to change the field name in user storage with a string?
If you write conv.user.storage.something = "test" I understand that, but can you change the field name "something" in this example.  Say you had an array of values named Fruit ["Banana", "Apple"] can you read the array and then assign those values to the field name value.  It seems like you can only set the field name manually such as conv.user.storage.Banana but what if I am getting those names from an array?</p>

答:
Yes you can iterate through the array and directly assign the keys.</p>

```<code>for (const element of array) {
  conv.user.storage[element] = "text"
}
</code>```

Body:
Yes you can iterate through the array and directly assign the keys.

for (const element of array) {
  conv.user.storage[element] = "text"
}


问:
'Could not resolve bean reference against BeanFactory' With spEl annotation
I am trying to have a programmation for the next 7 days. Before I used dateadd in my query by I am using a mysql database, and it is not working,

So I tried to use spEl annotation to use it, but I have this error :

'Could not resolve bean reference against BeanFactory'

Do you have a solution of this problem or an alternative to have the same result ?

```<code>public interface ProgrammationRepository extends JpaRepository<Programmation, Long> {
    @Query("select programmation from Programmation programmation left join fetch programmation.film where programmation.dateprogrammation >= ?#{@ProgrammationRepository.addSixDay()} and programmation.dateprogrammation <= ?#{@ProgrammationRepository.addSevenDay()}")
    List<Programmation> getSevenNextDay();

    @Query("select programmation from Programmation programmation left join fetch programmation.film where programmation.film.id = :id")
    List<Programmation> getFindByFilm(@Param("id") Long id);

    default Instant addSixDay() {
        System.out.println( Instant.now().plus(6, ChronoUnit.DAYS));
        return Instant.now().minus(6, ChronoUnit.DAYS);
    }

    default Instant addSevenDay() {
        return Instant.now().plus(7, ChronoUnit.DAYS);
    }
</code>```

Regards

答:
```<code>#{@ProgrammationRepository.addSevenDay()}
</code>```

The above SpEL means that it will find a bean whose name is ProgrammationRepository and invoke its addSevenDay() method.

However , the name of ProgrammationRepository bean is programmationRepository  but not ProgrammationRepository (Default name of a spring bean is the lowerCamelCase of the class name).Change the SpEL to the following should fix the problem:

```<code>#{@programmationRepository.addSevenDay()}
</code>```

Alternatively , you can change the name of ProgrammationRepository bean to ProgrammationRepository by:

```<code>@Repository(value = "ProgrammationRepository")
public interface ProgrammationRepository extends JpaRepository<Programmation, Long> {

}
</code>```

Body:
I am trying to have a programmation for the next 7 days. Before I used dateadd in my query by I am using a mysql database, and it is not working,

So I tried to use spEl annotation to use it, but I have this error :

'Could not resolve bean reference against BeanFactory'

Do you have a solution of this problem or an alternative to have the same result ?

public interface ProgrammationRepository extends JpaRepository<Programmation, Long> {
    @Query("select programmation from Programmation programmation left join fetch programmation.film where programmation.dateprogrammation >= ?#{@ProgrammationRepository.addSixDay()} and programmation.dateprogrammation <= ?#{@ProgrammationRepository.addSevenDay()}")
    List<Programmation> getSevenNextDay();

    @Query("select programmation from Programmation programmation left join fetch programmation.film where programmation.film.id = :id")
    List<Programmation> getFindByFilm(@Param("id") Long id);

    default Instant addSixDay() {
        System.out.println( Instant.now().plus(6, ChronoUnit.DAYS));
        return Instant.now().minus(6, ChronoUnit.DAYS);
    }

    default Instant addSevenDay() {
        return Instant.now().plus(7, ChronoUnit.DAYS);
    }

Regards

Body:
#{@ProgrammationRepository.addSevenDay()}

The above SpEL means that it will find a bean whose name is ProgrammationRepository and invoke its addSevenDay() method.

However , the name of ProgrammationRepository bean is programmationRepository  but not ProgrammationRepository (Default name of a spring bean is the lowerCamelCase of the class name).Change the SpEL to the following should fix the problem:

#{@programmationRepository.addSevenDay()}

Alternatively , you can change the name of ProgrammationRepository bean to ProgrammationRepository by:

@Repository(value = "ProgrammationRepository")
public interface ProgrammationRepository extends JpaRepository<Programmation, Long> {

}


答:
Let's test it by doing something horrible. You'll need to import the Debug.Trace module for this.

```<code>ghci> (map (\x -> trace "Performing..." (x + 1)) [1..10]) !! 5
</code>```

Now, we'll get that totally safe IO action to happen every time the lambda expression is called. When we run this in GHCi, we get

```<code>Performing
7
</code>```

So only once.

As a sanity check, we could remove the !! 5 bit.

```<code>ghci> map (\x -> trace "Performing..." (x + 1)) [1..10]
[Performing
2,Performing
3,Performing
4,Performing
5,Performing
6,Performing
7,Performing
8,Performing
9,Performing
10,Performing
11]
</code>```

So it's definitely happening 10 times when we ask for the whole list.

Title: How many times is (+ 1) computed here?

Body:
Let's test it by doing something horrible. You'll need to import the Debug.Trace module for this.

ghci> (map (\x -> trace "Performing..." (x + 1)) [1..10]) !! 5

Now, we'll get that totally safe IO action to happen every time the lambda expression is called. When we run this in GHCi, we get

Performing
7

So only once.

As a sanity check, we could remove the !! 5 bit.

ghci> map (\x -> trace "Performing..." (x + 1)) [1..10]
[Performing
2,Performing
3,Performing
4,Performing
5,Performing
6,Performing
7,Performing
8,Performing
9,Performing
10,Performing
11]

So it's definitely happening 10 times when we ask for the whole list.


问:
Kotlin: return readonly Set/Collection
I want to return a readonly Set/Collection of a property.
What is the best idiomatic way in Kotlin?

In Java we could use Collections.unmodifiableSet()

```<code>val property: MutableSet<String> = mutableSetOf()

    get() {
        // ?
    }
</code>```

答:
If you want to mutate the set from within the implementation of your class, you have no other way than to have two separate properties with different types.

```<code>private val mutableProperty: MutableSet<String> = mutableSetOf()

val property: Set<String>
    get() = mutableProperty
</code>```

With this approach, your interface exposes the set as a read-only type, but an explicit cast (or a usage from Java) will anyway allow to mutate the set. If you want to ensure that the set is not mutated from outside, you can wrap it into an unmodifiable set:

```<code>val property: Set<String>
    get() = Collections.unmodifiableSet(mutableProperty)
</code>```

Optionally, make a  defensive copy, so that the caller won't see the change to the mutable set, or use any efficient 3rd-party immutable collection implementation.

Title: Kotlin: return readonly Set/Collection

Body:
I want to return a readonly Set/Collection of a property.
What is the best idiomatic way in Kotlin?

In Java we could use Collections.unmodifiableSet()

val property: MutableSet<String> = mutableSetOf()

    get() {
        // ?
    }

Body:
If you want to mutate the set from within the implementation of your class, you have no other way than to have two separate properties with different types.

private val mutableProperty: MutableSet<String> = mutableSetOf()

val property: Set<String>
    get() = mutableProperty

With this approach, your interface exposes the set as a read-only type, but an explicit cast (or a usage from Java) will anyway allow to mutate the set. If you want to ensure that the set is not mutated from outside, you can wrap it into an unmodifiable set:

val property: Set<String>
    get() = Collections.unmodifiableSet(mutableProperty)

Optionally, make a  defensive copy, so that the caller won't see the change to the mutable set, or use any efficient 3rd-party immutable collection implementation.


问:
Combining LOESS and Quantreg to caculate percentiles/quantiles for data
I am trying to calculate percentiles or quantils for data which considerably scatter.
Using the Loess function the mean is nicely presented, however, I cannot get percentile/quantils from this function.

I tried to combine quantreg with loess. This plot shows linear curves instead of loess smoothed curves.

I would like to get a result similar to this:

```<code>data(cars)
plot(cars)
lmodel <- loess(cars$dist~cars$speed,span = 0.3, degree = 1)
lpred<-predict(lmodel, newdata= 5:25,se=TRUE)
lines(5:25, lpred$fit,col='#000066',lwd=4)
lines(5:25, lpred$fit - qt(0.975, lpred$df)*lpred$se, lty=2)
lines(5:25, lpred$fit + qt(0.975, lpred$df)*lpred$se, lty=2)

#### combination of quantreg with loess

plot(cars$speed,cars$dist)
xx <- seq(min(cars$speed),max(cars$speed),1)
f <- coef(rq(loess(cars$dist~cars$speed,span = 0.3, degree = 1), tau=c(0.1,0.25,0.5,0.75,0.9)) )
yy <- cbind(1,xx)%*%f
for(i in 1:length(taus)){
  lines(xx,yy[,i],col = "gray")
}

</code>```

I also tried the suggested code, however, I could not change the settings of the smoothing. The lines showed wavy path.

```<code>library(quantreg)
data(cars)
taus <- c(0.1, 0.25, 0.5, 0.75, 0.9)
lmodel <- loess(dist ~ speed, data = cars, span = 0.9, degree = 1)
rqmodel <- rq(lmodel, tau = taus, data = cars)
f <- coef(rqmodel)
xx <- seq(min(cars$speed), max(cars$speed), length.out = nrow(cars))
yy <- predict(rqmodel)
plot(cars)
matlines(xx, yy, col = "grey",lwd=3)
</code>```

The Loess function does not provide data for quantiles as the rg would.

However, the Loess functions allows to get a curve without zigzag.
Please see the code snip. What would be the setting for tau=0.5 using the rg function to produce the same results compared with Loess function.

```<code>data(cars)
lmodel <- loess(dist ~ speed, data = cars, span = 0.9 )
plot(cars)
lines( x=4:25 , y=predict(lmodel, newdata= data.frame(speed=4:25)) ,col="Blue")
</code>```

答:
I believe the code in the question is mixing loess and quantile regressions when they are different methods and the latter does not need the former.

I will try to fit both and plot the respective results.
In the code below I will use matlines, not a for loop.

These code lines are common.

```<code>library(quantreg)

data(cars)

xx <- seq(min(cars$speed), max(cars$speed), length.out = nrow(cars))
</code>```

First the loess model.

```<code>lmodel <- loess(dist ~ speed, data = cars, span = 0.5, degree = 1)
ls_yy <- predict(lmodel, se = TRUE)
ls_yy <- cbind(ls_yy$fit,
               ls_yy$fit - 2*ls_yy$se.fit,
               ls_yy$fit + 2*ls_yy$se.fit)

plot(cars)
matlines(xx, ls_yy, col = "darkgrey")
</code>```

Now quantile regression.

```<code>taus <- c(0.1, 0.25, 0.5, 0.75, 0.9)
rqmodel <- rq(dist ~ speed, tau = taus, data = cars)

rq_yy <- predict(rqmodel)

plot(cars)
matlines(xx, rq_yy, col = "darkgrey")
</code>```

Body:
I am trying to calculate percentiles or quantils for data which considerably scatter.
Using the Loess function the mean is nicely presented, however, I cannot get percentile/quantils from this function.

I tried to combine quantreg with loess. This plot shows linear curves instead of loess smoothed curves.

I would like to get a result similar to this:

data(cars)
plot(cars)
lmodel <- loess(cars$dist~cars$speed,span = 0.3, degree = 1)
lpred<-predict(lmodel, newdata= 5:25,se=TRUE)
lines(5:25, lpred$fit,col='#000066',lwd=4)
lines(5:25, lpred$fit - qt(0.975, lpred$df)*lpred$se, lty=2)
lines(5:25, lpred$fit + qt(0.975, lpred$df)*lpred$se, lty=2)

#### combination of quantreg with loess

plot(cars$speed,cars$dist)
xx <- seq(min(cars$speed),max(cars$speed),1)
f <- coef(rq(loess(cars$dist~cars$speed,span = 0.3, degree = 1), tau=c(0.1,0.25,0.5,0.75,0.9)) )
yy <- cbind(1,xx)%*%f
for(i in 1:length(taus)){
  lines(xx,yy[,i],col = "gray")
}

I also tried the suggested code, however, I could not change the settings of the smoothing. The lines showed wavy path.

library(quantreg)
data(cars)
taus <- c(0.1, 0.25, 0.5, 0.75, 0.9)
lmodel <- loess(dist ~ speed, data = cars, span = 0.9, degree = 1)
rqmodel <- rq(lmodel, tau = taus, data = cars)
f <- coef(rqmodel)
xx <- seq(min(cars$speed), max(cars$speed), length.out = nrow(cars))
yy <- predict(rqmodel)
plot(cars)
matlines(xx, yy, col = "grey",lwd=3)

The Loess function does not provide data for quantiles as the rg would.

However, the Loess functions allows to get a curve without zigzag.
Please see the code snip. What would be the setting for tau=0.5 using the rg function to produce the same results compared with Loess function.

data(cars)
lmodel <- loess(dist ~ speed, data = cars, span = 0.9 )
plot(cars)
lines( x=4:25 , y=predict(lmodel, newdata= data.frame(speed=4:25)) ,col="Blue")

Body:
I believe the code in the question is mixing loess and quantile regressions when they are different methods and the latter does not need the former.

I will try to fit both and plot the respective results.
In the code below I will use matlines, not a for loop.

These code lines are common.

library(quantreg)

data(cars)

xx <- seq(min(cars$speed), max(cars$speed), length.out = nrow(cars))

First the loess model.

lmodel <- loess(dist ~ speed, data = cars, span = 0.5, degree = 1)
ls_yy <- predict(lmodel, se = TRUE)
ls_yy <- cbind(ls_yy$fit,
               ls_yy$fit - 2*ls_yy$se.fit,
               ls_yy$fit + 2*ls_yy$se.fit)

plot(cars)
matlines(xx, ls_yy, col = "darkgrey")

Now quantile regression.

taus <- c(0.1, 0.25, 0.5, 0.75, 0.9)
rqmodel <- rq(dist ~ speed, tau = taus, data = cars)

rq_yy <- predict(rqmodel)

plot(cars)
matlines(xx, rq_yy, col = "darkgrey")


问:
virtualenv: cannot access lib: No such virtualenv or site directory
I am using Google Cloud Platform to create a Django based http API, which uses Google's cloud SQL API and Machine Learning API.

I made a django-mysql app on my pc and is able to test it successfully on localhost. I want to deploy this app to Google Cloud.

Following are my relevant files:
app.yaml:-

```<code>runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /static
  static_dir: static/
- url: .*
  script: mysite.wsgi.application

libraries:
- name: MySQLdb
  version: 1.2.5
- name: numpy
  version: "1.6.1"

skip_files:
- ^(.*/)?- ^(.*/)?.*~$
- ^(.*/)?.*\.py[co]$
- ^(.*/)?.*/RCS/.*$
- ^(.*/)?\..*$
- ^env/.*$
</code>```

appengine_config.py:-

```<code>from google.appengine.ext import vendor
import os
vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
</code>```

I am getting a 500 error on api home. here. I am getting the following error report on my dashboard:-

```<code>Traceback (most recent call last):
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 351, in __getattr__
    self._update_configs()
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 287, in _update_configs
    self._registry.initialize()
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 160, in initialize
    import_func(self._modname)
  File "/base/data/home/apps/b~neuralnet-171308/20170628t204601.402294282540056750/appengine_config.py", line 18, in <module>
    vendor.add('lib')
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/vendor/__init__.py", line 44, in add
    'No such virtualenv or site directory' % path)
ValueError: virtualenv: cannot access lib: No such virtualenv or site directory
</code>```

Originally the appengine_config.py contained:-

```<code>from google.appengine.ext import vendor

vendor.add('lib')
</code>```

As suggested here, I changed it to the current file.

I deploy my project using gcloud app deploy. I do not understand how to use gcloud_sql_proxy for deploying.

I am for sure having a lib folder in same directory as app.yaml. I do not know what I am doing wrong. Any help or suggestion is appreciated.

答:
Run the below command in root directory of app in cloud shell and deploy.

pip install -t lib -r requirements.txt

Body:
I am using Google Cloud Platform to create a Django based http API, which uses Google's cloud SQL API and Machine Learning API.

I made a django-mysql app on my pc and is able to test it successfully on localhost. I want to deploy this app to Google Cloud.

Following are my relevant files:
app.yaml:-

runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /static
  static_dir: static/
- url: .*
  script: mysite.wsgi.application

libraries:
- name: MySQLdb
  version: 1.2.5
- name: numpy
  version: "1.6.1"

skip_files:
- ^(.*/)?- ^(.*/)?.*~$
- ^(.*/)?.*\.py[co]$
- ^(.*/)?.*/RCS/.*$
- ^(.*/)?\..*$
- ^env/.*$

appengine_config.py:-

from google.appengine.ext import vendor
import os
vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))

I am getting a 500 error on api home. here. I am getting the following error report on my dashboard:-

Traceback (most recent call last):
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 351, in __getattr__
    self._update_configs()
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 287, in _update_configs
    self._registry.initialize()
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 160, in initialize
    import_func(self._modname)
  File "/base/data/home/apps/b~neuralnet-171308/20170628t204601.402294282540056750/appengine_config.py", line 18, in <module>
    vendor.add('lib')
  File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/vendor/__init__.py", line 44, in add
    'No such virtualenv or site directory' % path)
ValueError: virtualenv: cannot access lib: No such virtualenv or site directory

Originally the appengine_config.py contained:-

from google.appengine.ext import vendor

vendor.add('lib')

As suggested here, I changed it to the current file.

I deploy my project using gcloud app deploy. I do not understand how to use gcloud_sql_proxy for deploying.

I am for sure having a lib folder in same directory as app.yaml. I do not know what I am doing wrong. Any help or suggestion is appreciated.


问:
VUE add a component with JS
Can I create/mount a VUE component calling a JS function in a fullyloaded page?

As a async call? Something like:

```<code>function getComponent(obj){
    return <component parameters="obj"></component >;
}
</code>```

答: I think what you are looking for is Vue dynamic components. What that allows you is to choose which component to load after the original component has loaded. You can do that whenever and however you want to, aka in an async way. You can read more in the Vue guides. All the code you need is there so won't repost it here again.</p>

Title: VUE add a component with JS

Body:
Can I create/mount a VUE component calling a JS function in a fullyloaded page?

As a async call? Something like:

function getComponent(obj){
    return <component parameters="obj"></component >;
}


问:
Upgrade Gradle to a new version for all projects in my IDE?
W10 OS, Eclipse 4.10 IDE

I just upgraded Gradle to 5.4.1.  I did this by going (Cygwin):

```<code>$ ./gradlew wrapper --gradle-version 5.4.1
</code>```

for all my different projects.  On the Gradle site it says this is the better way, rather than manually editing gradle-wrapper.properties.

After doing this, in Eclipse I then have to: highlight project and context menu --> Gradle --> Refresh Gradle for each project which takes a long time for each.

At the moment I only have about 10 active projects, and upgrading Gradle is not something you do every day, but as a matter of interest is there a quicker way doing an upgrade globally?

答:
Assuming you are using the Eclipse gradle plugin, you can run

```<code>./gradlew eclipse
</code>```

in the root project and it will refresh all the sub-projects in Eclipse.

Body:
W10 OS, Eclipse 4.10 IDE

I just upgraded Gradle to 5.4.1.  I did this by going (Cygwin):

$ ./gradlew wrapper --gradle-version 5.4.1

for all my different projects.  On the Gradle site it says this is the better way, rather than manually editing gradle-wrapper.properties.

After doing this, in Eclipse I then have to: highlight project and context menu --> Gradle --> Refresh Gradle for each project which takes a long time for each.

At the moment I only have about 10 active projects, and upgrading Gradle is not something you do every day, but as a matter of interest is there a quicker way doing an upgrade globally?

Body:
Assuming you are using the Eclipse gradle plugin, you can run

./gradlew eclipse

in the root project and it will refresh all the sub-projects in Eclipse.