问:
Is it necessary to check for non-zero length when read from a Reader and write to a Writer in Golang?
When I try to copy from a Reader to a Writer manually, I notice that this works:

```<code>func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        n, err := a.Read(buf)
        if n > 0 {
            if err != nil {
                log.Fatal(err)
            }
            b.Write(buf[0:n])
        }
    }
}
</code>```

But this doesn't

```<code>func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        _, err := a.Read(buf)
        if err != nil {
            log.Fatal(err)
        }
        b.Write(buf)
    }
}
</code>```

So the questions are:

Why is the check if n>0 necessary?

Is this only necessary for net.Conn or for any type that implements the Reader and Writer interfaces?

EDIT: The second snippet runs fine without any runtime error, just that the behavior is not correct. I want to know what is the effect of that n>0 check and what will happen under the surface when I remove it.

答: There's already a function io.Copy to do exactly this. You can see how it's implemented for a good example. It works with all io.Reader/io.Writer types.

Body:
When I try to copy from a Reader to a Writer manually, I notice that this works:

func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        n, err := a.Read(buf)
        if n > 0 {
            if err != nil {
                log.Fatal(err)
            }
            b.Write(buf[0:n])
        }
    }
}

But this doesn't

func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        _, err := a.Read(buf)
        if err != nil {
            log.Fatal(err)
        }
        b.Write(buf)
    }
}

So the questions are:

Why is the check if n>0 necessary?

Is this only necessary for net.Conn or for any type that implements the Reader and Writer interfaces?

EDIT: The second snippet runs fine without any runtime error, just that the behavior is not correct. I want to know what is the effect of that n>0 check and what will happen under the surface when I remove it.


来源: stackexchange

问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答:
I believe the Template Method pattern generally is a very dangerous pattern.

A lot of times it uses up your inheritance hierarchy for "the wrong reasons".

Base classes have a tendency to become littered with all sorts of unerelated code.

It forces you to lock down design, often quite early in the development process. (Premature lock down in a lot of cases)

Changing this at a later stage becomes just harder and harder.

OwnerDisplayName: Brian Rasmussen

ContentLicense: CC BY-SA 2.5

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: krosenvold


问:
ordering y axis with facet
I have this data frame

```<code>library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat %>% arrange(parent,-count )

 parent group value count
1      F  D(5)     4     5
2      F  A(4)     3     4
3      J  A(4)     1     4
4      J  C(3)     2     3
</code>```

You can see above that the data is ordered by parent and then count descending. I would like the chart to keep this ordering BUT when I plot it in the "J" chart C(3) comes on top of A(4) and that should be revered. How can that be done?

```<code>ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")
</code>```

答:
You can try:</p>

```<code>dat %>% arrange(parent,-count ) %>%
  mutate(group2=factor(c(2,1,4,3))) %>%
  ggplot(aes(x = group2, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")+
  scale_x_discrete(breaks=1:4,labels = c("A(4)","D(5)","C(3)","A(4)"))
</code>```

ContentLicense: CC BY-SA 3.0

Title: ordering y axis with facet

Body:
I have this data frame

library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat %>% arrange(parent,-count )

 parent group value count
1      F  D(5)     4     5
2      F  A(4)     3     4
3      J  A(4)     1     4
4      J  C(3)     2     3

You can see above that the data is ordered by parent and then count descending. I would like the chart to keep this ordering BUT when I plot it in the "J" chart C(3) comes on top of A(4) and that should be revered. How can that be done?

ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")

Body:
You can try:

dat %>% arrange(parent,-count ) %>%
  mutate(group2=factor(c(2,1,4,3))) %>%
  ggplot(aes(x = group2, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")+
  scale_x_discrete(breaks=1:4,labels = c("A(4)","D(5)","C(3)","A(4)"))


问:
How to trim values and send to deepEquals method ()
```<code>public static void main(String args[]){
         String [] a={"A","B"};
         String[] b ={"  B"," A"};
         Arrays.sort(a);
         Arrays.sort(b);
         System.out.println(Arrays.deepEquals(a,b));
}
</code>```

I want to compare two string arrays and should return true values but its giving a false value since String[] b values has space. How do I trim my values and send to deepEquals method .

答:
Java 8's streams make this pretty neat:

```<code>public static void main(String args[]){
    String [] a={"A","B"};
    String[] b ={"  B"," A"};
    a = trimAndSort(a);
    b = trimAndSort(b);
    System.out.println(Arrays.deepEquals(a,b));
}

private static String[] trimAndSort(String[] arr) {
    return Arrays.stream(arr).map(String::trim).sorted().toArray(String[]::new);
}
</code>```

Note that since you're dealing with a one-dimensional array, you don't really need to use Arrays#deepEquals, and Arrays#equals would suffice.

Body:
public static void main(String args[]){
         String [] a={"A","B"};
         String[] b ={"  B"," A"};
         Arrays.sort(a);
         Arrays.sort(b);
         System.out.println(Arrays.deepEquals(a,b));
}

I want to compare two string arrays and should return true values but its giving a false value since String[] b values has space. How do I trim my values and send to deepEquals method .

Body:
Java 8's streams make this pretty neat:

public static void main(String args[]){
    String [] a={"A","B"};
    String[] b ={"  B"," A"};
    a = trimAndSort(a);
    b = trimAndSort(b);
    System.out.println(Arrays.deepEquals(a,b));
}

private static String[] trimAndSort(String[] arr) {
    return Arrays.stream(arr).map(String::trim).sorted().toArray(String[]::new);
}

Note that since you're dealing with a one-dimensional array, you don't really need to use Arrays#deepEquals, and Arrays#equals would suffice.


问:
java compare multiple values and find best match
I need to find best matched employee salary in the DB records as:

```<code>Name:   City:     State:

A       (null)    (null)

A       (null)    DEL

(null)  (null)    (null)

A        SAKET    DEL
</code>```

Match order should be:

1. NAME = name, STATE = state, CITY = city

2. NAME = name, STATE = state , CITY = NULL

3. NAME = name, STATE = NULL, CITY = NULL

4. NAME = NULL, STATE = NULL, CITY = NULL

Means if in a row where all attributes matches – it should be selected, if we do not have that kind of data we should go to next best option like select state and city as NULL, etc.

My code as below, is giving me correct results but I need a more efficient way.

```<code>    private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
    BigDecimal salary = null;
    BigDecimal salaryWithState = null;
    BigDecimal salaryWithName = null;
    BigDecimal salaryWithNoMatch = null;
     while (results.next()) {

        String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
        String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
        String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;

        BigDecimal salaryRslt = null;

        if(results.getString("SALARY") != null){
            salaryRslt = BigDecimal.valueOf(results.getDouble("SALARY"));
        }
        if(billerName != null && !billerName.equals("") && billerName.equals(request.getBillPaymentsalaryCalculateInfo().getBillerName())){
            if(city != null && !city.equals("") && city.equals(request.getMsgRqHdr().getCity()) &&
                    state != null && !state.equals("") && state.equalsIgnoreCase(request.getMsgRqHdr().getstate())){
                salary = salaryRslt;
                break;
            } else if((city == null || city.equals("")) && state != null && !state.equals("") &&
                    state.equalsIgnoreCase(request.getMsgRqHdr().getState())){
                salaryWithState = salaryRslt;
            } else if((city == null || city.equals("")) && (state == null || state.equals(""))){
                salaryWithName = salaryRslt;
            }
        } else if((billerName == null || billerName.equals("")) && (city == null || city.equals("")) &&
                (state == null || state.equals(""))){
            salaryWithNoMatch = salaryRslt;
        }
     }

     if(salary != null){
         return salary;
     } else if(salaryWithState != null){
         salary = salaryWithState;
     } else if(salaryWithName != null){
         salary = salaryWithName;
     } else if(salaryWithNoMatch != null){
         salary = salaryWithNoMatch;
     }

     return salary;

}
</code>```

EDIT: I dont want to use 3 extra variables: salaryWithState, salaryWithName,  salaryWithNoMatch.

答:
I have written the same logic in a different way with using arrays. If your environment can afford to use arrays, you can use this code. But I have not tested the code.</p>

```<code> private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
    BigDecimal salary = null;
    int matchCount = 0;
    String rBillerName = request.getBillPaymentsalaryCalculateInfo().getBillerName();
    String rCity = request.getMsgRqHdr().getCity();
    String rState = request.getMsgRqHdr().getstate();

    String [] truthArray = new String[] {rBillerName, rCity, rState};

    while (results.next()) {
        String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
        String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
        String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;
        BigDecimal salaryRslt = results.getString("SALARY") != null ? BigDecimal.valueOf(results.getDouble("SALARY")): null;

        String [] testArray = new String[] {billerName, city, state};

        int localMatchCount = 0;
        for(int i = 0; i < testArray.length; i++) {
            if(testArray[i] != null && testArray[i].equals(truthArray[i]))
                localMatchCount++;
            else {
                break;
            }
        }

        if(localMatchCount >= matchCount){
            matchCount = localMatchCount;
            salary = salaryRslt;
        }
    }
    return salary;
}
</code>```

Body:
I need to find best matched employee salary in the DB records as:

Name:   City:     State:

A       (null)    (null)

A       (null)    DEL

(null)  (null)    (null)

A        SAKET    DEL

Match order should be:

1. NAME = name, STATE = state, CITY = city

2. NAME = name, STATE = state , CITY = NULL

3. NAME = name, STATE = NULL, CITY = NULL

4. NAME = NULL, STATE = NULL, CITY = NULL

Means if in a row where all attributes matches – it should be selected, if we do not have that kind of data we should go to next best option like select state and city as NULL, etc.

My code as below, is giving me correct results but I need a more efficient way.

    private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
    BigDecimal salary = null;
    BigDecimal salaryWithState = null;
    BigDecimal salaryWithName = null;
    BigDecimal salaryWithNoMatch = null;
     while (results.next()) {

        String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
        String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
        String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;

        BigDecimal salaryRslt = null;

        if(results.getString("SALARY") != null){
            salaryRslt = BigDecimal.valueOf(results.getDouble("SALARY"));
        }
        if(billerName != null && !billerName.equals("") && billerName.equals(request.getBillPaymentsalaryCalculateInfo().getBillerName())){
            if(city != null && !city.equals("") && city.equals(request.getMsgRqHdr().getCity()) &&
                    state != null && !state.equals("") && state.equalsIgnoreCase(request.getMsgRqHdr().getstate())){
                salary = salaryRslt;
                break;
            } else if((city == null || city.equals("")) && state != null && !state.equals("") &&
                    state.equalsIgnoreCase(request.getMsgRqHdr().getState())){
                salaryWithState = salaryRslt;
            } else if((city == null || city.equals("")) && (state == null || state.equals(""))){
                salaryWithName = salaryRslt;
            }
        } else if((billerName == null || billerName.equals("")) && (city == null || city.equals("")) &&
                (state == null || state.equals(""))){
            salaryWithNoMatch = salaryRslt;
        }
     }

     if(salary != null){
         return salary;
     } else if(salaryWithState != null){
         salary = salaryWithState;
     } else if(salaryWithName != null){
         salary = salaryWithName;
     } else if(salaryWithNoMatch != null){
         salary = salaryWithNoMatch;
     }

     return salary;

}

EDIT: I dont want to use 3 extra variables: salaryWithState, salaryWithName,  salaryWithNoMatch.

Body:
I have written the same logic in a different way with using arrays. If your environment can afford to use arrays, you can use this code. But I have not tested the code.

 private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
    BigDecimal salary = null;
    int matchCount = 0;
    String rBillerName = request.getBillPaymentsalaryCalculateInfo().getBillerName();
    String rCity = request.getMsgRqHdr().getCity();
    String rState = request.getMsgRqHdr().getstate();

    String [] truthArray = new String[] {rBillerName, rCity, rState};

    while (results.next()) {
        String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
        String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
        String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;
        BigDecimal salaryRslt = results.getString("SALARY") != null ? BigDecimal.valueOf(results.getDouble("SALARY")): null;

        String [] testArray = new String[] {billerName, city, state};

        int localMatchCount = 0;
        for(int i = 0; i < testArray.length; i++) {
            if(testArray[i] != null && testArray[i].equals(truthArray[i]))
                localMatchCount++;
            else {
                break;
            }
        }

        if(localMatchCount >= matchCount){
            matchCount = localMatchCount;
            salary = salaryRslt;
        }
    }
    return salary;
}


