问:
Working with handlers and threads in service, Thread.sleep makes the program to hang?
i am working on a task scheduler applications as my college project, i have a service that checks the expire time of an task. i had implemented handlers to check the expire time. When the expire time of an application is matched with current time then it sends a status bar notification. At this point i am pausing the Thread using Thread.sleep method for a minute, which is causing my application to hang. At logcat it shows heavy CPU usages by applications.

i am fetching the data from database, but it works fine when Thread.sleep is not called.
Please help.

Here is the code:

```<code>package com.apps.niit.taskm;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class ExpireTimeService extends Service {

    DataHelper dh;
    ArrayList<String> tData=new ArrayList<String>();
    String date;
    Calendar c;
    String str;
    String str1;
    String str2;
    String str3;
    String str4;
    String str5;
    int notificationID=1;
    String [][] data;
    NotificationManager notificationManager;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate(){
        super.onCreate();
        dh = new DataHelper(this);
        fetchData();
        handler.removeCallbacks(updateTimeTask);
        handler.postDelayed(updateTimeTask, 1000);
    }
    public void fetchData(){
        String eDate = android.text.format.DateFormat.format("d/M/yyyy", new java.util.Date()).toString();
        tData.addAll(this.dh.selectDate(eDate));
        data =new String[tData.size()][4];
        if(!tData.isEmpty()){
            for(int i=0; i<tData.size();i++){
                breakString(tData.get(i));
                data[i][0]=str1;
                data[i][1]=str2;
                data[i][2]=str3;
                data[i][3]=str4;
            }
        }
    }

    public void stopService(){
        stopSelf();
    }
    private Runnable updateTimeTask = new Runnable() {
        public void run(){
            try {
                String time = android.text.format.DateFormat.format("k:m", new java.util.Date()).toString();

                for(int i=0; i<tData.size();i++){
                    if(data[i][3].equals(time)){
                    //send notification code goes here
                        String serName = Context.NOTIFICATION_SERVICE;
                        notificationManager = (NotificationManager)getSystemService(serName);
                        String ticker= data[i][0]+" "+data[i][1]+" "+data[i][2]+" "+data[i][3];
                        long when= System.currentTimeMillis();
                        int icon = R.drawable.icon;
                        Notification notification = new Notification(icon, ticker,when);
                        Intent intent = new Intent (getApplicationContext(), DisplayTask.class);
                        Bundle myBundle = new Bundle();
                        myBundle.putString("str1", data[i][0]);
                        myBundle.putString("str2", data[i][1]);Log.i("data1",data[i][1]);
                        myBundle.putString("str3", data[i][2]);Log.i("data1",data[i][2]);
                        myBundle.putString("str4", data[i][3]);Log.i("data1",data[i][3]);
                        intent.putExtras(myBundle);
                        PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
                        notification.setLatestEventInfo(getApplicationContext(), "", "", launchIntent);
                        notificationID=1;
                        notificationManager.notify(notificationID, notification);
                        Thread.sleep(10000);
                    }
                }
                handler.postDelayed(this, 1000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e("Error from service", e.toString());
            }
        }
    };

    private void breakString(String str) {
        // TODO Auto-generated method stub
        str1 = str.substring(0, str.indexOf(";"));
        str = str.substring(str1.length()+1, str.length());
        str2 = str.substring(0, str.indexOf(";"));
        str = str.substring(str2.length()+1, str.length());
        str3 = str.substring(0, str.indexOf(";"));
        str4 = str.substring(str3.length()+1, str.length());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null)
            handler.removeCallbacks(updateTimeTask);
        handler = null;
    }
    private Handler handler = new Handler();
}
</code>```

答:
When you're using Handler's postDelayed function here is what happens:

Handler puts your Runnable into the current thread's Looper queue.

When time comes, your code in Runnable is run on the UI thread.

Note that its not that Handler always puts Runnable to UI thread queue. It puts Runnable to current thread's queue, and your current thread was the UI thread.

So if you put Thread.sleep or anything time consuming (like network communication) in that updateTimeTask it will hang the whole UI thread.

In your case you should use ScheduledExecutorService, see scheduleWithFixedDelay function. Or as alternative, you can start AsyncTask from your updateTimeTask function and do all heavy-lifting and Thread.sleep in doInBackgrund function.

Body:
i am working on a task scheduler applications as my college project, i have a service that checks the expire time of an task. i had implemented handlers to check the expire time. When the expire time of an application is matched with current time then it sends a status bar notification. At this point i am pausing the Thread using Thread.sleep method for a minute, which is causing my application to hang. At logcat it shows heavy CPU usages by applications.

i am fetching the data from database, but it works fine when Thread.sleep is not called.
Please help.

Here is the code:

package com.apps.niit.taskm;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class ExpireTimeService extends Service {

    DataHelper dh;
    ArrayList<String> tData=new ArrayList<String>();
    String date;
    Calendar c;
    String str;
    String str1;
    String str2;
    String str3;
    String str4;
    String str5;
    int notificationID=1;
    String [][] data;
    NotificationManager notificationManager;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate(){
        super.onCreate();
        dh = new DataHelper(this);
        fetchData();
        handler.removeCallbacks(updateTimeTask);
        handler.postDelayed(updateTimeTask, 1000);
    }
    public void fetchData(){
        String eDate = android.text.format.DateFormat.format("d/M/yyyy", new java.util.Date()).toString();
        tData.addAll(this.dh.selectDate(eDate));
        data =new String[tData.size()][4];
        if(!tData.isEmpty()){
            for(int i=0; i<tData.size();i++){
                breakString(tData.get(i));
                data[i][0]=str1;
                data[i][1]=str2;
                data[i][2]=str3;
                data[i][3]=str4;
            }
        }
    }

    public void stopService(){
        stopSelf();
    }
    private Runnable updateTimeTask = new Runnable() {
        public void run(){
            try {
                String time = android.text.format.DateFormat.format("k:m", new java.util.Date()).toString();

                for(int i=0; i<tData.size();i++){
                    if(data[i][3].equals(time)){
                    //send notification code goes here
                        String serName = Context.NOTIFICATION_SERVICE;
                        notificationManager = (NotificationManager)getSystemService(serName);
                        String ticker= data[i][0]+" "+data[i][1]+" "+data[i][2]+" "+data[i][3];
                        long when= System.currentTimeMillis();
                        int icon = R.drawable.icon;
                        Notification notification = new Notification(icon, ticker,when);
                        Intent intent = new Intent (getApplicationContext(), DisplayTask.class);
                        Bundle myBundle = new Bundle();
                        myBundle.putString("str1", data[i][0]);
                        myBundle.putString("str2", data[i][1]);Log.i("data1",data[i][1]);
                        myBundle.putString("str3", data[i][2]);Log.i("data1",data[i][2]);
                        myBundle.putString("str4", data[i][3]);Log.i("data1",data[i][3]);
                        intent.putExtras(myBundle);
                        PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
                        notification.setLatestEventInfo(getApplicationContext(), "", "", launchIntent);
                        notificationID=1;
                        notificationManager.notify(notificationID, notification);
                        Thread.sleep(10000);
                    }
                }
                handler.postDelayed(this, 1000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e("Error from service", e.toString());
            }
        }
    };

    private void breakString(String str) {
        // TODO Auto-generated method stub
        str1 = str.substring(0, str.indexOf(";"));
        str = str.substring(str1.length()+1, str.length());
        str2 = str.substring(0, str.indexOf(";"));
        str = str.substring(str2.length()+1, str.length());
        str3 = str.substring(0, str.indexOf(";"));
        str4 = str.substring(str3.length()+1, str.length());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null)
            handler.removeCallbacks(updateTimeTask);
        handler = null;
    }
    private Handler handler = new Handler();
}


来源: stackexchange

问:
How to add placeholders in or near the input fields in django models
I am trying to build a blog app in Django. The problem is that i am not able to mention any thing near the input field.

For example

There is an image field and i want mention "Only upload images of size 300px x 250px" near it. Thanks in advance

答:
First install pillow, pip install Pillow, then modify your model as below

```<code>from django.db import models

from PIL import Image

class Yourmodelname(models.Model):

    image = models.ImageField(upload_to='profile_pics', help_text = 'upload image of 250*300')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)
</code>```

Whatever be the user input image size it save in database as 300 * 300 image.

ContentLicense: CC BY-SA 4.0

Body:
First install pillow, pip install Pillow, then modify your model as below

from django.db import models

from PIL import Image

class Yourmodelname(models.Model):

    image = models.ImageField(upload_to='profile_pics', help_text = 'upload image of 250*300')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

Whatever be the user input image size it save in database as 300 * 300 image.


问:
Create a file in 700 (drwx------) directory using Dockerfile
I am using the gitlab-runner base image for my docker file

```<code>FROM gitlab/gitlab-runner:alpine
WORKDIR /app

RUN touch /etc/gitlab-runner/config.toml   # it doesn't work because of drwx------ direcotry
RUN touch /etc/config.toml                 # it worked because etc is   drwxr-xr-x directory

COPY . /app
...
...

ENTRYPOINT ["yarn"]
CMD ["run", "start"]
</code>```

Inspecting the images using a tool

When the image is created I couldn't see the config.toml file in the etc/gitlab-runner directory

Is it hidden?

How can I create config.toml file under etc/gitlab-runner directory

Also, wondering what purpose of the certs folder? what does it contain? Actually I wanted to mount the config.toml file to the host machine so that the runner details are syn always when the container is destroyed.

答:
Actually I wanted to mount the config.toml file to the host machine so that the runner details are syn always when the container is destroyed.

From this statement, I guess you no need to worry about creating a file as your intention is to mount the file from the host to the container.
On a Linux environment (on your host machine).
create a folder in your app folder and file in it as:

mkdir config
touch config.toml
```

<p>Now update your docker file as:</p>

```FROM gitlab/gitlab-runner:alpine
WORKDIR /app