问:
How do I create a dynamic array of arrays (of arrays)?
I'm trying to create a dynamic array of arrays (of arrays). But for some reason the data gets corrupted. I'm using the data to generate a texture in a OpenGL application.

The following code works fine:

```<code>unsigned char imageData[64][64][3];
    for (int i = 0; i < 64; i++)
    {
        for (int j = 0; j < 64; j++)
        {
            unsigned char r = 0, g = 0, b = 0;
            if (i < 32)
            {
                if (j < 32)
                    r = 255;
                else
                    b = 255;
            }
            else
            {
                if (j < 32)
                    g = 255;
            }
            imageData[i][j][0] = r;
            imageData[i][j][1] = g;
            imageData[i][j][2] = b;
        }
        std::cout << std::endl;
    }

    glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
</code>```

Problem is, I want to be able to create a texture of any size (not just 64*64). So I'm trying this:

```<code>unsigned char*** imageData = new unsigned char**[64]();
for (int i = 0; i < 64; i++)
{
    imageData[i] = new unsigned char*[64]();
    for (int j = 0; j < 64; j++)
    {
        imageData[i][j] = new unsigned char[3]();
        unsigned char r = 0, g = 0, b = 0;
        if (i < 32)
        {
            if (j < 32)
                r = 255;
            else
                b = 255;
        }
        else
        {
            if (j < 32)
                g = 255;
        }
        imageData[i][j][0] = r;
        imageData[i][j][1] = g;
        imageData[i][j][2] = b;
    }
    std::cout << std::endl;
}

glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
</code>```

But that doesn't work, the image gets all messed up so I assume I'm creating the array of arrays (of arrays) incorrectly? What am I doing wrong?

Also, I guess I should be using vectors instead. But how can I cast the vector of vectors of vectors data into a (void *) ?

答:
You need to use continuous memory for it to work with opengl.
My solution is inspired by previous answers, with a different indexing system

```<code>unsigned char* imageData = new unsigned char[width*height*3];
unsigned char r, g, b;
const unsigned int row_size_bytes = width * 3;

for( unsigned int x = 0; x < width; x++ ) {
   unsigned int current_row_offset_bytes = x * 3;
   for( unsigned int y = 0; y < height; y++ ) {
      unsigned int one_dim_offset = y * row_size_bytes + current_row_offset_bytes
      unsigned char* pixel = &(imageData[one_dim_offset]);
      pixel[0] = r;
      pixel[1] = g;
      pixel[2] = b;
   }
}
</code>```

Unfortunnately it's untested, but i'm confident assuming sizeof(char) is 1.

Body:
I'm trying to create a dynamic array of arrays (of arrays). But for some reason the data gets corrupted. I'm using the data to generate a texture in a OpenGL application.

The following code works fine:

unsigned char imageData[64][64][3];
    for (int i = 0; i < 64; i++)
    {
        for (int j = 0; j < 64; j++)
        {
            unsigned char r = 0, g = 0, b = 0;
            if (i < 32)
            {
                if (j < 32)
                    r = 255;
                else
                    b = 255;
            }
            else
            {
                if (j < 32)
                    g = 255;
            }
            imageData[i][j][0] = r;
            imageData[i][j][1] = g;
            imageData[i][j][2] = b;
        }
        std::cout << std::endl;
    }

    glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

Problem is, I want to be able to create a texture of any size (not just 64*64). So I'm trying this:

unsigned char*** imageData = new unsigned char**[64]();
for (int i = 0; i < 64; i++)
{
    imageData[i] = new unsigned char*[64]();
    for (int j = 0; j < 64; j++)
    {
        imageData[i][j] = new unsigned char[3]();
        unsigned char r = 0, g = 0, b = 0;
        if (i < 32)
        {
            if (j < 32)
                r = 255;
            else
                b = 255;
        }
        else
        {
            if (j < 32)
                g = 255;
        }
        imageData[i][j][0] = r;
        imageData[i][j][1] = g;
        imageData[i][j][2] = b;
    }
    std::cout << std::endl;
}

glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

But that doesn't work, the image gets all messed up so I assume I'm creating the array of arrays (of arrays) incorrectly? What am I doing wrong?

Also, I guess I should be using vectors instead. But how can I cast the vector of vectors of vectors data into a (void *) ?

Body:
You need to use continuous memory for it to work with opengl.
My solution is inspired by previous answers, with a different indexing system

unsigned char* imageData = new unsigned char[width*height*3];
unsigned char r, g, b;
const unsigned int row_size_bytes = width * 3;

for( unsigned int x = 0; x < width; x++ ) {
   unsigned int current_row_offset_bytes = x * 3;
   for( unsigned int y = 0; y < height; y++ ) {
      unsigned int one_dim_offset = y * row_size_bytes + current_row_offset_bytes
      unsigned char* pixel = &(imageData[one_dim_offset]);
      pixel[0] = r;
      pixel[1] = g;
      pixel[2] = b;
   }
}

Unfortunnately it's untested, but i'm confident assuming sizeof(char) is 1.


问:
Streaming large static files using NodeJS
I need to consume large unformatted read-only text files periodically and check for the presence of certain content/words in each of those files. This file is composed of all alphanumeric characters. However, I am having issues even reading to the end of the stream for one of these large static files.

Below is a copy of the simplest code I tried to run after noticing it was not reaching the end and this still does not trigger an end event. I can see many iterations/chunks of data being read, but never all of the data for the file and end is never triggered.

```<code>function readFile(file) {
    const readStream = fs.createReadStream(file, {
      fd: null,
      flags: 'r',
      encoding: 'utf-8',
      allowVolatile: true,
      highWaterMark: staticHighWaterMark,
    });

    readStream.on('data', (chunk) => {
      console.log('DATA chunk', chunk.length);
    });

    readStream.on('end', () => {
      console.log('END file');
    });
}
</code>```

This is so simple that I'm starting to wonder if it's something with my environment, but if there is anything identified as an issue in the simple logic above to read the stream, please let me know.

NOTE: If I keep increasing the highWaterMark option it makes it further through the file, but still does not reach the end of the file. However, that shouldn't make a difference to reaching, or not reaching, the end of the file but instead control how much data it reads per 'chunk'.

答:
Can you test this and see if with this you will be able to read the entire file?</p>

```<code>function readFileV2(file) {
    const readStream = fs.createReadStream(file, {
      fd: null,
      flags: 'r',
      encoding: 'utf-8',
      allowVolatile: true,
      highWaterMark: staticHighWaterMark,
    });

    readStream.pipe(process.stdout);
}
</code>```

Body:
I need to consume large unformatted read-only text files periodically and check for the presence of certain content/words in each of those files. This file is composed of all alphanumeric characters. However, I am having issues even reading to the end of the stream for one of these large static files.

Below is a copy of the simplest code I tried to run after noticing it was not reaching the end and this still does not trigger an end event. I can see many iterations/chunks of data being read, but never all of the data for the file and end is never triggered.

function readFile(file) {
    const readStream = fs.createReadStream(file, {
      fd: null,
      flags: 'r',
      encoding: 'utf-8',
      allowVolatile: true,
      highWaterMark: staticHighWaterMark,
    });

    readStream.on('data', (chunk) => {
      console.log('DATA chunk', chunk.length);
    });

    readStream.on('end', () => {
      console.log('END file');
    });
}

This is so simple that I'm starting to wonder if it's something with my environment, but if there is anything identified as an issue in the simple logic above to read the stream, please let me know.

NOTE: If I keep increasing the highWaterMark option it makes it further through the file, but still does not reach the end of the file. However, that shouldn't make a difference to reaching, or not reaching, the end of the file but instead control how much data it reads per 'chunk'.

Body:
Can you test this and see if with this you will be able to read the entire file?

function readFileV2(file) {
    const readStream = fs.createReadStream(file, {
      fd: null,
      flags: 'r',
      encoding: 'utf-8',
      allowVolatile: true,
      highWaterMark: staticHighWaterMark,
    });

    readStream.pipe(process.stdout);
}


问:
How could I make the SurfaceView and Button have a different orientation in a Activity
I hava a simple program about video recording .
I use the surfaceView to show the preview screen.
and I also want to put some buttons on the screen.

I put all the component mentioned above into a XML file which is "ipcam.xml"

I use MediaRecorder , SurfaceView , SurfaceHolder to complete this program
because the preview screen does not orientate correctly when I rotate my phone.
so I use "setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);"
but , the button in the program is always in LANDSCAPE direction .
it will not auto change direction when I rotate my phone , but the preview is ok!!

so is there anyway to solve this problem.

Thank you all very much in advance.

you can see this picture , I put my phone in vertical direction
the preview screen seems OK
 but the button is in horizontal direction , i don't want it.

https://newslab.csie.ntu.edu.tw/~poc7667/123.png

答:
Try this:</p>

```<code><activity android:name=".MyActivity"
      android:label="@string/app_title"
      android:screenOrientation="landscape"
      android:configChanges="keyboardHidden|orientation">
</activity>
</code>```

Body:
Try this:

<activity android:name=".MyActivity"
      android:label="@string/app_title"
      android:screenOrientation="landscape"
      android:configChanges="keyboardHidden|orientation">
</activity>


问:
Java program wont react till the window gets resized
I have a simple java program and when I run it, using eclipse, it displays the 3 JButtons that I have set to the layout. The buttons are set to change the alignment of the layout. So you press left to align left and right to align right and center to align center.

While the buttons do this, the alignment doesn't change in the window till you resize it.

Ive tried updating both the jdk and eclipse and didnt make a difference and I cant see a problem with the code itself.

Anyone know why this is?

import javax.swing.JFrame;

```<code>public class Main {
    public static void main(String []args){

        Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents();

        layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout.setSize(300,300);
        layout.setVisible(true);

    }

}

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Layout_buttonsAndActionEvents extends JFrame {

    private static final long serialVersionUID = 1L;
    private JButton leftButton;
    private JButton rightButton;
    private JButton centerButton;

    private FlowLayout layout;
    private Container container;

    public Layout_buttonsAndActionEvents(){
        super("The Title");
        layout = new FlowLayout();
        container = new Container();
        setLayout(layout);

        leftButton = new JButton("Left");
        add(leftButton);
    //Align to the left
        leftButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent event){
                layout.setAlignment(FlowLayout.LEFT);
                layout.layoutContainer(container);
            }
        });

    centerButton = new JButton("Center");
    add(centerButton);

    //Align to the right
         centerButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.CENTER);
                    layout.layoutContainer(container);
                }
            });

         rightButton = new JButton("Right");
        add(rightButton);

        //Align to the right
            rightButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.RIGHT);
                    layout.layoutContainer(container);
                }
            });

    }

}
</code>```

答:
When you resize a JFrame, it is re-validated with the new size and layout. Similarly, you must validate the and repaint the frame after adding the altered layout to apply a visual difference.

Make sure to call these methods in this order after altering the layout:

```<code>setLayout(layout);
repaint();
revalidate();
</code>```

Body:
I have a simple java program and when I run it, using eclipse, it displays the 3 JButtons that I have set to the layout. The buttons are set to change the alignment of the layout. So you press left to align left and right to align right and center to align center.

While the buttons do this, the alignment doesn't change in the window till you resize it.

Ive tried updating both the jdk and eclipse and didnt make a difference and I cant see a problem with the code itself.

Anyone know why this is?

import javax.swing.JFrame;

public class Main {
    public static void main(String []args){

        Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents();

        layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout.setSize(300,300);
        layout.setVisible(true);

    }

}

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Layout_buttonsAndActionEvents extends JFrame {

    private static final long serialVersionUID = 1L;
    private JButton leftButton;
    private JButton rightButton;
    private JButton centerButton;

    private FlowLayout layout;
    private Container container;

    public Layout_buttonsAndActionEvents(){
        super("The Title");
        layout = new FlowLayout();
        container = new Container();
        setLayout(layout);

        leftButton = new JButton("Left");
        add(leftButton);
    //Align to the left
        leftButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent event){
                layout.setAlignment(FlowLayout.LEFT);
                layout.layoutContainer(container);
            }
        });

    centerButton = new JButton("Center");
    add(centerButton);

    //Align to the right
         centerButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.CENTER);
                    layout.layoutContainer(container);
                }
            });

         rightButton = new JButton("Right");
        add(rightButton);

        //Align to the right
            rightButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.RIGHT);
                    layout.layoutContainer(container);
                }
            });

    }

}

Body:
When you resize a JFrame, it is re-validated with the new size and layout. Similarly, you must validate the and repaint the frame after adding the altered layout to apply a visual difference.

Make sure to call these methods in this order after altering the layout:

setLayout(layout);
repaint();
revalidate();


问:
Creating Lua dissector in Wireshark for non-Ethernet data
I'm trying to create dissector in Wireshark using Lua script for non-Ethernet data. For example, I captured I2C bus data, converted it to .pcap file format, which can be opened by Wireshark. Each record has one byte of address and few bytes of data. How can I handle this in Lua for dissecting data?</p>

答:
If you look at the packet-i2c.c source file, you will see on line 258 that you need to register your dissector with the "i2c.message" table, similar to how it was described in the How to register a Lua dissector for 802.1Q Ethernet payload question over at Wireshark's Q&A site.  So, in your case, something like:

```<code>-- Protocol
local p_i2cfoo = Proto("i2cfoo", "I2C FOO Protocol")

-- Fields
local f_i2cfoo_addr = ProtoField.uint8("i2cfoo.addr", "Address", base.DEC)
local f_i2cfoo_val16 = ProtoField.uint16("i2cfoo.val16", "Value 16", base.HEX)
local f_i2cfoo_val32 = ProtoField.uint32("i2cfoo.val32", "Value 32", base.HEX)

p_i2cfoo.fields = { f_i2cfoo_addr, f_i2cfoo_val16, f_i2cfoo_val32 }

-- Dissection
function p_i2cfoo.dissector(buf, pinfo, tree)
    local i2cfoo_tree = tree:add(p_i2cfoo, buf(0,-1))

    pinfo.cols.protocol:set("I2CFOO")
    pinfo.cols.info:set("Hello World!")

    i2cfoo_tree:add(f_i2cfoo_addr, buf(0, 1))
    i2cfoo_tree:add(f_i2cfoo_val16, buf(1, 2))
    i2cfoo_tree:add(f_i2cfoo_val32, buf(3, 4))
end

-- Registration
local i2c_table = DissectorTable.get("i2c.message")
i2c_table:add(0, p_i2cfoo)
</code>```

Body:
If you look at the packet-i2c.c source file, you will see on line 258 that you need to register your dissector with the "i2c.message" table, similar to how it was described in the How to register a Lua dissector for 802.1Q Ethernet payload question over at Wireshark's Q&A site.  So, in your case, something like:

-- Protocol
local p_i2cfoo = Proto("i2cfoo", "I2C FOO Protocol")

-- Fields
local f_i2cfoo_addr = ProtoField.uint8("i2cfoo.addr", "Address", base.DEC)
local f_i2cfoo_val16 = ProtoField.uint16("i2cfoo.val16", "Value 16", base.HEX)
local f_i2cfoo_val32 = ProtoField.uint32("i2cfoo.val32", "Value 32", base.HEX)

p_i2cfoo.fields = { f_i2cfoo_addr, f_i2cfoo_val16, f_i2cfoo_val32 }

-- Dissection
function p_i2cfoo.dissector(buf, pinfo, tree)
    local i2cfoo_tree = tree:add(p_i2cfoo, buf(0,-1))

    pinfo.cols.protocol:set("I2CFOO")
    pinfo.cols.info:set("Hello World!")

    i2cfoo_tree:add(f_i2cfoo_addr, buf(0, 1))
    i2cfoo_tree:add(f_i2cfoo_val16, buf(1, 2))
    i2cfoo_tree:add(f_i2cfoo_val32, buf(3, 4))
end

-- Registration
local i2c_table = DissectorTable.get("i2c.message")
i2c_table:add(0, p_i2cfoo)


问:
c# uwp listview finished loading items
In C# UWP what event is fired when all items in listview are loaded and rendering is done?

I need to make some calculations that will be executed after loading is finished.

答: Is FrameworkElement.Loaded what you're looking for?</p>

Title: c# uwp listview finished loading items


问:
Best way to list the items through a card using node.js
I am a newbie in chatbot and i am using microsoft bot framework.I want to list the items that my knowlegde base has trained with. What kind of cards can be used to prompt the user like "Hey user, I am trained with these list of items 1. .. 2. .. 3. .. "
Thanks in advance..</p>

答: For cards, it is important to know which channel you will be using because they render differently on different channels.  I would go through the rich cards readme.md here as well as this adaptive cards readme.md.  Those are great samples you can play around with to see what suits your needs. also adaptivecards.io  and here is a list of channel supported by adaptive cards</p>


问:
Creating a split view application similar to 'settings' app
I am trying to build an iPad app set-up as a split-view, but on the detail page being able to drill down like a navigation controller.

An example of this working is the setting app on the iPad where if you select the 'General' tab you can then drill down on the detail page from say general > network > VPN

Any help or tips on this would be great. I thought it might be two navigation controllers on the root nib, but couldn't get this working.

答:
you mean like General -> About ->.. (in ipad simulator) right .

if all your detail view needs the TableView, then its better to make your detailviewcontroller as  the subclass of UITableViewCOntroller.

OR If you need different views when click on the cells of rootcontroller(left pane)

Create a method in DetailViewController say setDetailView{}. And call this method when click on the cell of RootController
inside this method,

remove all subviews from detailview

create UITableView and set its delegates

on tableview didSelect method, we can push other UIViewController instance
[self.navigationController push...]

Hope it helps.


问:
Multiple builtin type for graphql
How can I create a multiple type for graphql? I have this given code:

```<code>status: {
  type: GraphQLString || GraphQLBoolean,
  resolver: Blahblah
}
</code>```

obviously this doesn't work coz it converts the boolean to string, I want to support both boolean and string.

I can't just make them string and adjust the code because other projects are using them and it will take sometime after I can contact the other devs, And yes we have a bad data on our database.

Thanks in advance.

答:
GraphQL is all about specificity. There is intentionally very little room for ambiguity in the spec, even when it eliminates convenient shortcuts, I think one solution to the problem here could be a Union type, whereby you define a type that is a union of other types, so for example

```<code>type StringType {
  fieldName: String
}

type BooleanType {
  fieldName: Boolean
}

union StringBool = StringType | BooleanType

myQuery(someArg: String!): StringBool
</code>```