COPY . .
...
...

ENTRYPOINT ["yarn"]
CMD ["run", "start"]
```

<p>Now you rebuild your image and start your container as:</p>

```docker build -t username/image_name .
docker run -v "absolute path to the folder config":"/etc/gitlab-runner/" username/image_name
```

Now you should see config.toml file mounted to the /etc/gitlab-runner and also container runs with no errors.

Body:
I am using the gitlab-runner base image for my docker file

FROM gitlab/gitlab-runner:alpine
WORKDIR /app

RUN touch /etc/gitlab-runner/config.toml   # it doesn't work because of drwx------ direcotry
RUN touch /etc/config.toml                 # it worked because etc is   drwxr-xr-x directory

COPY . /app
...
...

ENTRYPOINT ["yarn"]
CMD ["run", "start"]

Inspecting the images using a tool

When the image is created I couldn't see the config.toml file in the etc/gitlab-runner directory

Is it hidden?

How can I create config.toml file under etc/gitlab-runner directory

Also, wondering what purpose of the certs folder? what does it contain? Actually I wanted to mount the config.toml file to the host machine so that the runner details are syn always when the container is destroyed.

Body:
Actually I wanted to mount the config.toml file to the host machine so that the runner details are syn always when the container is destroyed.

From this statement, I guess you no need to worry about creating a file as your intention is to mount the file from the host to the container.
On a Linux environment (on your host machine).
create a folder in your app folder and file in it as:

mkdir config
touch config.toml

Now update your docker file as:

FROM gitlab/gitlab-runner:alpine
WORKDIR /app

COPY . .
...
...

ENTRYPOINT ["yarn"]
CMD ["run", "start"]

Now you rebuild your image and start your container as:

docker build -t username/image_name .
docker run -v "absolute path to the folder config":"/etc/gitlab-runner/" username/image_name

Now you should see config.toml file mounted to the /etc/gitlab-runner and also container runs with no errors.


问:
How can I convert a long to int in Java?
How can I convert a long to int in Java?</p>

答:
If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression
You can use it like:</p>

```<code>val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression
You can use it like:

val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)


问:
Does it make sense to use Vuejs and Reactjs on the same project
So my question is pretty self explanatory. Does it make sense to use Vue.js and React.js together on a same project ?</p>

答:
Both Vue and Reactjs are javascript Frameworks that are in themselves self sufficient. Also since both do the same job it makes sense to use either one of them.

If you use both Vue and React together it will make it more and more difficult for you to share states and data between parts written with Vue and Parts written with React.

What you would have to do is to keep them as independent modules.

Also both Vue and ReactJs have different APIs so it makes it difficult for a developer to code it out too. This will lead to bad patterns and hacks developing in your code which will later lead to issues such as maintainability and feature extension.

If you have control over your entire code, its better to just evaluate what better suits your purpose and then choose that framework for development of the entire app.

P.S. Certains exceptions to using both of them together will include a migration from framework to another in progress or your app having various modules in your App each of which independent from one another and included as plugins in the main code.


问:
Zend: get Url parameter from inside Zend_Form
Zend talk.I need to set an hidden form field as the value of an url parameter.
I have:

```<code>class Form_Custom extends Zend_Form
{
  public function init()
  {
   [..]
   $id = new Zend_Form_Element_Hidden('name');
   [..]
  }
}
</code>```

I know that I could pass it (from controller) inside an array of options while instantiating the class.But how could I tell the form to look for the URL parameter itself??

Thanks

Luca

答:
I don't think there is a way to do that because Zend_form is dissociated from the controller.
You could register in the registry your pos/get variables but thats dirty. You could also access directly $_GET/$_POST...

Or in your controller you can do:

```<code>$form = new Zend_form();
$form->populate($this->_getAllParams());
</code>```

Which will populate your form with all values from $_POST/$_GET

Body:
Zend talk.I need to set an hidden form field as the value of an url parameter.
I have:

class Form_Custom extends Zend_Form
{
  public function init()
  {
   [..]
   $id = new Zend_Form_Element_Hidden('name');
   [..]
  }
}

I know that I could pass it (from controller) inside an array of options while instantiating the class.But how could I tell the form to look for the URL parameter itself??

Thanks

Luca

Body:
I don't think there is a way to do that because Zend_form is dissociated from the controller.
You could register in the registry your pos/get variables but thats dirty. You could also access directly $_GET/$_POST...

Or in your controller you can do:

$form = new Zend_form();
$form->populate($this->_getAllParams());

Which will populate your form with all values from $_POST/$_GET


问:
How to call a random function
Say I have a class A with methods functionA(), functionB() and functionC():

```<code>class A {

int functionA () {
}

int functionB() {
}

int functionC() {
}

};
</code>```

how would I go about calling functionA, functioB and functionC at random?

答:
Method 1

One of the naive methods can be to generate a random number and call the functions based on the generated number in an if statements or switch.

```<code>#include<iostream>
#include<time.h>
using namespace std;

int main(void)
{
    A a;
    srand(time(0));
    int a = rand()%3;

    switch (a)
    {
    case 0:
        a.functionA();
        break;

    case 1:
        a.functionB();
        break;

    case 2:
        a.functionC();
        break;

    default:
        break;
    }

    return 0;
}

</code>```

Method 2

Based on the Comment by @Remy Lebeau, I recommend the following approach

```<code>int main(void)
{
    srand(time(0));

    int (A::*arr[])() = {&A::functionA, &A::functionB, &A:functionC};

/*
   **Note**
   You need to call the non-static class methods using an Object of the
   class. So we make an object and call methods using that object.
*/

    A a;

    (a.*arr[rand() % 3])();

    return 0;
}
</code>```

Edit

As suggested by @cdihowie, c/c++ random library is not recommended as the random number generated may not be uniform. We can use uniform_distribution for generating uniform pseudo random numbers. So your final code becomes as follows:

```<code>#include <iostream>
#include <random>
#include <time.h>
using namespace std;

class A
{
public:
    int functionA()
    {
        printf("inside functionA()\n");
        return 0;
    }

    int functionB()
    {
        printf("inside functionB()\n");
        return 0;
    }

    int functionC()
    {
        printf("inside functionC()\n");
        return 0;
    }
};

int main(void)
{
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine generator(seed);
    std::uniform_int_distribution<int> distribution(0, 2);

    A a;
    A *aPtr = new A();

    int (A::*arr[])() = {&A::functionA, &A::functionB, &A::functionC};

    for (int i = 0; i < 99; i++)
    {
        int num = distribution(generator);
        (a.*arr[num])();
    }
    return 0;
}
</code>```

Title: How to call a random function

Body:
Say I have a class A with methods functionA(), functionB() and functionC():

class A {

int functionA () {
}

int functionB() {
}

int functionC() {
}

};

how would I go about calling functionA, functioB and functionC at random?

Body:
Method 1

One of the naive methods can be to generate a random number and call the functions based on the generated number in an if statements or switch.

#include<iostream>
#include<time.h>
using namespace std;

int main(void)
{
    A a;
    srand(time(0));
    int a = rand()%3;

    switch (a)
    {
    case 0:
        a.functionA();
        break;

    case 1:
        a.functionB();
        break;

    case 2:
        a.functionC();
        break;

    default:
        break;
    }

    return 0;
}

Method 2

Based on the Comment by @Remy Lebeau, I recommend the following approach

int main(void)
{
    srand(time(0));

    int (A::*arr[])() = {&A::functionA, &A::functionB, &A:functionC};

/*
   **Note**
   You need to call the non-static class methods using an Object of the
   class. So we make an object and call methods using that object.
*/

    A a;

    (a.*arr[rand() % 3])();

    return 0;
}

Edit

As suggested by @cdihowie, c/c++ random library is not recommended as the random number generated may not be uniform. We can use uniform_distribution for generating uniform pseudo random numbers. So your final code becomes as follows:

#include <iostream>
#include <random>
#include <time.h>
using namespace std;

class A
{
public:
    int functionA()
    {
        printf("inside functionA()\n");
        return 0;
    }

    int functionB()
    {
        printf("inside functionB()\n");
        return 0;
    }

    int functionC()
    {
        printf("inside functionC()\n");
        return 0;
    }
};

int main(void)
{
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine generator(seed);
    std::uniform_int_distribution<int> distribution(0, 2);

    A a;
    A *aPtr = new A();

    int (A::*arr[])() = {&A::functionA, &A::functionB, &A::functionC};

    for (int i = 0; i < 99; i++)
    {
        int num = distribution(generator);
        (a.*arr[num])();
    }
    return 0;
}


问:
Node.js create folder or use existing
I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdir(). As you can see in the documentation, it's not very much.

Currently, I have this code, which tries to create a folder or use an existing one instead:

```<code>fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});
</code>```

But I wonder is this the right way to do it? Is checking for the code EEXIST the right way to know that the folder already exists? I know I can do fs.stat() before making the directory, but that would already be two hits to the filesystem.

Secondly, is there a complete or at least a more detailed documentation of Node.js that contains details as to what error objects contain, what parameters signify etc.

答:
@Liberateur's answer above did not work for me (Node v8.10.0).
Little modification did the trick but I am not sure if this is a right way. Please suggest.</p>

```<code>// Get modules node
const fs   = require('fs');
const path = require('path');

// Create
function mkdirpath(dirPath)
{
    try {
        fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
    }
    catch(err) {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');
</code>```

Title: Node.js create folder or use existing

Body:
I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdir(). As you can see in the documentation, it's not very much.

Currently, I have this code, which tries to create a folder or use an existing one instead:

fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});

But I wonder is this the right way to do it? Is checking for the code EEXIST the right way to know that the folder already exists? I know I can do fs.stat() before making the directory, but that would already be two hits to the filesystem.