Keep in mind that this is only an acceptable type as a return value for queries. It is not an acceptable input type for mutations. When you specify the fields you want returned from your query, you will have to "fragment" on the different types, and explain which fields you want back from each possible member of the union:

```<code>... on StringType {
  fieldName
}
... on BooleanType {
  fieldName
}
</code>```

Title: Multiple builtin type for graphql

Body:
How can I create a multiple type for graphql? I have this given code:

status: {
  type: GraphQLString || GraphQLBoolean,
  resolver: Blahblah
}

obviously this doesn't work coz it converts the boolean to string, I want to support both boolean and string.

I can't just make them string and adjust the code because other projects are using them and it will take sometime after I can contact the other devs, And yes we have a bad data on our database.

Thanks in advance.

Body:
GraphQL is all about specificity. There is intentionally very little room for ambiguity in the spec, even when it eliminates convenient shortcuts, I think one solution to the problem here could be a Union type, whereby you define a type that is a union of other types, so for example

type StringType {
  fieldName: String
}

type BooleanType {
  fieldName: Boolean
}

union StringBool = StringType | BooleanType

myQuery(someArg: String!): StringBool

Keep in mind that this is only an acceptable type as a return value for queries. It is not an acceptable input type for mutations. When you specify the fields you want returned from your query, you will have to "fragment" on the different types, and explain which fields you want back from each possible member of the union:

... on StringType {
  fieldName
}
... on BooleanType {
  fieldName
}


问:
differentiate between instances of the same form with different prefixes in Django
I am passing two form with different prefix in the template and each form has own submit button but how can I get data from these two form in submit button is pressed in any one of them and how to differentiate which form button was pressed

```<code>return render(request,'part_details.html', {'part_stock_form': forms.part_stock_form(prefix='add'),'part_stock_edit':forms.part_stock_form(prefix='edit')})
</code>```

template: add_app form object

```<code><form id="add_app_form" method="post" action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {% csrf_token %}
    {{ add_app.applicable }}
    <input type="submit">
</form>
</code>```

template: edit_app form object

```<code>  <form method="post"  action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {{ edit_app.applicable }}
    <input type="submit">
</form>
</code>```

答:
One simple way is to check keys of POST data.
Let's say you have field1 in one form and field2 in another form, but neither is present in both the forms.

```<code>if 'field1' in request.POST.keys():
    #statements
elif 'field2' in request.POST.keys():
    #statements
</code>```

Other way is sending them to different urls under action attribute of form and then define separate views for them, and configuring urls.py accordingly.
Hope it helps.

Body:
I am passing two form with different prefix in the template and each form has own submit button but how can I get data from these two form in submit button is pressed in any one of them and how to differentiate which form button was pressed

return render(request,'part_details.html', {'part_stock_form': forms.part_stock_form(prefix='add'),'part_stock_edit':forms.part_stock_form(prefix='edit')})

template: add_app form object

<form id="add_app_form" method="post" action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {% csrf_token %}
    {{ add_app.applicable }}
    <input type="submit">
</form>

template: edit_app form object

  <form method="post"  action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {{ edit_app.applicable }}
    <input type="submit">
</form>

Body:
One simple way is to check keys of POST data.
Let's say you have field1 in one form and field2 in another form, but neither is present in both the forms.

if 'field1' in request.POST.keys():
    #statements
elif 'field2' in request.POST.keys():
    #statements

Other way is sending them to different urls under action attribute of form and then define separate views for them, and configuring urls.py accordingly.
Hope it helps.


问:
Custom Deserializer in Json
I want to implement a custom Json mapping to the POJO below at class level.

```<code>@JsonDeserialize(using = DeviceDeserializer.class)
 public class Pojo {
   private String device;
   private String port;
   private String reservbleBw;
   *default constructor, getter and setters*
 }
</code>```

Below is my Json File

```<code>[
  {
   "Device":"ABCD",
   "ifces":[
     {
      "port":"ABCD:1/2/0",
      "reservableBW":"1000",
      "capabilites":[ "MPLS" ]
    },
    {
      "port":"ABCD:1/2/1",
      "reservableBW":"100",
      "capabilites":[ "ETHERNET" ]
    }
  ]
 }
]
</code>```

Now i only need to map the ports and reservableBw when 'capabilities' is 'ETHERNET'. I looked at few examples of custom deserializer but i do not know how to pass the value for JsonParser and DeserializationContext. I have problem understanding the below line.

```<code>  public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
 // custom deserializer implementation
}
</code>```

答:
Your model:

```<code>public class Ifce {

    public String port;
    public String reservableBW;
    public List<String> capabilites = null;

}

public class Device {
    public String device;
    public List<Ifce> ifces = null;

}
</code>```

Then use the objectMapper like this:

```<code>objectMapper = new ObjectMapper()
Device device = objectMapper.readValue(yourJsonData, Device.class)
List<Ifce> deviceList  = device.ifces.find { it.capabilites.contains("ETHERNET")}
</code>```

Title: Custom Deserializer in Json

Body:
I want to implement a custom Json mapping to the POJO below at class level.

@JsonDeserialize(using = DeviceDeserializer.class)
 public class Pojo {
   private String device;
   private String port;
   private String reservbleBw;
   *default constructor, getter and setters*
 }

Below is my Json File

[
  {
   "Device":"ABCD",
   "ifces":[
     {
      "port":"ABCD:1/2/0",
      "reservableBW":"1000",
      "capabilites":[ "MPLS" ]
    },
    {
      "port":"ABCD:1/2/1",
      "reservableBW":"100",
      "capabilites":[ "ETHERNET" ]
    }
  ]
 }
]

Now i only need to map the ports and reservableBw when 'capabilities' is 'ETHERNET'. I looked at few examples of custom deserializer but i do not know how to pass the value for JsonParser and DeserializationContext. I have problem understanding the below line.

  public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
 // custom deserializer implementation
}

Body:
Your model:

public class Ifce {

    public String port;
    public String reservableBW;
    public List<String> capabilites = null;

}

public class Device {
    public String device;
    public List<Ifce> ifces = null;

}

Then use the objectMapper like this:

objectMapper = new ObjectMapper()
Device device = objectMapper.readValue(yourJsonData, Device.class)
List<Ifce> deviceList  = device.ifces.find { it.capabilites.contains("ETHERNET")}


问:
Golang encoding/json marshall add null
Hi i am working with golang on encoding/json and it return the json error with null:

```<code>{"user_message":"Can't find any Query with those parameters","application_context":"GroupsRepository.GetGroupsByQuery: ApplicationError: UserMessage - Error querying database for many Groups. ApplicationContext - Groups.GetMany: pq: column \"refill_too_soon_gpi_digits\" does not exist"} null
</code>```

and the way that i marshall that it is:

```<code>func EncodeErrorResponse(w http.ResponseWriter, err error, status int) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(err)
}
</code>```

could someone help me please.

答: Looking at the JSON output you quoted, it looks like the error is being encoded correctly, but null is being output after the JSON, indicating a separate write operation. The function that calls EncodeErrorResponse, after it calls it, is writing additional output to the ResponseWriter.</p>

Title: Golang encoding/json marshall add null

Body:
Hi i am working with golang on encoding/json and it return the json error with null:

{"user_message":"Can't find any Query with those parameters","application_context":"GroupsRepository.GetGroupsByQuery: ApplicationError: UserMessage - Error querying database for many Groups. ApplicationContext - Groups.GetMany: pq: column \"refill_too_soon_gpi_digits\" does not exist"} null

and the way that i marshall that it is:

func EncodeErrorResponse(w http.ResponseWriter, err error, status int) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(err)
}

could someone help me please.


问:
PhpStorm file watchers to minify and merge JS files from multiple folders
I am trying to accomplish the following.

I have raw assets such as JavaScript source files in folder assets/js in application root. I also have folder public where should go minified files that will be loaded in application.

What I want is when I change my js files I want to IDE create minified versions of it, and then to merge those minified files into one in public folder.

I need two file watchers but don't know how to configure them.

I tried default options for YUI Compressor and those build minified files in the same folder where source files are. But I can't manage to merge those files with File Watcher.

I also created two scopes, one for source JS files, and one for minified JS files.

I am not even sure if File Watchers can do this. I am talking about multiple folders, and recursive scopes.

I would appreciate any help.

答:
File watcher itself can't do anything, as it is nothing more then a way to set up some tool with CLI as a listener to file changes. So, you need to find a tool that would combine your minified files into a single file, and set it up as a watcher, external tool, etc. You can find plenty of such files on the web - see
Combine multiple JavaScript files into one JS file, for example.

But, rather than using 2 separate tools set up as watchers, etc., I'd suggest using Grunt, Gulp, webpack,...
You can try using grunt-contrib-uglify, for example:

```<code>module.exports = function (grunt) {
grunt.initConfig({

    ngmin: {
           concat:{
            src: ['assets/js/*.js'],
            dest: 'public/out.min.js'
    }}
});
grunt.loadNpmTasks('grunt-ngmin');

grunt.registerTask('default', ['ngmin' ])
</code>```

You can run the task using Grunt console, or configure it as a file watcher

Body:
File watcher itself can't do anything, as it is nothing more then a way to set up some tool with CLI as a listener to file changes. So, you need to find a tool that would combine your minified files into a single file, and set it up as a watcher, external tool, etc. You can find plenty of such files on the web - see
Combine multiple JavaScript files into one JS file, for example.

But, rather than using 2 separate tools set up as watchers, etc., I'd suggest using Grunt, Gulp, webpack,...
You can try using grunt-contrib-uglify, for example:

module.exports = function (grunt) {
grunt.initConfig({

    ngmin: {
           concat:{
            src: ['assets/js/*.js'],
            dest: 'public/out.min.js'
    }}
});
grunt.loadNpmTasks('grunt-ngmin');

grunt.registerTask('default', ['ngmin' ])

You can run the task using Grunt console, or configure it as a file watcher


问:
Python Multiprocessing Modules
EDIT: Updated with environment information (see first section)

Environment

I'm using Python 2.7

Ubuntu 16.04

Issue

I have an application which I've simplified into a three-stage process:

Gather data from multiple data sources (HTTP requests, system info, etc)

Compute metrics based on this data

Output these metrics in various formats

Each of these stages must complete before moving on to the next stage, however each stage consists of multiple sub-tasks that can be run in parallel (I can send off 3 HTTP requests and read system logs while waiting for them to return)

I've divided up the stages into modules and the sub-tasks into submodules, so my project hierarchy looks like so:

```<code>+ datasources
|-- __init__.py
|-- data_one.py
|-- data_two.py
|-- data_three.py
+ metrics
|-- __init__.py
|-- metric_one.py
|-- metric_two.py
+ outputs
|-- output_one.py
|-- output_two.py
- app.py
</code>```

app.py looks roughly like so (pseudo-code for brevity):

```<code>import datasources
import metrics
import outputs

for datasource in dir(datasources):
    datasource.refresh()
for metric in dir(metrics):
    metric.calculate()
for output in dir(outputs):
    output.dump()
</code>```

(There's additional code wrapping the dir call to ignore system modules, there's exception handling, etc -- but this is the gist of it)

Each datasource sub-module looks roughly like so:

```<code>data = []

def refresh():
    # Populate the "data" member somehow
    data = [1, 2, 3]
    return
</code>```

Each metric sub-module looks roughly like so:

```<code>import datasources.data_one as data_one
import datasources.data_two as data_two

data = []

def calculate():
    # Use the datasources to compute the metric
    data = [sum(x) for x in zip(data_one, data_two)]
    return
</code>```

In order to parallelize the first stage (datasources) I wrote something simple like the following:

```<code>def run_thread(datasource):
    datasource.refresh()

threads = []
for datasource in dir(datasources):
    thread = threading.Thread(target=run_thread, args=(datasource))
    threads.append(thread)
    thread.start()
for thread in threads:
    thread.join()
</code>```

This works, and afterwards I can compute any metric and the datasources.x.data attribute is populated

In order to parallelize the second stage (metrics) because it depends less on I/O and more on CPU, I felt like simple threading wouldn't actually speed things up and I would need the multiprocessing module in order to take advantage of multiple cores. I wrote the following:

```<code>def run_pool(calculate):
    calculate()

pool = multiprocessing.Pool()
pool.map(run_pool, [m.calculate for m in dir(metrics)]
pool.close()
pool.join()
</code>```

This code runs for a few seconds (so I think it's working?) but then when I try:

```<code>metrics.metric_one.data
</code>```

it returns [], like the module was never run

Somehow by using the multiprocessing module it seems to be scoping the threads so that they no longer share the data attribute. How should I go about rewriting this so that I can compute each metric in parallel, taking advantage of multiple cores, but still have access to the data when it's done?

答:
Process and Thread behave quite differently in python. If you want to use multiprocessing you will need to use a synchronized data type to pass information around.

For example you could use multiprocessing.Array, which can be shared between your processes.

For detail see the docs: https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes

Title: Python Multiprocessing Modules

Body:
EDIT: Updated with environment information (see first section)

Environment

I'm using Python 2.7

Ubuntu 16.04

Issue

I have an application which I've simplified into a three-stage process:

Gather data from multiple data sources (HTTP requests, system info, etc)

Compute metrics based on this data

Output these metrics in various formats

Each of these stages must complete before moving on to the next stage, however each stage consists of multiple sub-tasks that can be run in parallel (I can send off 3 HTTP requests and read system logs while waiting for them to return)

I've divided up the stages into modules and the sub-tasks into submodules, so my project hierarchy looks like so:

+ datasources
|-- __init__.py
|-- data_one.py
|-- data_two.py
|-- data_three.py
+ metrics
|-- __init__.py
|-- metric_one.py
|-- metric_two.py
+ outputs
|-- output_one.py
|-- output_two.py
- app.py

app.py looks roughly like so (pseudo-code for brevity):

import datasources
import metrics
import outputs

for datasource in dir(datasources):
    datasource.refresh()
for metric in dir(metrics):
    metric.calculate()
for output in dir(outputs):
    output.dump()

(There's additional code wrapping the dir call to ignore system modules, there's exception handling, etc -- but this is the gist of it)

Each datasource sub-module looks roughly like so:

data = []

def refresh():
    # Populate the "data" member somehow
    data = [1, 2, 3]
    return

Each metric sub-module looks roughly like so:

import datasources.data_one as data_one
import datasources.data_two as data_two

data = []

def calculate():
    # Use the datasources to compute the metric
    data = [sum(x) for x in zip(data_one, data_two)]
    return

In order to parallelize the first stage (datasources) I wrote something simple like the following:

def run_thread(datasource):
    datasource.refresh()

threads = []
for datasource in dir(datasources):
    thread = threading.Thread(target=run_thread, args=(datasource))
    threads.append(thread)
    thread.start()
for thread in threads:
    thread.join()

This works, and afterwards I can compute any metric and the datasources.x.data attribute is populated

In order to parallelize the second stage (metrics) because it depends less on I/O and more on CPU, I felt like simple threading wouldn't actually speed things up and I would need the multiprocessing module in order to take advantage of multiple cores. I wrote the following:

def run_pool(calculate):
    calculate()

pool = multiprocessing.Pool()
pool.map(run_pool, [m.calculate for m in dir(metrics)]
pool.close()
pool.join()

This code runs for a few seconds (so I think it's working?) but then when I try:

metrics.metric_one.data

it returns [], like the module was never run

Somehow by using the multiprocessing module it seems to be scoping the threads so that they no longer share the data attribute. How should I go about rewriting this so that I can compute each metric in parallel, taking advantage of multiple cores, but still have access to the data when it's done?


问:
Not able to add Multiple Markers in GSMapView xCode Swift 3
I am trying to add multiple Markers on Googlemaps in my app.

In the viewcontrolller under viewDidLoad I am able to load the map and a single marker.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    title = NSLocalizedString("section_map", comment: "test")
    let camera = GMSCameraPosition.camera(withLatitude: 48.7784, longitude:9.18121, zoom: 12)
    let mapView = GMSMapView.map(withFrame: .zero, camera: camera)

    view = mapView
    mapView.settings.myLocationButton = true

    mapView.delegate = self

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 48.7784,longitude: 9.18121)
    marker.title = "title"
    marker.snippet = "snipple"
    marker.icon = UIImage(named:"pin_you")
    marker.map = mapView

    mapData()
}
</code>```

It call mapData() and from there is json file is generated
after parsing setPin is called to set the markers

```<code>  func setPin(){

    DispatchQueue.main.async {

       for item in self.mapItems {
           print (" \(item.name)  \(item.marker) \(item.latitude) \(item.longitude)")

           let marker = GMSMarker()
           marker.position = CLLocationCoordinate2D(latitude: item.latitude,longitude: item.longitude)
           marker.title = item.name
           marker.snippet = item.fulladdress

           var iconImage: String
           switch (item.marker){
           case 1:
              iconImage = "pin_silver"
           case 2:
              iconImage = "pin_blue"
           case 3:
              iconImage = "pin_gold"
           case 6:
              iconImage = "pin_you"
           default:
              iconImage = "pin_silver"
           }
           marker.icon = UIImage(named:iconImage)
           marker.map = self.mapView

       }

    }
}
</code>```

The pins are not shown.

The print in for item in self.mapItems shows

```<code>Position number A  1 48.76947562 9.15440351
Position number B  1 48.75716485 9.17081058
Position number C  1 48.81191625 9.22752149
Position number D  2 48.81192516 9.22766708
</code>```

this means all the proper data is available.
However the map is there the one pin made in viewDidLoad
The Markers in function setPin are not shown or maybe not set.

Does any-one have an idea?

答:
I have solved it in have changed the mapData(mapView: GMSMapView!) also for setPin(mapView: GMSMapView!)</p>

```<code>  func setpin(mapView: GMSMapView!){

    DispatchQueue.main.async {

       for item in self.mapItems {
           print (" \(item.name)  \(item.marker) \(item.latitude) \(item.longitude)")

           let marker = GMSMarker()
           marker.position = CLLocationCoordinate2D(latitude: item.latitude,longitude: item.longitude)
           marker.title = item.name
           marker.snippet = item.fulladdress

           var iconImage: String
           switch (item.marker){
           case 1:
              iconImage = "pin_silver"
           case 2:
              iconImage = "pin_blue"
           case 3:
              iconImage = "pin_gold"
           case 6:
              iconImage = "pin_you"
           default:
              iconImage = "pin_silver"
           }
           marker.icon = UIImage(named:iconImage)
           marker.map = mapView

       }

    }
}
</code>```

Body:
I am trying to add multiple Markers on Googlemaps in my app.

In the viewcontrolller under viewDidLoad I am able to load the map and a single marker.

override func viewDidLoad() {
    super.viewDidLoad()
    title = NSLocalizedString("section_map", comment: "test")
    let camera = GMSCameraPosition.camera(withLatitude: 48.7784, longitude:9.18121, zoom: 12)
    let mapView = GMSMapView.map(withFrame: .zero, camera: camera)

    view = mapView
    mapView.settings.myLocationButton = true

    mapView.delegate = self

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 48.7784,longitude: 9.18121)
    marker.title = "title"
    marker.snippet = "snipple"
    marker.icon = UIImage(named:"pin_you")
    marker.map = mapView

    mapData()
}

It call mapData() and from there is json file is generated
after parsing setPin is called to set the markers

  func setPin(){

    DispatchQueue.main.async {

       for item in self.mapItems {
           print (" \(item.name)  \(item.marker) \(item.latitude) \(item.longitude)")

           let marker = GMSMarker()
           marker.position = CLLocationCoordinate2D(latitude: item.latitude,longitude: item.longitude)
           marker.title = item.name
           marker.snippet = item.fulladdress

           var iconImage: String
           switch (item.marker){
           case 1:
              iconImage = "pin_silver"
           case 2:
              iconImage = "pin_blue"
           case 3:
              iconImage = "pin_gold"
           case 6:
              iconImage = "pin_you"
           default:
              iconImage = "pin_silver"
           }
           marker.icon = UIImage(named:iconImage)
           marker.map = self.mapView

       }

    }
}

The pins are not shown.

The print in for item in self.mapItems shows

Position number A  1 48.76947562 9.15440351
Position number B  1 48.75716485 9.17081058
Position number C  1 48.81191625 9.22752149
Position number D  2 48.81192516 9.22766708

this means all the proper data is available.
However the map is there the one pin made in viewDidLoad
The Markers in function setPin are not shown or maybe not set.

Does any-one have an idea?

Body:
I have solved it in have changed the mapData(mapView: GMSMapView!) also for setPin(mapView: GMSMapView!)

  func setpin(mapView: GMSMapView!){

    DispatchQueue.main.async {

       for item in self.mapItems {
           print (" \(item.name)  \(item.marker) \(item.latitude) \(item.longitude)")

           let marker = GMSMarker()
           marker.position = CLLocationCoordinate2D(latitude: item.latitude,longitude: item.longitude)
           marker.title = item.name
           marker.snippet = item.fulladdress

           var iconImage: String
           switch (item.marker){
           case 1:
              iconImage = "pin_silver"
           case 2:
              iconImage = "pin_blue"
           case 3:
              iconImage = "pin_gold"
           case 6:
              iconImage = "pin_you"
           default:
              iconImage = "pin_silver"
           }
           marker.icon = UIImage(named:iconImage)
           marker.map = mapView

       }

    }
}


问:
Import Errror for python pg module
I am having trouble using the pg module in my code. I've installed it using pip. But when I go to run it I get the following error:</p>

```<code>Traceback (most recent call last):
  File "Contract_gen.py", line 2, in <module>
    import pg
  File "C:\Python27\lib\site-packages\pg\__init__.py", line 1, in <module>
    from .core import (
  File "C:\Python27\lib\site-packages\pg\core.py", line 6, in <module>
    from . import glfw
  File "C:\Python27\lib\site-packages\pg\glfw.py", line 140, in <module>
    raise ImportError("Failed to load GLFW3 shared library.")
ImportError: Failed to load GLFW3 shared library.
</code>```

答:
Your version of OpenGL might be too old compared to the pg requirement which is
3.1.0 as specified in
https://github.com/fogleman/pg/blob/master/requirements.txt

You can re install python-openGL with pip:

```<code>$ pip install PyOpenGL PyOpenGL_accelerate
</code>```

This removes this problem but creates other errors for me.

note, besides, that this problem seems to be mentioned in
https://github.com/fogleman/pg/issues

Title: Import Errror for python pg module

Body:
I am having trouble using the pg module in my code. I've installed it using pip. But when I go to run it I get the following error:

Traceback (most recent call last):
  File "Contract_gen.py", line 2, in <module>
    import pg
  File "C:\Python27\lib\site-packages\pg\__init__.py", line 1, in <module>
    from .core import (
  File "C:\Python27\lib\site-packages\pg\core.py", line 6, in <module>
    from . import glfw
  File "C:\Python27\lib\site-packages\pg\glfw.py", line 140, in <module>
    raise ImportError("Failed to load GLFW3 shared library.")
ImportError: Failed to load GLFW3 shared library.

Body:
Your version of OpenGL might be too old compared to the pg requirement which is
3.1.0 as specified in
https://github.com/fogleman/pg/blob/master/requirements.txt

You can re install python-openGL with pip:

$ pip install PyOpenGL PyOpenGL_accelerate

This removes this problem but creates other errors for me.

note, besides, that this problem seems to be mentioned in
https://github.com/fogleman/pg/issues


问:
php oop, class structure with many class
how in one class use another class?
My code is correct?</p>

```<code><?php
class Country{
    function countryById($id)   {
        echo $id;
    }

}
class Validate{
    function text($id)  {
        return true;
    }

}
class Register{

    function write($name, $url, $country){
        $val = new Validate();
        $c_id = new Country();

        if(!$val->text($name))
          return false;

        $country_id = $c_id->countryById($country);
        }
}

$r = new Register();
$r->write('test', 'www.google.com', 'france');
?>
</code>```

答:
almost.
except $val = new Validate;
right syntax is $val = new Validate();
and include function expects string literal or variable (include ('class/myclass.php'))</p>

Body:
how in one class use another class?
My code is correct?

<?php
class Country{
    function countryById($id)   {
        echo $id;
    }

}
class Validate{
    function text($id)  {
        return true;
    }

}
class Register{

    function write($name, $url, $country){
        $val = new Validate();
        $c_id = new Country();

        if(!$val->text($name))
          return false;

        $country_id = $c_id->countryById($country);
        }
}

$r = new Register();
$r->write('test', 'www.google.com', 'france');
?>


问:
How to check if a string contains a number in powershell
How do I check if a string contains any numeric value.

Ex: paul123

The above example contains numeric value so I should get the output as true.

答:
Use a regular expression match:

```<code>'paul123' -match '\d'
</code>```

\d matches a digit (0-9), so the expression will evaluate to true if the string contains at least one digit.

Body:
Use a regular expression match:

'paul123' -match '\d'

\d matches a digit (0-9), so the expression will evaluate to true if the string contains at least one digit.


问:
React Native - Detect when view goes offscreen Flatlist
I have a Flatlist element that renders a collection of Views that could be Images or Videos, similar to a Facebook feed. Is there any way to detect when a View will disappear from screen so I could stop automatic playback of video elements?

Currently my Flatlist component has a scrollHandler attached that detects the offset of the content and calculates the view number.

```<code>scrollHandler(event){

    let postHeight = 200;
    var currentOffset = Number(event.nativeEvent.contentOffset.y);

    this.offsetActual=currentOffset;
    this.velOffset=currentOffset-this.prevOffset;
    this.prevOffset=currentOffset;

    let postNumber=(currentOffset/postHeight);
    // Any additional logic
}
</code>```

Could there be something like UITableViewCell will disappear but for the Flatlist elements? Or any other handler where I could attach "will disappear" logic?

Thank you for your help!

答: You need to make use of onViewableItemsChanged prop. This way you'll know which items are visible at the moment. </p>

Body:
I have a Flatlist element that renders a collection of Views that could be Images or Videos, similar to a Facebook feed. Is there any way to detect when a View will disappear from screen so I could stop automatic playback of video elements?

Currently my Flatlist component has a scrollHandler attached that detects the offset of the content and calculates the view number.

scrollHandler(event){

    let postHeight = 200;
    var currentOffset = Number(event.nativeEvent.contentOffset.y);

    this.offsetActual=currentOffset;
    this.velOffset=currentOffset-this.prevOffset;
    this.prevOffset=currentOffset;

    let postNumber=(currentOffset/postHeight);
    // Any additional logic
}

Could there be something like UITableViewCell will disappear but for the Flatlist elements? Or any other handler where I could attach "will disappear" logic?

Thank you for your help!


问:
babel webpack configuration ignored in karma.conf.js?
I am trying to make my first JS unit test with Karma and Jasmin. I am testing a react app.

I generated the karma config with "karma init" and modified it, see below for the karma.config.js
The webpack.config is required in the karma.config.js, but the babel loader is completely ignored, why?
I noticed it's ignored as it resulted in errors of undefined variable, etc...
When adding parts of the webpack.config.js directly in the karma.config.js (copy/paste), it works, but that is not what I want as I am duplicating code like my loaders and aliases, etc... How to solve this? See below also the webpack.config.js

The karma.config.js:

```<code>module.exports = function (config) {
    config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: 'src/js/',
        frameworks: ['jasmine'],
        files: [
            'tests/*.test.js',
        ],
        preprocessors: {
            '**/tests/*.test.js': ['webpack', 'sourcemap'],
        },

        webpack: require("../webpack.conf.js"),
        webpackMiddleware: {
            stats: "errors-only"
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['PhantomJS'],
        phantomJsLauncher: {exitOnResourceError: true},
        singleRun: false,
        concurrency: Infinity
    })
};
</code>```

The webpack.config.js:

```<code>module.exports = function (env) {
    if (env !== undefined) {
        let analyse = !!env.analyse;
        console.log("Analyse?: " + analyse);
        if (analyse) {
            plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'}));
        }
    }

    return {
        entry: {
            entry: ['./src/entry.js', './src/js/utils.js'],
        },
        devtool: devTool,
        devServer: devServer,
        output: {
            path: __dirname + '/dist',
            filename: '[name]-[hash].cache.js', // it contains the name ".cache", that is used in the webserver config.
            sourceMapFilename: '[name]-[hash].cache.js.map',
        },
        module: {
            rules: [
                { // The Babel loader:
                    test: /(\.jsx|\.js)$/,
                    exclude: /(node_modules|bower_components)/,
                    use: [{
                        loader: 'babel-loader',
                        options: {
                            presets: ['babel-preset-es2015', 'babel-preset-react'].map(require.resolve),
                            plugins: ['babel-plugin-transform-react-jsx-img-import'].map(require.resolve) // It will convert the used images to to "require" statements such that it's used by a loader below.
                        }
                    }]
                },
                {
                    test: /\.s?css$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                },
                {
                    test: /\.(png|gif|jpe?g)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'resources/images/[name]-[hash]-cache.[ext]'
                        }
                    }]
                },
                {
                    test: /\.(otf|svg|eot|ttf|woff2?)(\?.*$|$)/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'resources/fonts/[name]-[hash]-cache.[ext]'
                        }
                    }]
                },
            ]
        },
        plugins: plugins,
        externals: ['axios'],
        resolve: {
            alias: {
                // Ref: https://webpack.js.org/configuration/resolve/
                Context: path.resolve(__dirname, 'src/js/context'),
                Utils: path.resolve(__dirname, 'src/js/utils'),
                ....etc...
            },
        }
    };
};
</code>```

答:
in karma.config.js:

```<code>webpack: require("../webpack.conf.js")
</code>```

you're giving "webpack" a function instead of an object. you should immediately invoke it (with or without an env param) require("../webpack.conf.js")()

Body:
I am trying to make my first JS unit test with Karma and Jasmin. I am testing a react app.

I generated the karma config with "karma init" and modified it, see below for the karma.config.js
The webpack.config is required in the karma.config.js, but the babel loader is completely ignored, why?
I noticed it's ignored as it resulted in errors of undefined variable, etc...
When adding parts of the webpack.config.js directly in the karma.config.js (copy/paste), it works, but that is not what I want as I am duplicating code like my loaders and aliases, etc... How to solve this? See below also the webpack.config.js

The karma.config.js:

module.exports = function (config) {
    config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: 'src/js/',
        frameworks: ['jasmine'],
        files: [
            'tests/*.test.js',
        ],
        preprocessors: {
            '**/tests/*.test.js': ['webpack', 'sourcemap'],
        },

        webpack: require("../webpack.conf.js"),
        webpackMiddleware: {
            stats: "errors-only"
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['PhantomJS'],
        phantomJsLauncher: {exitOnResourceError: true},
        singleRun: false,
        concurrency: Infinity
    })
};

The webpack.config.js:

module.exports = function (env) {
    if (env !== undefined) {
        let analyse = !!env.analyse;
        console.log("Analyse?: " + analyse);
        if (analyse) {
            plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'}));
        }
    }

    return {
        entry: {
            entry: ['./src/entry.js', './src/js/utils.js'],
        },
        devtool: devTool,
        devServer: devServer,
        output: {
            path: __dirname + '/dist',
            filename: '[name]-[hash].cache.js', // it contains the name ".cache", that is used in the webserver config.
            sourceMapFilename: '[name]-[hash].cache.js.map',
        },
        module: {
            rules: [
                { // The Babel loader:
                    test: /(\.jsx|\.js)$/,
                    exclude: /(node_modules|bower_components)/,
                    use: [{
                        loader: 'babel-loader',
                        options: {
                            presets: ['babel-preset-es2015', 'babel-preset-react'].map(require.resolve),
                            plugins: ['babel-plugin-transform-react-jsx-img-import'].map(require.resolve) // It will convert the used images to to "require" statements such that it's used by a loader below.
                        }
                    }]
                },
                {
                    test: /\.s?css$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                },
                {
                    test: /\.(png|gif|jpe?g)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'resources/images/[name]-[hash]-cache.[ext]'
                        }
                    }]
                },
                {
                    test: /\.(otf|svg|eot|ttf|woff2?)(\?.*$|$)/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'resources/fonts/[name]-[hash]-cache.[ext]'
                        }
                    }]
                },
            ]
        },
        plugins: plugins,
        externals: ['axios'],
        resolve: {
            alias: {
                // Ref: https://webpack.js.org/configuration/resolve/
                Context: path.resolve(__dirname, 'src/js/context'),
                Utils: path.resolve(__dirname, 'src/js/utils'),
                ....etc...
            },
        }
    };
};

Body:
in karma.config.js:

webpack: require("../webpack.conf.js")

you're giving "webpack" a function instead of an object. you should immediately invoke it (with or without an env param) require("../webpack.conf.js")()


问:
C# Regex.Split() does not work as expected
I'm trying out services in C#, so I cannot debug values using Console.WriteLine(...). That's why I don't know what is in my variable number at the end :

```<code>    public int addAndSoustractNumberFromAString(string ustr)
    {
        int result = 0;

        if(!string.IsNullOrEmpty(str))
        {
            string str = ustr.Trim();

            //Regexes
            System.Text.RegularExpressions.Regex valid_regex = new System.Text.RegularExpressions.Regex(@"[\+]\d+|[\-]\d+");
            System.Text.RegularExpressions.Regex invalid_regex = new System.Text.RegularExpressions.Regex(@"[a-zA-Z]");

            //Handling errors
            if (invalid_regex.IsMatch(str) || !valid_regex.IsMatch(str) || !Char.IsDigit(str[str.Length - 1])) return 0;
            if (Char.IsDigit(str[0])) str = "+" + str;

            //Load all numbers in a string array
            List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

            //Cast string numbers to int + result calculation
            foreach (string number in numbers) { if (!int.TryParse(number, out int n)) return 99; result += n; }
        }

        return result;
    }