Secondly, is there a complete or at least a more detailed documentation of Node.js that contains details as to what error objects contain, what parameters signify etc.

Body:
@Liberateur's answer above did not work for me (Node v8.10.0).
Little modification did the trick but I am not sure if this is a right way. Please suggest.

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create
function mkdirpath(dirPath)
{
    try {
        fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
    }
    catch(err) {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');


问:
Unable to connect to google cloud instance mongo with mongocompass
I hosted a mongodb in the google cloud instance. I want to use mongocompass on my local to connect to the mongo instance in the google cloud.

my mongd.conf network interfaces is as such

```<code>net:
  port: 27017
  bindIp: 0.0.0.0
</code>```

However, when i type in my google cloud static ip and port 27017 in mongocompass, i cannot connect. How do i fix this?

答: I was able to solve it by adding my white-listing my IP address under Clusters -> security -> IP Whitelist. Instead of clicking my current ip address, just search what's my ip on google and paste that instead. I hope it works!

Body:
I hosted a mongodb in the google cloud instance. I want to use mongocompass on my local to connect to the mongo instance in the google cloud.

my mongd.conf network interfaces is as such

net:
  port: 27017
  bindIp: 0.0.0.0

However, when i type in my google cloud static ip and port 27017 in mongocompass, i cannot connect. How do i fix this?


问:
reducing spacing in subplots of matplotlib
```<code>import matplotlib.pyplot as plt
import numpy as np
f, axarr = plt.subplots(nrows=10, ncols=10,
                                gridspec_kw={'hspace': 0, 'wspace': 0})
for dim in range(10):
    samples = np.random.rand(10, 256, 256, 1)
    for sample_idx in range(10):
        axarr[dim][sample_idx].imshow(samples[sample_idx,:,:,0],
                                             cmap='gray')
        axarr[dim][sample_idx].set_axis_off()
plt.show()
</code>```

My code above gives the plot below for some reason. I'm trying to make it so that each of the subplots are right next to each other, with maybe .01 of spacing in between. Right now, for some reason, the columns are too spaced apart; it's not letting me change their spacing. Anyone have any suggestions? Thanks.

答:
Usually I would use f.subplots_adjust(wspace=desired_hor_spacing) but in your case I think the plots are already as close as they can be without leaving any "empty space" on the left and right of the plot.

You can change the left and right margin of the plot to get around this:

```<code>f.subplots_adjust(left=.1, right=.9)
</code>```

Which gives you:

If you make the left margin larger and the right one smaller you can get them to be even tighter.

You can even change the left and right parameters interactively by clicking on the "configure subplots" button when you show the plot.

To get around the empty space on the left and right you can either crop the image or change the aspect ratio of the figure.

Body:
import matplotlib.pyplot as plt
import numpy as np
f, axarr = plt.subplots(nrows=10, ncols=10,
                                gridspec_kw={'hspace': 0, 'wspace': 0})
for dim in range(10):
    samples = np.random.rand(10, 256, 256, 1)
    for sample_idx in range(10):
        axarr[dim][sample_idx].imshow(samples[sample_idx,:,:,0],
                                             cmap='gray')
        axarr[dim][sample_idx].set_axis_off()
plt.show()

My code above gives the plot below for some reason. I'm trying to make it so that each of the subplots are right next to each other, with maybe .01 of spacing in between. Right now, for some reason, the columns are too spaced apart; it's not letting me change their spacing. Anyone have any suggestions? Thanks.

Body:
Usually I would use f.subplots_adjust(wspace=desired_hor_spacing) but in your case I think the plots are already as close as they can be without leaving any "empty space" on the left and right of the plot.

You can change the left and right margin of the plot to get around this:

f.subplots_adjust(left=.1, right=.9)

Which gives you:

If you make the left margin larger and the right one smaller you can get them to be even tighter.

You can even change the left and right parameters interactively by clicking on the "configure subplots" button when you show the plot.

To get around the empty space on the left and right you can either crop the image or change the aspect ratio of the figure.


问:
Inheritance guideline for a child class
Since in C#, we can only inherit from a single base class and implement multiple interfaces.

I see this normal pattern everywhere:-

DerivedClass : BaseClass, IInterface1, IInterface2

How should one decide what goes inside BaseClass and what things inside the interfaces?

Are there any guidelines for it?

答:
Implementations should go into the base class while declarations into the interfaces. There can be some exceptions e.g. if a declaration is strongly coupled with an implementation, then both can go into base class.
 ( with C# 8 interfaces can have default implementations, but this should not be misused in my opinion)</p>

Title: Inheritance guideline for a child class


答:
Just use the rand() function to randomize it as follows.

A a;
int randFuncIdx = std::rand() % 3;
switch(randFuncIdx) {
  case 0:
    a.functionA();
    break;
  case 1:
    a.functionB();
    break;
  case 2:
    a.functionC();
    break;
  default:
    break;
}
```

Title: How to call a random function


问:
Rstudio via docker cannot read /etc/.odbc.ini, only ~/.odbc.ini
When I build and then run a Docker container which runs rstudio on Ubuntu, the odbc connection does not work when I add the odbc.ini file during the build. However, if I leave out the odbc.ini file from the build and instead add it myself from within the running container, the connection does indeed work.

So my problem is that I am trying to get the odbc connection up and running out of the box whenever this image is run, without the additional step of having to login to the ubuntu container instance and add connection details to the odbc.ini file.

Here's what the odbc.ini file looks like, with dummy data:

```<code>[PostgreSQL ANSI]
    Driver              = PostgreSQL ANSI
    Database            = GoogleData
    Servername          = somename.postgres.database.azure.com
    UserName            = docker_rstudio@somename
    Password            = abc123abc
    Port                = 5432
    sslmode             = require
</code>```

I have a copy of this file, odbc.ini, in my repo directory and then include it in the build. My DockerFile.

```<code>FROM rocker/tidyverse:3.6.3
ENV ADD=SHINY
ENV ROOT=TRUE
ENV PASSWORD='abc123'
RUN apt-get update && apt-get install -y \
   less \
   vim  \
   unixodbc unixodbc-dev \
   odbc-postgresql
ADD odbc.ini /etc/odbc.ini
ADD install_packages.R /tmp/install_packages.R
RUN Rscript /tmp/install_packages.R && rm -R /tmp/*
ADD flagship_ecommerce /home/rstudio/blah/zprojects/flagship_ecommerce
ADD commission_junction /home/rstudio/blah/zprojects/commission_junction
RUN mkdir /srv/shiny-server; ln -s /home/rstudio/blah/zprojects/ /srv/shiny-server/
</code>```

If I then login to the instance via rstudio, the connection does not work, I get this error message:

Error: nanodbc/nanodbc.cpp:983: 00000: could not connect to server: No such file or directory
      Is the server running locally and accepting
      connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

If I take a look at the file with less /etc/odbc.ini I do indeed see the connection details per my top code block.

If I then copy to home with cp /etc/odbc.ini /home/rstudio/.odbc.ini then, after that, my connection does work.

But, even if I amend my dockerfile with ADD odbc.ini /home/rstudio/.odbc.ini, the connection doesn't work. It only works when I manually add to /home/rstudio/.odbc.ini.

So my problem is two fold:

No matter what I try I cannot get /etc/odbc.ini to be detected by ubuntu to use as odbc connection string. Whether via Dockerfile or by manually adding it. I would prefer this since I want to connection to be available to anyone using the container.

I am able to get a connection when I manually copy whats in odbc.ini above to /home/rstudio/.odbc.ini however if I try to do this via the docker build, the connection does not work. I do see the file there. It exists with all the correct data, it is just not detected by odbc.

In case it's relevant:

```<code>odbcinst -j
unixODBC 2.3.6
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/rstudio/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
</code>```

答:
I am no expert in docker, and have failed to find the specific documentation for this. But from experience it seems that every time you add a new layer (eg. using RUN) any copy from previous layers are "forgotten" (Note: this might be completely wrong, if so please someone correct me and specify the documentation).

So I would try to combine your RUN arguments and add every file right before the RUN statement they're needed. This has the added benefit of reducing the final image size, because of the way layers are created and kept.

```<code>FROM rocker/tidyverse:3.6.3
ENV ADD=SHINY
ENV ROOT=TRUE
ENV PASSWORD='abc123'
#add files (could also combine them into a single tar file and add it. Or add it via git, which is often used)
ADD odbc.ini /etc/odbc.ini
ADD install_packages.R /tmp/install_packages.R
ADD flagship_ecommerce /home/rstudio/blah/zprojects/flagship_ecommerce
ADD commission_junction /home/rstudio/blah/zprojects/commission_junction
#Combine all runs into a single statement
RUN apt-get update && apt-get install -y \
   less \
   vim  \
   unixodbc unixodbc-dev \
   odbc-postgresql \
 && Rscript /tmp/install_packages.R \
 && rm -R /tmp/* \
 && mkdir /srv/shiny-server \
 && ln -s /home/rstudio/blah/zprojects/ /srv/shiny-server/
</code>```

Note that now add technically comes right before the statement where it is used.

Body:
When I build and then run a Docker container which runs rstudio on Ubuntu, the odbc connection does not work when I add the odbc.ini file during the build. However, if I leave out the odbc.ini file from the build and instead add it myself from within the running container, the connection does indeed work.

So my problem is that I am trying to get the odbc connection up and running out of the box whenever this image is run, without the additional step of having to login to the ubuntu container instance and add connection details to the odbc.ini file.

Here's what the odbc.ini file looks like, with dummy data:

[PostgreSQL ANSI]
    Driver              = PostgreSQL ANSI
    Database            = GoogleData
    Servername          = somename.postgres.database.azure.com
    UserName            = docker_rstudio@somename
    Password            = abc123abc
    Port                = 5432
    sslmode             = require

I have a copy of this file, odbc.ini, in my repo directory and then include it in the build. My DockerFile.

FROM rocker/tidyverse:3.6.3
ENV ADD=SHINY
ENV ROOT=TRUE
ENV PASSWORD='abc123'
RUN apt-get update && apt-get install -y \
   less \
   vim  \
   unixodbc unixodbc-dev \
   odbc-postgresql
ADD odbc.ini /etc/odbc.ini
ADD install_packages.R /tmp/install_packages.R
RUN Rscript /tmp/install_packages.R && rm -R /tmp/*
ADD flagship_ecommerce /home/rstudio/blah/zprojects/flagship_ecommerce
ADD commission_junction /home/rstudio/blah/zprojects/commission_junction
RUN mkdir /srv/shiny-server; ln -s /home/rstudio/blah/zprojects/ /srv/shiny-server/

If I then login to the instance via rstudio, the connection does not work, I get this error message:

Error: nanodbc/nanodbc.cpp:983: 00000: could not connect to server: No such file or directory
      Is the server running locally and accepting
      connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

If I take a look at the file with less /etc/odbc.ini I do indeed see the connection details per my top code block.

If I then copy to home with cp /etc/odbc.ini /home/rstudio/.odbc.ini then, after that, my connection does work.

But, even if I amend my dockerfile with ADD odbc.ini /home/rstudio/.odbc.ini, the connection doesn't work. It only works when I manually add to /home/rstudio/.odbc.ini.

So my problem is two fold:

No matter what I try I cannot get /etc/odbc.ini to be detected by ubuntu to use as odbc connection string. Whether via Dockerfile or by manually adding it. I would prefer this since I want to connection to be available to anyone using the container.

I am able to get a connection when I manually copy whats in odbc.ini above to /home/rstudio/.odbc.ini however if I try to do this via the docker build, the connection does not work. I do see the file there. It exists with all the correct data, it is just not detected by odbc.

In case it's relevant:

odbcinst -j
unixODBC 2.3.6
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/rstudio/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

Body:
I am no expert in docker, and have failed to find the specific documentation for this. But from experience it seems that every time you add a new layer (eg. using RUN) any copy from previous layers are "forgotten" (Note: this might be completely wrong, if so please someone correct me and specify the documentation).

So I would try to combine your RUN arguments and add every file right before the RUN statement they're needed. This has the added benefit of reducing the final image size, because of the way layers are created and kept.

FROM rocker/tidyverse:3.6.3
ENV ADD=SHINY
ENV ROOT=TRUE
ENV PASSWORD='abc123'
#add files (could also combine them into a single tar file and add it. Or add it via git, which is often used)
ADD odbc.ini /etc/odbc.ini
ADD install_packages.R /tmp/install_packages.R
ADD flagship_ecommerce /home/rstudio/blah/zprojects/flagship_ecommerce
ADD commission_junction /home/rstudio/blah/zprojects/commission_junction
#Combine all runs into a single statement
RUN apt-get update && apt-get install -y \
   less \
   vim  \
   unixodbc unixodbc-dev \
   odbc-postgresql \
 && Rscript /tmp/install_packages.R \
 && rm -R /tmp/* \
 && mkdir /srv/shiny-server \
 && ln -s /home/rstudio/blah/zprojects/ /srv/shiny-server/

Note that now add technically comes right before the statement where it is used.


问:
Auto fix TSLint Warnings
```<code>    [64, 1]: space indentation expected
    [15, 27]: Missing semicolon
    [109, 36]: missing whitespace
    [111, 24]: missing whitespace
    [70, 1]: Consecutive blank lines are forbidden
</code>```

I keep getting warnings like these  from TSLint. There are huge amount of warnings, and it will be very difficult to fix it manually.

I was looking for a way which can auto-fix most of the warnings.

答:
May be this could help some one looking for autoFix on save!

we can make tslint warnings to get autofixed on save. To do this, go to tslint.json file and add the below settings. [Note: This setting works with latest TSLint and not the deprecated one].

```<code>  "source.fixAll.tslint": true
</code>```

After updating this, go to any file and try giving some spaces and it shows tslint warning message as "trailing whitespace" and when you save (Ctrl + S), this warning will get disappear. Though it appears manually, we usually tend to try saving the file once edited and by that time it will get fixed automatically.

Happy coding!

Title: Auto fix TSLint Warnings

Body:
    [64, 1]: space indentation expected
    [15, 27]: Missing semicolon
    [109, 36]: missing whitespace
    [111, 24]: missing whitespace
    [70, 1]: Consecutive blank lines are forbidden

I keep getting warnings like these  from TSLint. There are huge amount of warnings, and it will be very difficult to fix it manually.

I was looking for a way which can auto-fix most of the warnings.

Body:
May be this could help some one looking for autoFix on save!

we can make tslint warnings to get autofixed on save. To do this, go to tslint.json file and add the below settings. [Note: This setting works with latest TSLint and not the deprecated one].

  "source.fixAll.tslint": true

After updating this, go to any file and try giving some spaces and it shows tslint warning message as "trailing whitespace" and when you save (Ctrl + S), this warning will get disappear. Though it appears manually, we usually tend to try saving the file once edited and by that time it will get fixed automatically.

Happy coding!


问:
QuickFix C# or Python
We are about to implement a small automated securities trader. The trader will be build on top of the excellent quickfix FIX engine.

After due though, we narrowed our options down to implementing it in C# or in Python. Please specify the pros and cons of each language for this task, in term of:

Performance (The fact that Python uses a GIL troubles me in terms of thread concurrency)

Productivity

Scalability (We may need to scale this trader to a fully-sized platform)

EDIT
I've rephrased the question to make it less "C# vs. Python" (which I find irrelevant - both languages have their merits), but I'm simply trying to draw a comparison table before I make the decision.

答: For points "Performance" and "Scalability" I would suggest C# (although a large part of performance depends on your algorithms). Productivity is much of a subjective thing, but now C# has all cool features like lambda, anonymous method, classes etc which makes it much more productive.</p>

Title: QuickFix C# or Python


问:
How to read UTF-8 XML with RapidXML and use it with C++
I work on a C++ application and implemented a translator class that uses data from a XML file to translate strings. I have now serious problems with special characters currently for German Umlauts ÖÄÜ for example...

On Visual Studio I see following in Debug view, it reads following sample string "Dateiäüö":

Because of this problem I found this post on Stackoverflow:
How to read Unicode XML values with rapidxml
and changed my RapidXML class to work with wchar_t:

```<code>std::string RapidXMLParser::getValueUTF8(const std::string path)
{
    std::vector<std::string> tags = splitPath(path);
    rapidxml::file<wchar_t> xmlFile(filename.data());
    docUTF8.parse<0>(xmlFile.data());
    rapidxml::xml_node<wchar_t>* element = findElementUTF8(path);
    if (element)
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        std::wstring temp = element->value();
        std::string result = converter.to_bytes(temp);
        return result;
    }
    else
        return "";
}
</code>```

But this did not solve my problem:

The source XML file was checked by an UTF-8 validator and it is ok. If I change encoding to ANSI, everything works on Windows (but this is no solution!). If I compile same code on Linux I get empty strings for ANSI encoded XML with Umlauts and a crash for UTF-8 encoded XML...

The program uses wxwidgets for its interface and there this menu item renders the same characters as displayed by debugger. On Linux the empty strings leads to missing menu items or empty lines.

I hope someone has a good advice how to solve this or a suggestion for an alternative way to do UTF-8 translation with editable data source like an XML file.

EDIT:
My XML parser can switch between RapidXML and TinyXML. I've also tested this with TinyXML and I get the same problem:

答:
After hours working on this issue the solution was quite simple.
Never trust your debugger!!! The problem was caused by wxwidgets... it displays the same chars as seen in my debugger, but if I put a utf8 to utf16 conversion before rendering of menu items, it displays the string correct!

The solution is to do not use shown codecvt code in my XMLParser, but instead in my wxwidgets code just before output. On Linux I have now the problem, that codecvt is not part of std for g++...but this is another story.

Oh boy...I hope this is useful if anybody has a similar problem.

Body:
I work on a C++ application and implemented a translator class that uses data from a XML file to translate strings. I have now serious problems with special characters currently for German Umlauts ÖÄÜ for example...

On Visual Studio I see following in Debug view, it reads following sample string "Dateiäüö":

Because of this problem I found this post on Stackoverflow:
How to read Unicode XML values with rapidxml
and changed my RapidXML class to work with wchar_t:

std::string RapidXMLParser::getValueUTF8(const std::string path)
{
    std::vector<std::string> tags = splitPath(path);
    rapidxml::file<wchar_t> xmlFile(filename.data());
    docUTF8.parse<0>(xmlFile.data());
    rapidxml::xml_node<wchar_t>* element = findElementUTF8(path);
    if (element)
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        std::wstring temp = element->value();
        std::string result = converter.to_bytes(temp);
        return result;
    }
    else
        return "";
}

But this did not solve my problem:

The source XML file was checked by an UTF-8 validator and it is ok. If I change encoding to ANSI, everything works on Windows (but this is no solution!). If I compile same code on Linux I get empty strings for ANSI encoded XML with Umlauts and a crash for UTF-8 encoded XML...

The program uses wxwidgets for its interface and there this menu item renders the same characters as displayed by debugger. On Linux the empty strings leads to missing menu items or empty lines.

I hope someone has a good advice how to solve this or a suggestion for an alternative way to do UTF-8 translation with editable data source like an XML file.

EDIT:
My XML parser can switch between RapidXML and TinyXML. I've also tested this with TinyXML and I get the same problem:


问:
Haskell Higher Order Functions and Associativity
I'm learning FP and have a few confusion after playing around with GHCi.

Say I have 2 simple functions:

twice :: (a -> a) -> (a -> a)
twice f a = f (f a) -- Equation 1

double :: Int -> Int
double = \x -> x * 2
```

<p>Decomposing the evaluation <code>twice twice twice double 3</code> (note that 3x<code>twice</code>+1x<code>double</code>), I would have:</p>

<pre class="lang-hs prettyprint-override"><code>{-
   twice twice twice double 3
== (twice twice twice double) 3
== (twice twice (twice double)) 3
== (twice (twice (double double 3)))
== (twice ((double double) (double double 3)))
== (((double double) (double double)) ((double double) (double double 3)))
== 768
-}
</code>```

Is this correct?

According to this, if my definition of twice is changed as twice f a = f f a -- Equation 2, I should decompose the evaluation, with left associativity, as:

{-
   twice (twice twice double) 3
== (twice twice double) (twice twice double) 3
== ((twice double)(twice double)) ((twice double)(twice double)) 3
== ((double double)(double double)) ((double double)(double double)) 3
== (double (double (double (double (double (double (double (double 3 ) ) ) ) ) ) )
== 768
-}
```

<p>right?</p>

<ul>
<li>However, the strangest part is GHC REPL gave me the answer of <code>196608</code> (2^16*3):</li>
</ul>

```> twice twice twice double 3
196608
```

which then makes me so confusing. Where would I make the mistake?
Thanks.

答:
As the comment said, function application is left associative, so:

```<code>twice twice twice double 3 == (((twice twice) twice) double) 3

which is not the same as:     twice (twice twice double 3)
</code>```

As requested in your comment: note that twice returns the same type of its argument.  So, the type of twice twice is just ((a -> a) -> (a -> a))

Now, let's expand the whole expression:

```<code>(((twice twice) twice) double) 3 ==> ((twice (twice twice)) double) 3
                                 ==> (((twice twice) ((twice twice) double)) 3
                                 ==> (twice (twice ((twice twice) double))) 3
                                 ==> (twice (twice (twice (twice double)))) 3

twice double ==> double^2
twice (twice double) ==> double^4
twice (twice (twice double)) ==> double^8
twice (twice (twice (twice double))) == double^16
</code>```

and double^16 3 == 2^16 * 3 as you found.

Body:
I'm learning FP and have a few confusion after playing around with GHCi.

Say I have 2 simple functions:

twice :: (a -> a) -> (a -> a)
twice f a = f (f a) -- Equation 1

double :: Int -> Int
double = \x -> x * 2

Decomposing the evaluation twice twice twice double 3 (note that 3xtwice+1xdouble), I would have:

{-
   twice twice twice double 3
== (twice twice twice double) 3
== (twice twice (twice double)) 3
== (twice (twice (double double 3)))
== (twice ((double double) (double double 3)))
== (((double double) (double double)) ((double double) (double double 3)))
== 768
-}

Is this correct?

According to this, if my definition of twice is changed as twice f a = f f a -- Equation 2, I should decompose the evaluation, with left associativity, as:

{-
   twice (twice twice double) 3
== (twice twice double) (twice twice double) 3
== ((twice double)(twice double)) ((twice double)(twice double)) 3
== ((double double)(double double)) ((double double)(double double)) 3
== (double (double (double (double (double (double (double (double 3 ) ) ) ) ) ) )
== 768
-}

right?

However, the strangest part is GHC REPL gave me the answer of 196608 (2^16*3):

> twice twice twice double 3
196608

which then makes me so confusing. Where would I make the mistake?
Thanks.

Body:
As the comment said, function application is left associative, so:

twice twice twice double 3 == (((twice twice) twice) double) 3

which is not the same as:     twice (twice twice double 3)

As requested in your comment: note that twice returns the same type of its argument.  So, the type of twice twice is just ((a -> a) -> (a -> a))

Now, let's expand the whole expression:

(((twice twice) twice) double) 3 ==> ((twice (twice twice)) double) 3
                                 ==> (((twice twice) ((twice twice) double)) 3
                                 ==> (twice (twice ((twice twice) double))) 3
                                 ==> (twice (twice (twice (twice double)))) 3

twice double ==> double^2
twice (twice double) ==> double^4
twice (twice (twice double)) ==> double^8
twice (twice (twice (twice double))) == double^16

and double^16 3 == 2^16 * 3 as you found.


问:
tf.keras how to reuse resnet layers as customize layer in customize model
i am search a solution to reuse pre-trained Resnet50 model as a customized sub-layers inside a big customized model.

In my scenario, I use Resnet50 as FCN backbone, and then I will use FCN output result as input to another network layers.(its a pipeline)

you can see my code:
https://github.com/piginzoo/textscanner/blob/master/network/layers/fcn_layer.py
https://github.com/piginzoo/textscanner/blob/master/network/model.py

my question is, i cannot find an example code, to integrate the Resnet50 layers as partial of customized layer in TF 2.0, i search out stackoverflow, TF2.0 offical website and blogs, cannot find a feasible code snippet to demo how to implement such requirement.

but I believe this is a very common paradigm, does anyone ever faces on such problems, and any advices or code demo will be very appreciated.

答:
Finally i found a feasible way, like:

as the code shown, I created a new model who use pre-trained Resnet50's input as his input, and use the 3 "conv_block_out"s as new model's outputs, and in call method, i just call the model as "a layer" style.

for detail, you can refer to my Github for completed code.

Dummy code:

```<code>class FCNLayer(Layer):
    def __init__(self, name, resnet50_model):
        super().__init__(name=name)
        resnet50_model.layers.pop()
        resnet50_model.summary()
        self.resnet50_model = resnet50_model

    def build(self, input_image, FILTER_NUM=4):
        layer_names = [
            "conv3_block4_out",  # 1/8
            "conv4_block6_out",  # 1/16
            "conv5_block3_out",  # 1/32
        ]
        layers = [self.resnet50_model.get_layer(name).output for name in layer_names]
        self.FCN_left = Model(inputs=self.resnet50_model.input, outputs=layers)
        ......

    def call(self, input_image, training=True):

        pool3, pool4, pool5 = self.FCN_left(input_image)
        .......
</code>```

Body:
Finally i found a feasible way, like:

as the code shown, I created a new model who use pre-trained Resnet50's input as his input, and use the 3 "conv_block_out"s as new model's outputs, and in call method, i just call the model as "a layer" style.

for detail, you can refer to my Github for completed code.

Dummy code:

class FCNLayer(Layer):
    def __init__(self, name, resnet50_model):
        super().__init__(name=name)
        resnet50_model.layers.pop()
        resnet50_model.summary()
        self.resnet50_model = resnet50_model

    def build(self, input_image, FILTER_NUM=4):
        layer_names = [
            "conv3_block4_out",  # 1/8
            "conv4_block6_out",  # 1/16
            "conv5_block3_out",  # 1/32
        ]
        layers = [self.resnet50_model.get_layer(name).output for name in layer_names]
        self.FCN_left = Model(inputs=self.resnet50_model.input, outputs=layers)
        ......

    def call(self, input_image, training=True):

        pool3, pool4, pool5 = self.FCN_left(input_image)
        .......


问:
How to use CSS counter increment for dynamic page numbers
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="SetupMainTable">
  <thead>
    <tr>
       <td colspan="4">Company Name</td>
       <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
       <td colspan="1"><div class="page-number"></div></td>
    </tr>
  </thead>
</table>  </code>```

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

答:
I found that code in one Russian article. That code adds pagination to each page:

```<code>@page:right{
  @bottom-right {
    content: counter(page);
  }
}

@page:left{
  @bottom-left {
    content: counter(page);
  }
}
</code>```

And code below can show number of page of their total like "Page 3 of 120".

```<code>@page:left{
  @bottom-left {
    content: "Page " counter(page) " of " counter(pages);
  }
}
</code>```

Body:
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }

       Company Name
       Daily Time Ticket

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

Body:
I found that code in one Russian article. That code adds pagination to each page:

@page:right{
  @bottom-right {
    content: counter(page);
  }
}

@page:left{
  @bottom-left {
    content: counter(page);
  }
}

And code below can show number of page of their total like "Page 3 of 120".

@page:left{
  @bottom-left {
    content: "Page " counter(page) " of " counter(pages);
  }
}


问:
How to validate financial transactions in REST API with Spring Boot?
I need to implement a Spring Boot app, it is about financial transactions. I want to create a REST API like this:

```<code>@PostMapping("/sendmoney")
public void sendMoney(@RequestBody TransferBalanceRequest transferBalanceRequest) {
    transactionService.sendMoney(transferBalanceRequest);
}
</code>```

TransferBalanceRequest class:

```<code>public class TransferBalanceRequest {
    private String name;
    private String tin;
    private String fromIban;
    private String toIban;
    private BigDecimal amount;
}
</code>```

I need to validate in this way: payer si payee should have a valid IBAN and NIF and all the other fields shouldn't be empty.

So how ca I do this validation? Should I use this type of annotations?

```<code>@NotEmpty(message = "Please provide a name")
</code>```

答:
JSR-380 - Bean Validation 2.0 Spec

Implementations (such as Hibernate Validator) for this specification will provide you annotations that you can use on your request's fields, as for example the @NotEmpty and @Pattern, for the scenarios that you mentioned.

Body:
I need to implement a Spring Boot app, it is about financial transactions. I want to create a REST API like this:

@PostMapping("/sendmoney")
public void sendMoney(@RequestBody TransferBalanceRequest transferBalanceRequest) {
    transactionService.sendMoney(transferBalanceRequest);
}

TransferBalanceRequest class:

public class TransferBalanceRequest {
    private String name;
    private String tin;
    private String fromIban;
    private String toIban;
    private BigDecimal amount;
}

I need to validate in this way: payer si payee should have a valid IBAN and NIF and all the other fields shouldn't be empty.

So how ca I do this validation? Should I use this type of annotations?

@NotEmpty(message = "Please provide a name")


问:
Make sure that method returns a List<String> and not just a List. in java
```<code>public static void main(String[] args) {
    ArrayList idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1,"b");
    idList.add(2,"c");
    for (String uuid : idList) {
      System.out.println(uuid);
    }
  }
</code>```

In "uuid : idList"

"Type mismatch: cannot convert from element type Object to String"

What's wrong?

答:
A rule of thumb , never use a raw type like below

ArrayList idList = new ArrayList();

If you do so , the compiler will generate a warning , which you should never ignore. Always write the generic parametrised version to avoid such pitfalls

```<code>ArrayList<String> idList = new ArrayList<>();
</code>```

if you are using JDK10 or above , you an use

```<code>  var idList = new ArrayList<String>();  // compiler will infer from right handside that its a List<String>
</code>```

Body:
public static void main(String[] args) {
    ArrayList idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1,"b");
    idList.add(2,"c");
    for (String uuid : idList) {
      System.out.println(uuid);
    }
  }

In "uuid : idList"

"Type mismatch: cannot convert from element type Object to String"

What's wrong?

Body:
A rule of thumb , never use a raw type like below

ArrayList idList = new ArrayList();

If you do so , the compiler will generate a warning , which you should never ignore. Always write the generic parametrised version to avoid such pitfalls

ArrayList<String> idList = new ArrayList<>();

if you are using JDK10 or above , you an use

  var idList = new ArrayList<String>();  // compiler will infer from right handside that its a List<String>


问:
array filter and if true map data
i have this piece of code which should combine three apicalls together.

API 1: modules (like a container for multiple checkboxes)
data structure is this:

const modules = [
  {
    name: "Modul1",
    id: 1,
  },
  {
    name: "Modul2",
    id: 2,
  },
];
```

<hr>

<p>API 2: the elements which should be inside the modules and related to there
<code>modules[x].id === elements[x].idModule</code></p>

<pre class="lang-js prettyprint-override"><code>const elements = [
  {
    idModule: 1,
    default: false,
    id: 1,
  },
  {
    idModule: 1,
    default: false,
    id: 2,
  },
  {
    idModule: 1,
    default: false,
    id: 3,
  },
  {
    idModule: 2,
    default: false,
    id: 4,
  },
  {
    idModule: 2,
    default: false,
    id: 5,
  },
  {
    idModule: 2,
    default: false,
    id: 6,
  },
  {
    idModule: 2,
    default: false,
    id: 7,
  },
];
</code>```

API 3: the true/false value which should set to the elements related to
elements[x].id === items.items[x].id

const items = {
   "status":true,
   "items":[
      {
         "id":1,
         "value":true
      },
      {
         "id":2,
         "value":true
      },
      {
         "id":3,
         "value":true
      },
      {
         "id":4,
         "value":true
      },
      {
         "id":5,
         "value":true
      },
      {
         "id":6,
         "value":true
      },
      {
         "id":7,
         "value":true
      }
   ]
}
```

<hr>

<p>all three APIs should be combined to one single source of truth.
the result should looks like this:</p>

<pre class="lang-js prettyprint-override"><code>const result = [
  {
    id: 1,
    name: 'Module1',
    elements: [
      {
        idModule: 1,
        default: false,
        id: 1,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 2,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 3,
        value: true
      }
    ]
  },
  {
    id: 2,
    name: 'Module2',
    elements: [
      {
        idModule: 2,
        default: false,
        id: 4,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 5,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 6,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 7,
        value: true
      }
    ]
  }
];
</code>```

my brain is melting by doing this and i am stuck as f. what i tried for now 2 days is this:

const data = data.modules.map(x => {
  x.modules = data.elements.items.filter(
    d => d.idModule === x.id
  );

  x.modul.map(y => {
    // ---------- some where here the shit its the fan, idk -----------
    y.value = data.items.items.filter(f => {
      f.id === y.id;
    });
    return y;
  });
  return x;
});
```

答:
   var modules = [ { name: "Modul1", id: 1, }, { name: "Modul2", id: 2, }];
var elements = [ { idModule: 1, default: false, id: 1, }, { idModule: 1, default: false, id: 2, }, { idModule: 1, default: false, id: 3, }, { idModule: 2, default: false, id: 4, }, { idModule: 2, default: false, id: 5, }, { idModule: 2, default: false, id: 6, }, { idModule: 2, default: false, id: 7, },];
var items = { "status":true, "items":[ { "id":1, "value":true }, { "id":2, "value":true }, { "id":3, "value":true }, { "id":4, "value":true }, { "id":5, "value":true }, { "id":6, "value":true }, { "id":7, "value":true } ]}

let arr = modules.map(ele => {
  ele['elements'] = elements.filter(el => el.idModule == ele.id).map(inele => {
    let index = items['items'].map(fi => fi.id).indexOf(inele.id);
    (index != -1) ? inele['value'] = items['items'][index]['value'] : '';
    return inele;
  });
  return ele;
})
console.log(arr);```

Title: array filter and if true map data

Body:
i have this piece of code which should combine three apicalls together.

API 1: modules (like a container for multiple checkboxes)
data structure is this:

const modules = [
  {
    name: "Modul1",
    id: 1,
  },
  {
    name: "Modul2",
    id: 2,
  },
];

API 2: the elements which should be inside the modules and related to there
modules[x].id === elements[x].idModule

const elements = [
  {
    idModule: 1,
    default: false,
    id: 1,
  },
  {
    idModule: 1,
    default: false,
    id: 2,
  },
  {
    idModule: 1,
    default: false,
    id: 3,
  },
  {
    idModule: 2,
    default: false,
    id: 4,
  },
  {
    idModule: 2,
    default: false,
    id: 5,
  },
  {
    idModule: 2,
    default: false,
    id: 6,
  },
  {
    idModule: 2,
    default: false,
    id: 7,
  },
];

API 3: the true/false value which should set to the elements related to
elements[x].id === items.items[x].id

const items = {
   "status":true,
   "items":[
      {
         "id":1,
         "value":true
      },
      {
         "id":2,
         "value":true
      },
      {
         "id":3,
         "value":true
      },
      {
         "id":4,
         "value":true
      },
      {
         "id":5,
         "value":true
      },
      {
         "id":6,
         "value":true
      },
      {
         "id":7,
         "value":true
      }
   ]
}

all three APIs should be combined to one single source of truth.
the result should looks like this:

const result = [
  {
    id: 1,
    name: 'Module1',
    elements: [
      {
        idModule: 1,
        default: false,
        id: 1,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 2,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 3,
        value: true
      }
    ]
  },
  {
    id: 2,
    name: 'Module2',
    elements: [
      {
        idModule: 2,
        default: false,
        id: 4,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 5,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 6,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 7,
        value: true
      }
    ]
  }
];

my brain is melting by doing this and i am stuck as f. what i tried for now 2 days is this:

const data = data.modules.map(x => {
  x.modules = data.elements.items.filter(
    d => d.idModule === x.id
  );

  x.modul.map(y => {
    // ---------- some where here the shit its the fan, idk -----------
    y.value = data.items.items.filter(f => {
      f.id === y.id;
    });
    return y;
  });
  return x;
});


问:
How to stop Material dropdown autocomplete selection from triggering another search query in Angular 8/9?
Summary: I have a working as-you-type field dropdown search. When I choose from the dropdown, which happily sets the field to the object I've received in the search, but unhappily registers THAT change and sends the whole object off to be searched.

HTML:

<form [formGroup]="myForm" novalidate>
  <mat-form-field>
    <input matInput
    placeholder="SKU / Item Number"
    [matAutocomplete]="auto"
    formControlName='itemName'>
  </mat-form-field>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="parseDropDownSelection">
      <mat-option
            *ngFor="let row of searchQueryResult"
            [value]="row"
            (onSelectionChange)="onItemSelection($event)">
        {{ row.Name }}
      </mat-option>
  </mat-autocomplete>
</form>
```

<p>Setup:</p>

<pre class="lang-js prettyprint-override"><code>import {FieldSearchServiceItem}     from './../services/field-search.service';

constructor(
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private appServiceItem: FieldSearchServiceItem,
    )   {}
</code>```

ngOnInit()

ngOnInit(){
    this.myForm = this.formBuilder.group
        ({
        itemName: '',
        });

this.myForm
  .get('itemName')
  .valueChanges
  .pipe(
    debounceTime(200),
    switchMap(value => this.appServiceItem.search({name: value}, 1))
    )
  .subscribe(serviceResult => this.searchQueryResult = serviceResult.qResult);
}
```

<p>The service:</p>

<pre class="lang-js prettyprint-override"><code>@Injectable()
export class FieldSearchServiceItem
  {
  constructor(private http: HttpClient) {}
  search(filter: {name: string} = {name: ''}, page = 1): Observable<apiQueryResponseForItem>
    {
    var queryResponse;
    return this.http.get<apiQueryResponseForItem>(`example.com/search/item/${filter.name}`)
    .pipe(
      tap((response: apiQueryResponseForItem) =>
        {
        response.qResult = response.qResult
          .map(unit => new ItemUnit(unit.Id, unit.Name))
        return response;
        })
      );
    }
  }
</code>```

The class defs:

export class ItemUnit
    {
    constructor
        (
        public Id:number,
        public Name:string,
        )   {}
    }

export interface apiQueryResponseForItem
    {
    qSuccess: boolean;
    qResult: ItemUnit[];
    }
```

<p>I've seen other answers where the solution has been to use the emitEvent:false when setting the value, like so:</p>

<pre class="lang-js prettyprint-override"><code>this.myForm.get('itemName').patchValue('theDataThatCameBackFromSeach', {emitEvent:false})
</code>```

That makes sense... but I get the feeling that solution doesn't match up with this observable/injectable/Material approach... mainly because I'm not using a call that does a .setValue() or .patchValue(), I'm guessing there's a binding somewhere in the Material stuff that's handling that.

The server ending up seeing calls like this:

```<code>http://example.com/search/item/a                   (when the letter a is typed)
http://example.com/search/item/[object%20Object]   (after clicking the dropdown, JS tries to search 'object' after clumsily falling back to string representation )
</code>```

My onItemSelection() is currently uninvolved, it's working but does nothing other than dump to the console. The .qResult that's coming back from my searchQueryResult service contains {Id:number,Name:string}. How can I have the field-setting action of the autocomplete still do its work of setting the field, but not creating a change event when it does that, while still honoring the onItemSelection() so I can get my other processing done?

答:
Made a simple app in Stackblitz, you can check it out. Hope I understood correctly your issue.

Main idea is - when user fills in form input we get string, when autocomplete fills it we get ItemUnit.
This way we can decide whether to make http request or not.

Body:
Summary: I have a working as-you-type field dropdown search. When I choose from the dropdown, which happily sets the field to the object I've received in the search, but unhappily registers THAT change and sends the whole object off to be searched.

HTML:

<form [formGroup]="myForm" novalidate>
  <mat-form-field>
    <input matInput
    placeholder="SKU / Item Number"
    [matAutocomplete]="auto"
    formControlName='itemName'>
  </mat-form-field>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="parseDropDownSelection">
      <mat-option
            *ngFor="let row of searchQueryResult"
            [value]="row"
            (onSelectionChange)="onItemSelection($event)">
        {{ row.Name }}
      </mat-option>
  </mat-autocomplete>
</form>

Setup:

import {FieldSearchServiceItem}     from './../services/field-search.service';

constructor(
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private appServiceItem: FieldSearchServiceItem,
    )   {}

ngOnInit()

ngOnInit(){
    this.myForm = this.formBuilder.group
        ({
        itemName: '',
        });

this.myForm
  .get('itemName')
  .valueChanges
  .pipe(
    debounceTime(200),
    switchMap(value => this.appServiceItem.search({name: value}, 1))
    )
  .subscribe(serviceResult => this.searchQueryResult = serviceResult.qResult);
}

The service:

@Injectable()
export class FieldSearchServiceItem
  {
  constructor(private http: HttpClient) {}
  search(filter: {name: string} = {name: ''}, page = 1): Observable<apiQueryResponseForItem>
    {
    var queryResponse;
    return this.http.get<apiQueryResponseForItem>(`example.com/search/item/${filter.name}`)
    .pipe(
      tap((response: apiQueryResponseForItem) =>
        {
        response.qResult = response.qResult
          .map(unit => new ItemUnit(unit.Id, unit.Name))
        return response;
        })
      );
    }
  }

The class defs:

export class ItemUnit
    {
    constructor
        (
        public Id:number,
        public Name:string,
        )   {}
    }

export interface apiQueryResponseForItem
    {
    qSuccess: boolean;
    qResult: ItemUnit[];
    }

I've seen other answers where the solution has been to use the emitEvent:false when setting the value, like so:

this.myForm.get('itemName').patchValue('theDataThatCameBackFromSeach', {emitEvent:false})

That makes sense... but I get the feeling that solution doesn't match up with this observable/injectable/Material approach... mainly because I'm not using a call that does a .setValue() or .patchValue(), I'm guessing there's a binding somewhere in the Material stuff that's handling that.

The server ending up seeing calls like this:

http://example.com/search/item/a                   (when the letter a is typed)
http://example.com/search/item/[object%20Object]   (after clicking the dropdown, JS tries to search 'object' after clumsily falling back to string representation )

My onItemSelection() is currently uninvolved, it's working but does nothing other than dump to the console. The .qResult that's coming back from my searchQueryResult service contains {Id:number,Name:string}. How can I have the field-setting action of the autocomplete still do its work of setting the field, but not creating a change event when it does that, while still honoring the onItemSelection() so I can get my other processing done?


问:
How to find depth of an expression?
I have tried this code to find depth of an expression.Could you tell me where I am going wrong and what I should do to get the correct answer.</p>

```<code>k=0
m=0
def fn(x):
    global k,m
    if isinstance(x,(tuple,list))== False : return "xyz"
    if isinstance(x,(tuple,list))== True :
        k=k+1
        if k>m: m=k

        for i in x:
            print i
            print k
            if isinstance (i,(list,tuple)):
                fn(i)
            else:
                if k>1: k=m
                else:k=1

fn([[['x',[1,[8,9],2],'y',[7,6]]]])
print "depth is",m
</code>```

答:
Recently, I happened to come across this issue and couldn't find any definite guide. So I thought of leaving this answer for someone who might need it in the future.

I tried many alternatives and came up with this solution.

```<code>def depth(in_data, current_depth=0):
current_max_depth = 0
if isinstance(in_data, (list, tuple)):
    current_depth += 1
    for data  in in_data:
        d = depth(data, current_depth)
        if d > current_max_depth:
            current_max_depth = d
    return current_max_depth
return current_depth
</code>```

In this code, every time the program returns true for isinstance() it increases the current depth by 1 and passes this current depth together with the new elements to the function again. When it returns false it returns back the current depth with no change.
Then by storing and comparing the current depth we can find the maximum depth.
I hope this helps.

Title: How to find depth of an expression?

Body:
I have tried this code to find depth of an expression.Could you tell me where I am going wrong and what I should do to get the correct answer.

k=0
m=0
def fn(x):
    global k,m
    if isinstance(x,(tuple,list))== False : return "xyz"
    if isinstance(x,(tuple,list))== True :
        k=k+1
        if k>m: m=k

        for i in x:
            print i
            print k
            if isinstance (i,(list,tuple)):
                fn(i)
            else:
                if k>1: k=m
                else:k=1

fn([[['x',[1,[8,9],2],'y',[7,6]]]])
print "depth is",m

Body:
Recently, I happened to come across this issue and couldn't find any definite guide. So I thought of leaving this answer for someone who might need it in the future.

I tried many alternatives and came up with this solution.

def depth(in_data, current_depth=0):
current_max_depth = 0
if isinstance(in_data, (list, tuple)):
    current_depth += 1
    for data  in in_data:
        d = depth(data, current_depth)
        if d > current_max_depth:
            current_max_depth = d
    return current_max_depth
return current_depth

In this code, every time the program returns true for isinstance() it increases the current depth by 1 and passes this current depth together with the new elements to the function again. When it returns false it returns back the current depth with no change.
Then by storing and comparing the current depth we can find the maximum depth.
I hope this helps.


问:
What are the performance implications, if any, of chaining too many `.then`s on Promises?
I have an implementation of reduce that could potentially chain many .then handlers together.

```<code>const reduceIterable = (fn, x0, x) => {
  const iter = x[Symbol.iterator].call(x)
  let cursor = iter.next()
  if (cursor.done) {
    throw new TypeError('reduce(...)(x); x cannot be empty')
  }
  let y = !isUndefined(x0) ? fn(x0, cursor.value) : (() => {
    const x0 = cursor.value
    cursor = iter.next()
    return cursor.done ? x0 : fn(x0, cursor.value)
  })()
  cursor = iter.next()
  while (!cursor.done) {
    const { value } = cursor
    y = isPromise(y) ? y.then(res => fn(res, value)) : fn(y, value)
    cursor = iter.next()
  }
  return y
}

// you would use reduce like reduce(add, 0)([1, 2, 3]) // => 6
const reduce = (fn, x0) => {
  if (!isFunction(fn)) {
    throw new TypeError('reduce(x, y); x is not a function')
  }
  return x => {
    if (isIterable(x)) return reduceIterable(fn, x0, x)
    if (isAsyncIterable(x)) return reduceAsyncIterable(fn, x0, x)
    if (is(Object)(x)) return reduceObject(fn, x0, x)
    throw new TypeError('reduce(...)(x); x invalid')
  }
}
</code>```

Specifically, I'm looking at y.then(res => fn(res, value)). This keeps me up at night because of this issue. I know Promises have come a long way since then, but this has never been resolved. I really want to know if I'm okay to consume the Promise API like this, or if I need to do something harder.

答:
What are the performance implications, if any, of chaining too many .thens on Promises?

If you compare a .reduce() loop where you chain lots of .then() onto each other in order to sequence asynchronous operation and compare that to an await loop inside an async function where you finish one operation before starting the next, the main difference will be in peak memory usage.  Chaining a lot of .then() together will have the full chain of all the promise objects in memory at once.  If you do an await loop, you only have one promise active at a time.

Now, promises are not large objects so even if your chain is thousands of elements long, it probably still may not be a material difference.  But, if you want to minimize peak memory usage, an await loop would keep the peak memory usage lower.

As for pure execution speed, the story is the same as always.  If you really cared about execution speed, you'd have to write a representative test program using the .reduce() loop and a program that generated equivalent output and sequencing using an await loop and benchmark the two.  Performance is so dependent upon speicific circumstances that you have to measure if you really want to know which is faster.  Theorizing is often wrong because our intuition doesn't always know what the real bottleneck is.  You have to measure.

FYI, async/await have been sped up quite a bit in the last few nodejs releases.

Body:
I have an implementation of reduce that could potentially chain many .then handlers together.

const reduceIterable = (fn, x0, x) => {
  const iter = x[Symbol.iterator].call(x)
  let cursor = iter.next()
  if (cursor.done) {
    throw new TypeError('reduce(...)(x); x cannot be empty')
  }
  let y = !isUndefined(x0) ? fn(x0, cursor.value) : (() => {
    const x0 = cursor.value
    cursor = iter.next()
    return cursor.done ? x0 : fn(x0, cursor.value)
  })()
  cursor = iter.next()
  while (!cursor.done) {
    const { value } = cursor
    y = isPromise(y) ? y.then(res => fn(res, value)) : fn(y, value)
    cursor = iter.next()
  }
  return y
}

// you would use reduce like reduce(add, 0)([1, 2, 3]) // => 6
const reduce = (fn, x0) => {
  if (!isFunction(fn)) {
    throw new TypeError('reduce(x, y); x is not a function')
  }
  return x => {
    if (isIterable(x)) return reduceIterable(fn, x0, x)
    if (isAsyncIterable(x)) return reduceAsyncIterable(fn, x0, x)
    if (is(Object)(x)) return reduceObject(fn, x0, x)
    throw new TypeError('reduce(...)(x); x invalid')
  }
}

Specifically, I'm looking at y.then(res => fn(res, value)). This keeps me up at night because of this issue. I know Promises have come a long way since then, but this has never been resolved. I really want to know if I'm okay to consume the Promise API like this, or if I need to do something harder.


问:
DDD, BoundedContexts, Domain Events and Transactions
I am currently in the process of creating a Proof of Concept for a product/party administration system, based on the principles of DDD. One of the requirements is that the party data (customer, reseller) will be stored in a CRM on the web and the product specific data will be stored in a SQL database on premise (see below).

CRM System (Web Based)

Customer (contains name, address, email, contact preference etc)

Reseller (contains name, address, active status)

Product System (On Premise)

BaseProduct (defines a vanilla product)

ResellerProduct (defines a customisation of a base product which will be sold by the reseller)
CustomerProduct (defines a product which the customer as registered).

I have been conducting a lot of research into the different approaches of how I could implement the solution, but am struggling to make sense of all the concepts and how they apply to my problem.

I started out by splitting the areas into 2 different bounded contexts, Party and Product. I defined domain models for each of these contexts, and where entities referenced concepts in the other model I left these as simple Guid Ids (i.e. CustomerProduct in the product domain would have a CustomerRef value of the related Guid).

I then implemented a Party infrastructure implementation which used API calls to the web CRM and a Product infrastructure implementation which used NHibernate. For each of these I implemented a UnitOfWork so I could control the transaction process in each context. The application layer would have the two contexts injected at runtime and use them.

For Example:

ApplicationService.RegisterNewProduct(customerId,
ProductId)

Start the transaction of each unit of
work (PartyUnitOfWork.Begin(),
ProductUnitOfWork.Begin())

Use the repositories for each context
to find the relevant domain objects
(Party.Customer.Find(Id),
Product.ResellerProduct.Find(Id))

Perform logic to determine if
customer is eligible, product is
valid etc.

Create a new CustomerProduct and save
to the product System

Commit each contexts UnitOfWork

I then started to explore bounded contexts a bit further and was thinking about refactoring the app so that each context had a limited representation of concepts from the other, but only specific to that context. i.e. In the Product context I would have a customer entity, which had an Id, Name and active status but maybe not contact preferences etc. I would then use DomainEvents to coordinate activities between the different systems to keep their data up to date (i.e. If a new customer was created in the CRM system an event would be raised and handled by the Product system to update its representation of customer). Therefore the above example would change so only the Product context was used.

To confuse matters further, say the ‘RegisterNewProduct’ call also created a new Customer, would I created the customer in the Product system and raise a ‘NewCustomer’ event which would be handled by the Party system?

I would be interested to gather peoples comments on these ideas?

答:
Besides my comment/question, there is fundamental issue with UnitOfWork approach you described. You'll run into a whole class of problems with one of the units committed and one failed. You will end up with a distributed transaction spanning two context.

A better (subjectively) approach to bounded contexts, if you really need to have more than one, is to have asynchronous, message based communication between them. You execute a command against an aggregate in one context and in the same transaction as persisting the changes to the DB, you publish (for example via NServiceBus or MassTransit) a message (an event) that something happened. The other context receives the message/event and reacts.

If you are a purist, you could use this approach to all inter-aggregate communication. By doing this you could remove the requirement of having a Unit of Work at all.

Does it make any sense?


问:
Why the code is not taking the specified number of elements in the ArrayList?
Here is my code:

```<code>        ArrayList<String> arr= new ArrayList();
        Scanner sc= new Scanner(System.in);

        System.out.println("Enter the number of elements in the array");
        int temp= sc.nextInt();
        System.out.println("Enter the elements in the array");

        String num;
        for(int i=0; i<temp; i++) {
            num= sc.nextLine();
            arr.add(num);
            //System.out.println("i= "+ i +"temp= "+temp);
        }
</code>```

The problem is that if i want to add 5 elements it is taking the first element as null and only letting me to input rest 4 elements but i want to enter all the 5 numbers. Where is the problem?

答:
```<code>ArrayList<String> arr= new ArrayList<>();
        Scanner sc= new Scanner(System.in);

        System.out.println("Enter the number of elements in the array");
        int temp= sc.nextInt();
        System.out.println("Enter the elements in the array");

        String num;
        sc.nextLine(); //add this it should work !
        for(int i=0; i<temp; i++) {
            num= sc.nextLine();
            arr.add(num);
            //System.out.println("i= "+ i +"temp= "+temp);
        }
</code>```

Reason --
"You need to move the sc pointer to the next line after taking the first input, your pointer is looking for the first integer on the same line instead of the one below it"

Body:
Here is my code:

        ArrayList<String> arr= new ArrayList();
        Scanner sc= new Scanner(System.in);

        System.out.println("Enter the number of elements in the array");
        int temp= sc.nextInt();
        System.out.println("Enter the elements in the array");

        String num;
        for(int i=0; i<temp; i++) {
            num= sc.nextLine();
            arr.add(num);
            //System.out.println("i= "+ i +"temp= "+temp);
        }

The problem is that if i want to add 5 elements it is taking the first element as null and only letting me to input rest 4 elements but i want to enter all the 5 numbers. Where is the problem?

Body:
ArrayList<String> arr= new ArrayList<>();
        Scanner sc= new Scanner(System.in);

        System.out.println("Enter the number of elements in the array");
        int temp= sc.nextInt();
        System.out.println("Enter the elements in the array");

        String num;
        sc.nextLine(); //add this it should work !
        for(int i=0; i<temp; i++) {
            num= sc.nextLine();
            arr.add(num);
            //System.out.println("i= "+ i +"temp= "+temp);
        }

Reason --
"You need to move the sc pointer to the next line after taking the first input, your pointer is looking for the first integer on the same line instead of the one below it"


问:
Datagridview refresh data keeps old values there
I'm developing a small piece of SW using Windows Forms. I'm trying to populate a datagridview with the content of a list using its dataSource property.

The binding seems to be correct but I'm having this behaviour. Looks like the old data is not removed and the new one is place above the old one, overlapping both texts. I'm not able to determine the reason.

You can see this behaviour here

And here

Every time I need to update my datagridview I'm calling:

```<code> private void updateAforoInDatagridView()
 {
        parentForm.dataGridView2.DataSource = null;
        parentForm.dataGridView2.DataSource = presenter.getTurnosState(dayBookings, dayTurnos);
        parentForm.dataGridView2.Refresh();
        parentForm.dataGridView2.Update();
 }
</code>```

This is the object I'm trying to place in the datagridview

```<code>public string Entrada { get => entrada; set => entrada = value; }
public string Salida { get => salida; set => salida = value; }
public string Nombre { get => nombre; set => nombre = value; }
public decimal Aforo { get => aforo; set => aforo = value; }
public decimal Libre { get => libre; set => libre = value; }
</code>```

First four properties come from a database and the last one is added manually by me after making some calculations here:

```<code>internal List<Turno> getTurnosState(List<Booking> dayBookings, List<Turno> dayTurnos)
{
    for (int i = 0; i < dayTurnos.Count; i++)
    {
        var currentTurno = dayTurnos[i];
        var bookingsForCurrentTurno = dayBookings.Where(booking => booking.TurnoName.Equals(currentTurno.Nombre) && booking.TurnoTime == DateAndTiming.getTimeFromString(currentTurno.Entrada)).ToList();
        currentTurno.Libre = currentTurno.Aforo - bookingsForCurrentTurno.Sum(booking => booking.NumberOfPeople);
    }

    return dayTurnos;
}
</code>```

答:
I eventually got rid of this strange behaviour by removing the datagridview from the view and adding a new one. I can't say precisely which property caused this behaviour but luckily it's been solved.

Thanks.

Body:
I'm developing a small piece of SW using Windows Forms. I'm trying to populate a datagridview with the content of a list using its dataSource property.

The binding seems to be correct but I'm having this behaviour. Looks like the old data is not removed and the new one is place above the old one, overlapping both texts. I'm not able to determine the reason.

You can see this behaviour here

And here

Every time I need to update my datagridview I'm calling:

 private void updateAforoInDatagridView()
 {
        parentForm.dataGridView2.DataSource = null;
        parentForm.dataGridView2.DataSource = presenter.getTurnosState(dayBookings, dayTurnos);
        parentForm.dataGridView2.Refresh();
        parentForm.dataGridView2.Update();
 }

This is the object I'm trying to place in the datagridview

public string Entrada { get => entrada; set => entrada = value; }
public string Salida { get => salida; set => salida = value; }
public string Nombre { get => nombre; set => nombre = value; }
public decimal Aforo { get => aforo; set => aforo = value; }
public decimal Libre { get => libre; set => libre = value; }

First four properties come from a database and the last one is added manually by me after making some calculations here:

internal List<Turno> getTurnosState(List<Booking> dayBookings, List<Turno> dayTurnos)
{
    for (int i = 0; i < dayTurnos.Count; i++)
    {
        var currentTurno = dayTurnos[i];
        var bookingsForCurrentTurno = dayBookings.Where(booking => booking.TurnoName.Equals(currentTurno.Nombre) && booking.TurnoTime == DateAndTiming.getTimeFromString(currentTurno.Entrada)).ToList();
        currentTurno.Libre = currentTurno.Aforo - bookingsForCurrentTurno.Sum(booking => booking.NumberOfPeople);
    }

    return dayTurnos;
}