</code>```

What does my code ?
I enter additions & subtractions, it does the operations & return the result as an integer.

example :
If I enter "52-2+3" it should return 53

Problem :
My code always returns 99 wich means the parsing failed.
Just in case, I tried int.TryParse("-2", out int n) instead and it works fine.

The line not working :

List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

My regexes are fine, I tested them with the website regexstorm net.

My question is, why my string ain't split correctly using a supposed valid regex ? Is Regex.Split() not doing what I believe it does ? (I tought it would split my string into +number or -number strings

Side note : it's ok if do not start with a sign. If my string starts with a number it will add "+" at the end for regex purposes.

答:
Your Regex is not a Split()ing Regex.

Split() expects the regular expression to define the delimiter (i.e. split on a comma or semicolon).  Your regex describes the values.

It seems like you want the result of Matches() and not Split().

This seems to work for me with your example:

```<code>List<string> numbers = valid_regex.Matches(str).Cast<Match>().Select(m => m.Value).ToList();
</code>```

Also, LinqPad is a wonderful tool to prototype code snippets like this one.

Body:
I'm trying out services in C#, so I cannot debug values using Console.WriteLine(...). That's why I don't know what is in my variable number at the end :

    public int addAndSoustractNumberFromAString(string ustr)
    {
        int result = 0;

        if(!string.IsNullOrEmpty(str))
        {
            string str = ustr.Trim();

            //Regexes
            System.Text.RegularExpressions.Regex valid_regex = new System.Text.RegularExpressions.Regex(@"[\+]\d+|[\-]\d+");
            System.Text.RegularExpressions.Regex invalid_regex = new System.Text.RegularExpressions.Regex(@"[a-zA-Z]");

            //Handling errors
            if (invalid_regex.IsMatch(str) || !valid_regex.IsMatch(str) || !Char.IsDigit(str[str.Length - 1])) return 0;
            if (Char.IsDigit(str[0])) str = "+" + str;

            //Load all numbers in a string array
            List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

            //Cast string numbers to int + result calculation
            foreach (string number in numbers) { if (!int.TryParse(number, out int n)) return 99; result += n; }
        }

        return result;
    }

What does my code ?
I enter additions & subtractions, it does the operations & return the result as an integer.

example :
If I enter "52-2+3" it should return 53

Problem :
My code always returns 99 wich means the parsing failed.
Just in case, I tried int.TryParse("-2", out int n) instead and it works fine.

The line not working :

List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

My regexes are fine, I tested them with the website regexstorm net.

My question is, why my string ain't split correctly using a supposed valid regex ? Is Regex.Split() not doing what I believe it does ? (I tought it would split my string into +number or -number strings

Side note : it's ok if do not start with a sign. If my string starts with a number it will add "+" at the end for regex purposes.

Body:
Your Regex is not a Split()ing Regex.

Split() expects the regular expression to define the delimiter (i.e. split on a comma or semicolon).  Your regex describes the values.

It seems like you want the result of Matches() and not Split().

This seems to work for me with your example:

List<string> numbers = valid_regex.Matches(str).Cast<Match>().Select(m => m.Value).ToList();

Also, LinqPad is a wonderful tool to prototype code snippets like this one.


问:
Use csscomb for VS Code
I'm trying VS Code for a few days and I've installed csscomb extension. It works fine when I put .csscomb.json on my work directory.
But I wish it worked even on file I open outside of my work directory.

Could you tell me how to configure VS Code and/or csscomb to work like this?
I use Windows 10 Pro.

答:
According to the csscomb page on VS Code's Marketplace...

They have "Supported settings"

csscomb.preset

Type: Object or String

Defaut: {}

Config's name. Should be one of the
  following: csscomb, zen, yandex or an object containing custom
  configuration or path to config.

And the following warning:

Warning!

If you want to specify a file in the current directory, the path must
  begin with a ./ or ../ if relative to the current directory. Also you
  can use HOME directory as ~ symbol.

In other words, since there is no default, you have to set either a preset config or path to a custom config.

To configure csscomb in VS Code:

Go to File > Preferences > Settings

Select the "User Settings" tab in the right window (to apply the config globally)

Expand the options for "CSScomb configuration"

Click the pencil to the left of "csscomb.preset"

Click "Copy to Settings"

Enter the path to your custom config or choose a preset

```<code>{
    "csscomb.preset": "~/.vscode/.csscomb.json"
}
</code>```

OR one of ("csscomb", "zen", "yandex")

```<code>{
    "csscomb.preset": "csscomb"
}
</code>```

Next, you need to create the .csscomb.json file in that location. I chose the C:\Users\username\.vscode directory because that's where VS Code also downloads extensions on Windows.

Here's the config I created using csscomb's config generator:

```<code>{
    "always-semicolon": true,
    "color-case": "upper",
    "block-indent": "    ",
    "color-shorthand": true,
    "element-case": "lower",
    "eof-newline": false,
    "leading-zero": false,
    "quotes": "double",
    "sort-order-fallback": "abc",
    "space-before-colon": "",
    "space-after-colon": " ",
    "space-before-combinator": " ",
    "space-after-combinator": " ",
    "space-between-declarations": "\n",
    "space-before-opening-brace": " ",
    "space-after-opening-brace": "\n",
    "space-after-selector-delimiter": " ",
    "space-before-selector-delimiter": "",
    "space-before-closing-brace": "\n",
    "strip-spaces": true,
    "tab-size": true,
    "vendor-prefix-align": true
}
</code>```

You can also include an option for sorting tags (or copy it from one of their presets on git):

```<code>{
    "sort-order": [
        [
            "font",
            "font-family",
            "font-size",
            "font-weight",
            "font-style"
        ],
        [
            "position",
            "z-index"
        ]
    ]
}
</code>```

Now you should be able to format CSS within VS Code by typing ctrl+shift+p then typing "CSScomb" then enter.

"Formatter" extensions are supposed to be recognized by the default formatting keyboard shortcut shift+alt+f, however I haven't gotten that to work. I think it's something the developer has to configure.

Instead, you can create your own keyboard shortcut in VS Code:

Go to File > Preferences > Keyboard Shortcuts

Click the link at the top to edit keybindings.json

Add your custom keybinding

```<code>{
    "key": "ctrl+shift+c",
    "command": "csscomb.execute"
}
</code>```

Now you should be all set!

Title: Use csscomb for VS Code

Body:
According to the csscomb page on VS Code's Marketplace...

They have "Supported settings"

csscomb.preset

Type: Object or String

Defaut: {}

Config's name. Should be one of the
  following: csscomb, zen, yandex or an object containing custom
  configuration or path to config.

And the following warning:

Warning!

If you want to specify a file in the current directory, the path must
  begin with a ./ or ../ if relative to the current directory. Also you
  can use HOME directory as ~ symbol.

In other words, since there is no default, you have to set either a preset config or path to a custom config.

To configure csscomb in VS Code:

Go to File > Preferences > Settings

Select the "User Settings" tab in the right window (to apply the config globally)

Expand the options for "CSScomb configuration"

Click the pencil to the left of "csscomb.preset"

Click "Copy to Settings"

Enter the path to your custom config or choose a preset

{
    "csscomb.preset": "~/.vscode/.csscomb.json"
}

OR one of ("csscomb", "zen", "yandex")

{
    "csscomb.preset": "csscomb"
}

Next, you need to create the .csscomb.json file in that location. I chose the C:\Users\username\.vscode directory because that's where VS Code also downloads extensions on Windows.

Here's the config I created using csscomb's config generator:

{
    "always-semicolon": true,
    "color-case": "upper",
    "block-indent": "    ",
    "color-shorthand": true,
    "element-case": "lower",
    "eof-newline": false,
    "leading-zero": false,
    "quotes": "double",
    "sort-order-fallback": "abc",
    "space-before-colon": "",
    "space-after-colon": " ",
    "space-before-combinator": " ",
    "space-after-combinator": " ",
    "space-between-declarations": "\n",
    "space-before-opening-brace": " ",
    "space-after-opening-brace": "\n",
    "space-after-selector-delimiter": " ",
    "space-before-selector-delimiter": "",
    "space-before-closing-brace": "\n",
    "strip-spaces": true,
    "tab-size": true,
    "vendor-prefix-align": true
}

You can also include an option for sorting tags (or copy it from one of their presets on git):

{
    "sort-order": [
        [
            "font",
            "font-family",
            "font-size",
            "font-weight",
            "font-style"
        ],
        [
            "position",
            "z-index"
        ]
    ]
}

Now you should be able to format CSS within VS Code by typing ctrl+shift+p then typing "CSScomb" then enter.

"Formatter" extensions are supposed to be recognized by the default formatting keyboard shortcut shift+alt+f, however I haven't gotten that to work. I think it's something the developer has to configure.

Instead, you can create your own keyboard shortcut in VS Code:

Go to File > Preferences > Keyboard Shortcuts

Click the link at the top to edit keybindings.json

Add your custom keybinding

{
    "key": "ctrl+shift+c",
    "command": "csscomb.execute"
}

Now you should be all set!


问:
Unexpected token }
I have a script to open a model window.. Chrome gives me "Uncaught SyntaxError: Unexpected token }" on a line that doesn't even have a closing curly brace.

Here is the portion of the script that has the error:

```<code>function showm(id1){
  window.onscroll=function(){document.getElementById(id1).style.top=document.body.scrollTop;};
  document.getElementById(id1).style.display="block";
  document.getElementById(id1).style.top=document.body.scrollTop;
}
</code>```

Does anybody have any ideas on this? Any help is appreciated.

答:
You have endless loop in place:

```<code>function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}
</code>```

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

Title: Unexpected token }

Body:
I have a script to open a model window.. Chrome gives me "Uncaught SyntaxError: Unexpected token }" on a line that doesn't even have a closing curly brace.

Here is the portion of the script that has the error:

function showm(id1){
  window.onscroll=function(){document.getElementById(id1).style.top=document.body.scrollTop;};
  document.getElementById(id1).style.display="block";
  document.getElementById(id1).style.top=document.body.scrollTop;
}

Does anybody have any ideas on this? Any help is appreciated.

Body:
You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.


问:
How do I create a dynamic array of arrays (of arrays)?
I'm trying to create a dynamic array of arrays (of arrays). But for some reason the data gets corrupted. I'm using the data to generate a texture in a OpenGL application.

The following code works fine:

```<code>unsigned char imageData[64][64][3];
    for (int i = 0; i < 64; i++)
    {
        for (int j = 0; j < 64; j++)
        {
            unsigned char r = 0, g = 0, b = 0;
            if (i < 32)
            {
                if (j < 32)
                    r = 255;
                else
                    b = 255;
            }
            else
            {
                if (j < 32)
                    g = 255;
            }
            imageData[i][j][0] = r;
            imageData[i][j][1] = g;
            imageData[i][j][2] = b;
        }
        std::cout << std::endl;
    }

    glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
</code>```

Problem is, I want to be able to create a texture of any size (not just 64*64). So I'm trying this:

```<code>unsigned char*** imageData = new unsigned char**[64]();
for (int i = 0; i < 64; i++)
{
    imageData[i] = new unsigned char*[64]();
    for (int j = 0; j < 64; j++)
    {
        imageData[i][j] = new unsigned char[3]();
        unsigned char r = 0, g = 0, b = 0;
        if (i < 32)
        {
            if (j < 32)
                r = 255;
            else
                b = 255;
        }
        else
        {
            if (j < 32)
                g = 255;
        }
        imageData[i][j][0] = r;
        imageData[i][j][1] = g;
        imageData[i][j][2] = b;
    }
    std::cout << std::endl;
}

glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
</code>```

But that doesn't work, the image gets all messed up so I assume I'm creating the array of arrays (of arrays) incorrectly? What am I doing wrong?

Also, I guess I should be using vectors instead. But how can I cast the vector of vectors of vectors data into a (void *) ?

答:
This line contains multiple bugs:

```<code>unsigned char* pixel = &(imageData[(y * height) + x]);
</code>```

You should multiply x by height and add y. And there's also the fact that each pixel is actually 3 bytes. Some issues that led to this bug in your code (and will lead to to others)

You should also be using std::vector. You can call std::vector::data to get a pointer to the underlying data to interface to C API's.

You should have a class that represents a pixel. This will handle the offsetting correctly and give things names and made the code clearer.

Whenever you are working with a multi dimensional array that you encode into a single dimensional one, you should try to carefully write an access function that takes care of indexing so you can test it separately.

(end bulleted list... oh SO).

```<code>struct Pixel {
    unsigned char red;
    unsigned char blue;
    unsigned char green;
};

struct TwoDimPixelArray {
    TwoDimArray(int width, int height)
      : m_width(width), m_height(height)
    {
        m_vector.resize(m_width * m_height);
    }

    Pixel& get(int x, int y) {
        return m_vector[x*height + y];
    }

    Pixel* data() { return m_vector.data(); }

private:
    int m_width;
    int m_height;
    std::vector<Pixel> m_vector;
}

int width = 64;
int height = 64;

TwoDimPixelArray imageData(width, height);

for (int x = 0; x != width ; ++ x) {
    for (int y = 0; y != height ; ++y) {
        auto& pixel = imageData.get(x, y);

        // ... pixel.red = something, pixel.blue = something, etc
    }
}

glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData.data());
</code>```

Body:
I'm trying to create a dynamic array of arrays (of arrays). But for some reason the data gets corrupted. I'm using the data to generate a texture in a OpenGL application.

The following code works fine:

unsigned char imageData[64][64][3];
    for (int i = 0; i < 64; i++)
    {
        for (int j = 0; j < 64; j++)
        {
            unsigned char r = 0, g = 0, b = 0;
            if (i < 32)
            {
                if (j < 32)
                    r = 255;
                else
                    b = 255;
            }
            else
            {
                if (j < 32)
                    g = 255;
            }
            imageData[i][j][0] = r;
            imageData[i][j][1] = g;
            imageData[i][j][2] = b;
        }
        std::cout << std::endl;
    }

    glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

Problem is, I want to be able to create a texture of any size (not just 64*64). So I'm trying this:

unsigned char*** imageData = new unsigned char**[64]();
for (int i = 0; i < 64; i++)
{
    imageData[i] = new unsigned char*[64]();
    for (int j = 0; j < 64; j++)
    {
        imageData[i][j] = new unsigned char[3]();
        unsigned char r = 0, g = 0, b = 0;
        if (i < 32)
        {
            if (j < 32)
                r = 255;
            else
                b = 255;
        }
        else
        {
            if (j < 32)
                g = 255;
        }
        imageData[i][j][0] = r;
        imageData[i][j][1] = g;
        imageData[i][j][2] = b;
    }
    std::cout << std::endl;
}

glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);

But that doesn't work, the image gets all messed up so I assume I'm creating the array of arrays (of arrays) incorrectly? What am I doing wrong?

Also, I guess I should be using vectors instead. But how can I cast the vector of vectors of vectors data into a (void *) ?

Body:
This line contains multiple bugs:

unsigned char* pixel = &(imageData[(y * height) + x]);

You should multiply x by height and add y. And there's also the fact that each pixel is actually 3 bytes. Some issues that led to this bug in your code (and will lead to to others)

You should also be using std::vector. You can call std::vector::data to get a pointer to the underlying data to interface to C API's.

You should have a class that represents a pixel. This will handle the offsetting correctly and give things names and made the code clearer.

Whenever you are working with a multi dimensional array that you encode into a single dimensional one, you should try to carefully write an access function that takes care of indexing so you can test it separately.

(end bulleted list... oh SO).

struct Pixel {
    unsigned char red;
    unsigned char blue;
    unsigned char green;
};

struct TwoDimPixelArray {
    TwoDimArray(int width, int height)
      : m_width(width), m_height(height)
    {
        m_vector.resize(m_width * m_height);
    }

    Pixel& get(int x, int y) {
        return m_vector[x*height + y];
    }

    Pixel* data() { return m_vector.data(); }

private:
    int m_width;
    int m_height;
    std::vector<Pixel> m_vector;
}

int width = 64;
int height = 64;

TwoDimPixelArray imageData(width, height);

for (int x = 0; x != width ; ++ x) {
    for (int y = 0; y != height ; ++y) {
        auto& pixel = imageData.get(x, y);

        // ... pixel.red = something, pixel.blue = something, etc
    }
}

glTexImage2D(target, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData.data());


问:
How convert string with underscore to unicode?
I try to create array with string elements in python.

```<code> a = array('u',["sub_id","datetime"])
</code>```

Python show TypeError: array item must be unicode character

Reason of create array is to send it with request. I use rest API with JSON of some product and send request, but It says this param is must be a array.(tuple and list don't suit)

I use python 3.4.4,How can I fix this?

答:
Arrays with the type code 'u' are deprecated in Python 3, and you should rarely need to use them.

In this particular case, it seems like a particularly bad idea, because arrays of Unicode characters are arrays of characters, not arrays of strings. You cannot create one which is an array of multiple Unicode strings. If the API you’re using wants a list of multiple strings, then it does not want you to use a Python array.

What JSON calls an “array” is very similar to what Python calls a “list”. What you actually should be doing is creating a Python list of all your strings, like ["sub_id","datetime"], and then using Python’s json module to encode the Python list into a JSON document containing an array.

Body:
I try to create array with string elements in python.

 a = array('u',["sub_id","datetime"])

Python show TypeError: array item must be unicode character

Reason of create array is to send it with request. I use rest API with JSON of some product and send request, but It says this param is must be a array.(tuple and list don't suit)

I use python 3.4.4,How can I fix this?