问:
http.ResponseWriter.Write with interface{}
I'm running a SQL query using the sample from denisenkom but coupled with a http.ResponseWriterand I'm struggling with interface{} type conversion. There are a few posts that are close to what I'm doing but the solution seems kind of heavy handed and always use fmt (which I'm not using).

Note that my query works and returns a result. I'm just trying to display that result.

Here is my code that I think is relatively close but doesn't work. I've tried a couple other things but none even compile.

```<code>vals := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
        vals[i] = new(interface{})
        if i != 0 {
                w.Write([]byte("\t"))
        }
        w.Write([]byte(cols[i]))
}

for rows.Next() {
      err = rows.Scan(vals...)
      if err != nil {
          w.Write([]byte("Row problem: " + err.Error()))
          continue
      }
      for i := 0; i < len(vals); i++ {
          if i != 0 {
              w.Write([]byte("\t"))
          }

      //THIS IS THE PART I'M STUCK ON
      switch v := vals[i].(type) {
      case int:
           w.Write([]byte("int!\n" + string(v)))
      case int8:
           w.Write([]byte("int8!\n" + string(v)))

      //etc, etc
      //more types
      //etc, etc

      case float64:
           w.Write([]byte("float64!\n" + string(v))) //This fails, can't convert, will need something else
      case string:
           w.Write([]byte("string!\n" + v))
      default:
           w.Write([]byte("something else!\n"))
      }
  }

}
</code>```

But isn't there a better way to dynamically check the underlying type and convert it to something readable? All I want to do is spit out the results of a query, this seems like I'm doing something wrong.

Note that it always hits the default case, even when it's explicitly the same type.

答:
The example at denisekom prints to stdout using the fmt.Print family of functions.  Change the example to print to a response writer by using the fmt.Fprint family of functions.

The fmt.Fprint functions write to the io.Writer specified as the first argument.  The response writer satisfies the io.Writer interface.  Here's the modified code from the original example where w is the http.ResponseWriter.

```<code>vals := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
    vals[i] = new(interface{})
    if i != 0 {
        fmt.Fprint(w, "\t")
    }
    fmt.Fprint(w, cols[i])
}
fmt.Fprintln(w)
for rows.Next() {
    err = rows.Scan(vals...)
    if err != nil {
        fmt.Fprintln(w, err)
        continue
    }
    for i := 0; i < len(vals); i++ {
        if i != 0 {
            fmt.Fprint(w, "\t")
        }
        printValue(w, vals[i].(*interface{}))
    }
    fmt.Fprintln(w)

}

...

func printValue(w io.Writer, pval *interface{}) {
    switch v := (*pval).(type) {
    case nil:
        fmt.Fprint(w, "NULL")
    case bool:
        if v {
            fmt.Fprint(w, "1")
        } else {
            fmt.Fprint(w, "0")
        }
    case []byte:
        fmt.Fprint(w, string(v))
    case time.Time:
        fmt.Fprint(w, v.Format("2006-01-02 15:04:05.999"))
    default:
        fmt.Fprint(w, v)
    }
}
</code>```

Regarding the code in the question: the expression string(v) is a string conversion. A string conversion does not convert numbers to a decimal representation as the code is assuming.  See the spec for details on string conversions.  Use either the fmt package as above or the strconv package to convert numbers to decimal strings.  The type switch should be switch v := (*(vals[i].(*interface{})).(type) {.  That's a bit of mess, and that leads to my next point.

The original example uses more indirection than needed. Here's a simplified version ready to be called with a response writer:

```<code>func exec(w io.Writer, db *sql.DB, cmd string) error {
    rows, err := db.Query(cmd)
    if err != nil {
        return err
    }
    defer rows.Close()
    cols, err := rows.Columns()
    if err != nil {
        return err
    }
    if cols == nil {
        return nil
    }
    vals := make([]interface{}, len(cols))
    args := make([]interface{}, len(cols))
    for i := 0; i < len(cols); i++ {
        args[i] = &vals[i]
        if i != 0 {
            fmt.Fprint(w, "\t")
        }
        fmt.Fprint(w, cols[i])
    }
    for rows.Next() {
        err = rows.Scan(args...)
        if err != nil {
            fmt.Fprintln(w, err)
            continue
        }
        for i := 0; i < len(vals); i++ {
            if i != 0 {
                fmt.Print("\t")
            }
            printValue(w, vals[i])
        }
        fmt.Fprintln(w)

    }
    if rows.Err() != nil {
        return rows.Err()
    }
    return nil
}

func printValue(w io.Writer, v interface{}) {
    switch v := v.(type) {
    case nil:
        fmt.Fprint(w, "NULL")
    case bool:
        if v {
            fmt.Fprint(w, "1")
        } else {
            fmt.Fprint(w, "0")
        }
    case []byte:
        fmt.Fprint(w, string(v))
    case time.Time:
        fmt.Fprint(w, v.Format("2006-01-02 15:04:05.999"))
    default:
        fmt.Fprint(w, v)
    }
}
</code>```

Body:
I'm running a SQL query using the sample from denisenkom but coupled with a http.ResponseWriterand I'm struggling with interface{} type conversion. There are a few posts that are close to what I'm doing but the solution seems kind of heavy handed and always use fmt (which I'm not using).

Note that my query works and returns a result. I'm just trying to display that result.

Here is my code that I think is relatively close but doesn't work. I've tried a couple other things but none even compile.

vals := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
        vals[i] = new(interface{})
        if i != 0 {
                w.Write([]byte("\t"))
        }
        w.Write([]byte(cols[i]))
}

for rows.Next() {
      err = rows.Scan(vals...)
      if err != nil {
          w.Write([]byte("Row problem: " + err.Error()))
          continue
      }
      for i := 0; i < len(vals); i++ {
          if i != 0 {
              w.Write([]byte("\t"))
          }

      //THIS IS THE PART I'M STUCK ON
      switch v := vals[i].(type) {
      case int:
           w.Write([]byte("int!\n" + string(v)))
      case int8:
           w.Write([]byte("int8!\n" + string(v)))

      //etc, etc
      //more types
      //etc, etc

      case float64:
           w.Write([]byte("float64!\n" + string(v))) //This fails, can't convert, will need something else
      case string:
           w.Write([]byte("string!\n" + v))
      default:
           w.Write([]byte("something else!\n"))
      }
  }

}

But isn't there a better way to dynamically check the underlying type and convert it to something readable? All I want to do is spit out the results of a query, this seems like I'm doing something wrong.

Note that it always hits the default case, even when it's explicitly the same type.

Body:
The example at denisekom prints to stdout using the fmt.Print family of functions.  Change the example to print to a response writer by using the fmt.Fprint family of functions.

The fmt.Fprint functions write to the io.Writer specified as the first argument.  The response writer satisfies the io.Writer interface.  Here's the modified code from the original example where w is the http.ResponseWriter.

vals := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
    vals[i] = new(interface{})
    if i != 0 {
        fmt.Fprint(w, "\t")
    }
    fmt.Fprint(w, cols[i])
}
fmt.Fprintln(w)
for rows.Next() {
    err = rows.Scan(vals...)
    if err != nil {
        fmt.Fprintln(w, err)
        continue
    }
    for i := 0; i < len(vals); i++ {
        if i != 0 {
            fmt.Fprint(w, "\t")
        }
        printValue(w, vals[i].(*interface{}))
    }
    fmt.Fprintln(w)

}

...

func printValue(w io.Writer, pval *interface{}) {
    switch v := (*pval).(type) {
    case nil:
        fmt.Fprint(w, "NULL")
    case bool:
        if v {
            fmt.Fprint(w, "1")
        } else {
            fmt.Fprint(w, "0")
        }
    case []byte:
        fmt.Fprint(w, string(v))
    case time.Time:
        fmt.Fprint(w, v.Format("2006-01-02 15:04:05.999"))
    default:
        fmt.Fprint(w, v)
    }
}

Regarding the code in the question: the expression string(v) is a string conversion. A string conversion does not convert numbers to a decimal representation as the code is assuming.  See the spec for details on string conversions.  Use either the fmt package as above or the strconv package to convert numbers to decimal strings.  The type switch should be switch v := (*(vals[i].(*interface{})).(type) {.  That's a bit of mess, and that leads to my next point.

The original example uses more indirection than needed. Here's a simplified version ready to be called with a response writer:

func exec(w io.Writer, db *sql.DB, cmd string) error {
    rows, err := db.Query(cmd)
    if err != nil {
        return err
    }
    defer rows.Close()
    cols, err := rows.Columns()
    if err != nil {
        return err
    }
    if cols == nil {
        return nil
    }
    vals := make([]interface{}, len(cols))
    args := make([]interface{}, len(cols))
    for i := 0; i < len(cols); i++ {
        args[i] = &vals[i]
        if i != 0 {
            fmt.Fprint(w, "\t")
        }
        fmt.Fprint(w, cols[i])
    }
    for rows.Next() {
        err = rows.Scan(args...)
        if err != nil {
            fmt.Fprintln(w, err)
            continue
        }
        for i := 0; i < len(vals); i++ {
            if i != 0 {
                fmt.Print("\t")
            }
            printValue(w, vals[i])
        }
        fmt.Fprintln(w)

    }
    if rows.Err() != nil {
        return rows.Err()
    }
    return nil
}

func printValue(w io.Writer, v interface{}) {
    switch v := v.(type) {
    case nil:
        fmt.Fprint(w, "NULL")
    case bool:
        if v {
            fmt.Fprint(w, "1")
        } else {
            fmt.Fprint(w, "0")
        }
    case []byte:
        fmt.Fprint(w, string(v))
    case time.Time:
        fmt.Fprint(w, v.Format("2006-01-02 15:04:05.999"))
    default:
        fmt.Fprint(w, v)
    }
}


来源: stackexchange

问:
Do iPad / iPhone Apps Get Reviewed and Approved on weekends?
Do iPad / iPhone Apps Get Reviewed and Approved on weekends?</p>

答: I believe that the answer you're looking for is "no".</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Anonymous


问:
replace single quote in middle of string using regex
Have a string:

```<code>stringName= "'john's example'"
</code>```

Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript

have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work

Help is very appreciated! :)

答: First thing is you aren't doing a regex replace, you are replacing a string which looks like /.'./ (because of the " in the first argument). Secondly, the regex you're doing is only going to be looking for a single character (.) then a single quote, then another character. What you might want to do is something like stringName.replace(/(.+)'(.+)/, "$1$2")

ContentLicense: CC BY-SA 3.0

Body:
Have a string:

stringName= "'john's example'"

Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript

have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work

Help is very appreciated! :)


问:
Which Docker images will run on Kubernetes?
How can I find out if a given Docker image can be run using Kubernetes?

What should I do to help ensure that my images will run well in any Kubernetes-managed environment?

答:
It depends on the processor architecture of the machine. If the image is compatible with the underlying hardware architecture, the K8s master node should be able to deploy the container. I had this problem when I try to deploy a Docker container on Raspberry pi 3(ARM arch. machine) with the Docker image which is built for x86-64.

For practical, try to deploy a container with the following image in X86-64 machine:

```<code>docker pull arifch2009/hello
</code>```

The error will be shown :

```<code>standard_init_linux.go:178: exec user process caused "exec format error"
</code>```

This is a simple application to print "Hello World". However, the program/application inside the image is compiled in arm architecture. So, the binary file cannot be executed in other than ARM machine.

Body:
It depends on the processor architecture of the machine. If the image is compatible with the underlying hardware architecture, the K8s master node should be able to deploy the container. I had this problem when I try to deploy a Docker container on Raspberry pi 3(ARM arch. machine) with the Docker image which is built for x86-64.

For practical, try to deploy a container with the following image in X86-64 machine:

docker pull arifch2009/hello

The error will be shown :

standard_init_linux.go:178: exec user process caused "exec format error"

This is a simple application to print "Hello World". However, the program/application inside the image is compiled in arm architecture. So, the binary file cannot be executed in other than ARM machine.


问:
How to connect interface array port to a concatenation of individual interfaces?
I have a module that has, as one of its ports, an unpacked array of an interface. I am trying to connect it to a few different singular interfaces using an assignment pattern, as I would for a simple port.

Doing so results in an error in QuestaSim:

"Expected an interface instance as an actual for 'intf_out'."

What syntactic sugar do I need get this working?

I wrote a small example that shows the issue.

```<code>interface example_interface #(
   parameter SIZE = 4
);
   logic [SIZE-1:0] example_signal;
endinterface

module example_module (
   example_interface intf_in,
   example_interface intf_out [0:2]
);
   assign intf_out[0].example_signal = intf_in.example_signal;
   assign intf_out[1].example_signal = intf_in.example_signal;
   assign intf_out[2].example_signal = intf_in.example_signal;
endmodule

module example_port_connection ();
   example_interface #(.SIZE(3)) a ();
   example_interface #(.SIZE(4)) b ();
   example_interface #(.SIZE(5)) c ();
   example_interface #(.SIZE(6)) d ();

   example_module uut (
      .intf_in(a),
      .intf_out('{b,c,d}) //error here
   );
endmodule
</code>```

答: This can't be done in SystemVerilog using interfaces. Besides not having any syntax for a concatenation of interfaces, you no longer have an array when each element is a different type. </p>

Body:
I have a module that has, as one of its ports, an unpacked array of an interface. I am trying to connect it to a few different singular interfaces using an assignment pattern, as I would for a simple port.

Doing so results in an error in QuestaSim:

"Expected an interface instance as an actual for 'intf_out'."

What syntactic sugar do I need get this working?

I wrote a small example that shows the issue.

interface example_interface #(
   parameter SIZE = 4
);
   logic [SIZE-1:0] example_signal;
endinterface

module example_module (
   example_interface intf_in,
   example_interface intf_out [0:2]
);
   assign intf_out[0].example_signal = intf_in.example_signal;
   assign intf_out[1].example_signal = intf_in.example_signal;
   assign intf_out[2].example_signal = intf_in.example_signal;
endmodule

module example_port_connection ();
   example_interface #(.SIZE(3)) a ();
   example_interface #(.SIZE(4)) b ();
   example_interface #(.SIZE(5)) c ();
   example_interface #(.SIZE(6)) d ();

   example_module uut (
      .intf_in(a),
      .intf_out('{b,c,d}) //error here
   );
endmodule


问:
Maximum Value From List with Dictionary
I'm trying to get the dictionary with the biggest value in the key
'points'.

So, I have the following list and I'm trying to create a function where the output will be the item from the list (in this case a dictionary) with the biggest value in the key points).

```<code>[ {"name":"John","points":4} , {"name": "Michael", "points":10} ]
</code>```

I want the output to be:

```<code>{"name": "Michael", "points":10}
</code>```

I 'm not posting any code because I have no idea of how to do this.

Thank you for the help!

答:
Try the following:

```<code>max(scores, key=lambda item: item['points'])
</code>```

```<code>>>> scores = [ {"name":"John","points":4} , {"name": "Michael", "points":10} ]
>>> max(scores, key=lambda item: item['points'])
{'points': 10, 'name': 'Michael'}
>>>
</code>```

Title: Maximum Value From List with Dictionary

Body:
I'm trying to get the dictionary with the biggest value in the key
'points'.

So, I have the following list and I'm trying to create a function where the output will be the item from the list (in this case a dictionary) with the biggest value in the key points).

[ {"name":"John","points":4} , {"name": "Michael", "points":10} ]

I want the output to be:

{"name": "Michael", "points":10}

I 'm not posting any code because I have no idea of how to do this.

Thank you for the help!

Body:
Try the following:

max(scores, key=lambda item: item['points'])

>>> scores = [ {"name":"John","points":4} , {"name": "Michael", "points":10} ]
>>> max(scores, key=lambda item: item['points'])
{'points': 10, 'name': 'Michael'}
>>>


答:
```<code>select number,
       min(case when `type` = 'A' then price end) as A,
       min(case when `type` = 'B' then price end) as B
from your_table
group by number
</code>```

Title: Can I group_by then separate into columns

Body:
+---------+-------+----------+
| number  | type  |   price  |
+---------+-------+----------+
|    1    |   A   |   7.00   |
|    1    |   B   |   3.00   |
|    2    |   A   |   1.00   |
|    2    |   B   |   2.00   |
|    3    |   A   |   6.00   |
|    3    |   B   |   9.00   |
+---------+-------+----------+

If I have a table like the example table above. Is it possible to run a query that would a result in a table like the below example in mysql?

+---------+---------+----------+
| number  |    A    |     B    |
+---------+---------+----------+
|    1    |   7.00  |   3.00   |
|    2    |   1.00  |   2.00   |
|    3    |   6.00  |   9.00   |
+---------+---------+----------+


问:
Observing changes in visibleCells array of UICollectionView
I would like to know when the count of visibleCells property of UICollectionView changes.
I know that I can observe objects that inherit from NSObject as long as the property I want to observe is dynamic. For example:

```<code>let view = UIView()
view.observe(\.isHidden, options: .new) { view, change in
  print(change.newValue)
}
</code>```

How can I observe visibleCells of UICollectionView in a similar manner?

答: I'm not so sure that KVO is going to help you here.  However collectionView does  have the delegate methods collectionView(:willDisplay:forItemAt:) and collectionView(:didEndDisplaying:forItemAt:) which you can use to infer changes in the visible cells.  You could also check in scrollViewDidScroll(_:)

Body:
I would like to know when the count of visibleCells property of UICollectionView changes.
I know that I can observe objects that inherit from NSObject as long as the property I want to observe is dynamic. For example:

let view = UIView()
view.observe(\.isHidden, options: .new) { view, change in
  print(change.newValue)
}

How can I observe visibleCells of UICollectionView in a similar manner?


答: I uploaded several builds on weekends and my experience is that no build ever got reviewed on weekends. So I'm quite confident to say: Unfortunately no.

Title: Do iPad / iPhone Apps Get Reviewed and Approved on weekends?


问:
Can I put this statement in the for loop?
```<code>for (int i = 0; i < numArray.size(); i++) {
    if (numArray.get(i) % 2 == 0) {
        evenSum += numArray.get(i);
        outputArea.append(numArray.get(i) + "\n");
    }
}
</code>```

Is there any way to get the line

```<code>if (numArray.get(i) % 2 == 0) {
</code>```

in the for loop condition line? And if so, would that be more efficient than how it is right now?

答:
I presume you are summing even numbers in the ArrayList, you asked for more efficiency so here you go, instead of using .get() we will use iterator as it will speed things up and we will use another faster method for checking if number is even:

```<code>package com.company;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Main {

    public static void main(String[] args) throws InterruptedException {

     int sum = 0;
     List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));

     Iterator<Integer> iter = numbers.iterator();
     int num;

     while(iter.hasNext()){
         if (((num = iter.next()) & 1) == 0) // number is even
             sum += num;
     }

        System.out.println("Sum of all even numbers is: " + sum);

    }

}
</code>```

If you had a really big list it would speed things up quite a bit compared to the original code.

EDIT:

Here are resources that you can study:

http://www.javainterviewpoint.com/check-number-even-odd-modulo-division-operators-java/

Iterator vs for

Body:
for (int i = 0; i < numArray.size(); i++) {
    if (numArray.get(i) % 2 == 0) {
        evenSum += numArray.get(i);
        outputArea.append(numArray.get(i) + "\n");
    }
}

Is there any way to get the line

if (numArray.get(i) % 2 == 0) {

in the for loop condition line? And if so, would that be more efficient than how it is right now?

Body:
I presume you are summing even numbers in the ArrayList, you asked for more efficiency so here you go, instead of using .get() we will use iterator as it will speed things up and we will use another faster method for checking if number is even:

package com.company;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Main {

    public static void main(String[] args) throws InterruptedException {

     int sum = 0;
     List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));

     Iterator<Integer> iter = numbers.iterator();
     int num;

     while(iter.hasNext()){
         if (((num = iter.next()) & 1) == 0) // number is even
             sum += num;
     }

        System.out.println("Sum of all even numbers is: " + sum);

    }

}

If you had a really big list it would speed things up quite a bit compared to the original code.

EDIT:

Here are resources that you can study:

http://www.javainterviewpoint.com/check-number-even-odd-modulo-division-operators-java/

Iterator vs for


问:
Unsupported config option for services.volumes
Trying to setup docker for the first time and I'm running into a problem with volumes. I feel pretty confident that the spacing and formatting in the .yml is correct at this point.

I've tried versions 3, 3.1, 3.2, 3.3 and 3.4. All are getting the same error message (below)

Unsupported config option for services.volumes: 'db2_prod'

```<code>version: '3'

services:
   liberty:
     image: liberty:${liberty_tag}
     ports:
       - "${liberty_ip}:9080:9080"
       - "${liberty_ip}:9443:9443"
     restart: always

   apache:
     image: webapp:${apache_tag}
     ports:
       - "${apache_ip}:80:80"
       - "${apache_ip}:443:443"
     restart: always

   db2:
     image: db2:${db2_tag}
     ports:
       - "${db2_ip}:50000:50000"
     stdin_open: true
     tty: true
     restart: always
     volumes:
       - db2_prod:/database/stagg3

   volumes:
     db2_prod:
</code>```

答:
volumes needs to be at the same indentation with services i.e

```<code>services:
    #...
volumes:
    db2_prod:
</code>```

Body:
Trying to setup docker for the first time and I'm running into a problem with volumes. I feel pretty confident that the spacing and formatting in the .yml is correct at this point.

I've tried versions 3, 3.1, 3.2, 3.3 and 3.4. All are getting the same error message (below)

Unsupported config option for services.volumes: 'db2_prod'

version: '3'

services:
   liberty:
     image: liberty:${liberty_tag}
     ports:
       - "${liberty_ip}:9080:9080"
       - "${liberty_ip}:9443:9443"
     restart: always

   apache:
     image: webapp:${apache_tag}
     ports:
       - "${apache_ip}:80:80"
       - "${apache_ip}:443:443"
     restart: always

   db2:
     image: db2:${db2_tag}
     ports:
       - "${db2_ip}:50000:50000"
     stdin_open: true
     tty: true
     restart: always
     volumes:
       - db2_prod:/database/stagg3

   volumes:
     db2_prod:

Body:
volumes needs to be at the same indentation with services i.e

services:
    #...
volumes:
    db2_prod:


答:
You could put the condition in the for loop:

```<code>for (int i = 0; (i < numArray.size()) && (numArray.get(i) % 2 == 0); i++) {
    evenSum += numArray.get(i);
    outputArea.append(numArray.get(i) + "\n");
}
</code>```

However, it will change what the loop is doing, because it will stop as soon as it hits an odd number. That may or may not be what you want, but is definitely different than the original code, which continues through the whole array.

If you do want to iterate over the whole array, it's probably best to use the foreach version of iteration, and let the compiler produce the fastest code:

```<code>for (int num : numArray) {
    if (num % 2 == 0) {
        evenSum += num;
        outputArea.append(num).append("\n");
    }
}
</code>```

Title: Can I put this statement in the for loop?

Body:
You could put the condition in the for loop:

for (int i = 0; (i < numArray.size()) && (numArray.get(i) % 2 == 0); i++) {
    evenSum += numArray.get(i);
    outputArea.append(numArray.get(i) + "\n");
}

However, it will change what the loop is doing, because it will stop as soon as it hits an odd number. That may or may not be what you want, but is definitely different than the original code, which continues through the whole array.

If you do want to iterate over the whole array, it's probably best to use the foreach version of iteration, and let the compiler produce the fastest code:

for (int num : numArray) {
    if (num % 2 == 0) {
        evenSum += num;
        outputArea.append(num).append("\n");
    }
}


问:
Keep words starting with character/letter in Pandas | Python
I'm not sure how to do this in a dataframe context

I have the table below here with text information

```<code>TEXT                                       |
-------------------------------------------|
"Get some new #turbo #stacks today!"       |
"Is it one or three? #phone"               |
"Mayhaps it be three afterall..."          |
"So many new issues with phone... #iphone" |
</code>```

And I want to edit it down to where only the words with a '#' symbol are kept, like in the result below.

```<code>TEXT             |
-----------------|
"#turbo #stacks" |
"#phone"         |
""               |
"#iphone"        |
</code>```

In some cases, I'd also like to know if it's possible to eliminate the rows that are empty by checking for NaN as true or if you run a different kind of condition to get this result:

```<code>TEXT             |
-----------------|
"#turbo #stacks" |
"#phone"         |
"#iphone"        |
</code>```

Python 2.7 and pandas for this.

答:
You could try using regex and extractall:

```<code>df.TEXT.str.extractall('(#\w+)').groupby(level=0)[0].apply(' '.join)
</code>```

Output:

```<code>0    #turbo #stacks
1            #phone
3           #iphone
Name: 0, dtype: object
</code>```

Body:
I'm not sure how to do this in a dataframe context

I have the table below here with text information

TEXT                                       |
-------------------------------------------|
"Get some new #turbo #stacks today!"       |
"Is it one or three? #phone"               |
"Mayhaps it be three afterall..."          |
"So many new issues with phone... #iphone" |

And I want to edit it down to where only the words with a '#' symbol are kept, like in the result below.

TEXT             |
-----------------|
"#turbo #stacks" |
"#phone"         |
""               |
"#iphone"        |

In some cases, I'd also like to know if it's possible to eliminate the rows that are empty by checking for NaN as true or if you run a different kind of condition to get this result:

TEXT             |
-----------------|
"#turbo #stacks" |
"#phone"         |
"#iphone"        |

Python 2.7 and pandas for this.

Body:
You could try using regex and extractall:

df.TEXT.str.extractall('(#\w+)').groupby(level=0)[0].apply(' '.join)

Output:

0    #turbo #stacks
1            #phone
3           #iphone
Name: 0, dtype: object


问:
angular 2 formdata empty
I can not pass data to FormData. I searched. but I could not understand. Could you please help me.
  My aim; image file save using web API 2. I have not written more wep api 2.

I could not find a solution. is there any other way of using it?

myComponent

```<code>let fp = new fileUploadParametre();
let formData: FormData = new FormData();
var file;

if ($('#fileinput')[0] != undefined) {
  if ($('#fileinput')[0].files.length > 0) {
    file = $('#fileinput')[0].files[0];
    formData.append('uploadingFile', file);
    //fp.fileName = file.name;
    console.log(formData);
  }
  formData.append('siparisid', this.siparis.siparisid);
  formData.append('dokumantipi',this.form.controls.belgeTipiFormController.value);
  formData.append('aciklama',this.form.controls.aciklamaFormController.value);

  this.fileUploadService.kaydet(
    formData
  )
    .subscribe(result => {
      console.log(result);
      if (result === true) {
        this.errorMessages = [];
        this.dialogRef.close(true)
      }
      else
        this.errorMessages = ['Kayıt Yapılamadı'];
    },
    err => {
      if (err.status == 0) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 404) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 401) {
        this.errorMessages = ['Yetki Hatası.'];
      }

      else if (err.status == 400) {
        let errBody = JSON.parse(err._body);
        if (errBody
          && errBody['error'] == 'invalid_grant')
          this.errorMessages = ['Oturum Açılamadı Geçersiz Kullanıcı veya Şifre'];
        else
          this.errorMessages = [errBody.message];
      }
      else
        this.errorMessages = [err.statusTest]

    }
    );
}

 **my Service**

 public kaydet(
  formData: FormData
 ): Observable<any> {

let postFiles = {
  formData: formData
};

return this.http.post(
  this.apiUrl + '/dokumanlar/ResimKaydet',
  JSON.stringify(postFiles)
)
  .map(res => res.json());
}
</code>```

formData=formData {} >> it is empty in this way.

答:
For sending image(avatar) to the server or web api you can use FormData and if you want to follow this purpose please do these works step by step:

In html file use #avatar for accessing ElementRef in component:

```<code><form (ngSubmit)="onSubmit()">
    <input type="file" accept=".png, .jpg, .jpeg" #avatar>
</form>
</code>```

Create component and using for sending image to the server;

```<code>import {Component} from '@angular/core';
import {ElementRef} from '@angular/core';
import {ViewChild} from '@angular/core';

import {HttpClient} from '@angular/common/http';
import {HttpParams} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';

@Component({
    selector: 'app-avatar',
    templateUrl: './avatar.component.html',
    styleUrls: ['./avatar.component.css']
})
export class AvatarComponent {
    @ViewChild('avatar') avatar: ElementRef;

    constructor(private http: HttpClient) { }

    onSubmit() {
        const formData = new FormData();
        formData.append('avatar',
                        this.avatar.nativeElement.files[0],
                        this.avatar.nativeElement.files[0].name);

        const headers = new HttpHeaders();
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        this.http.post('api/upload', formData, {headers: headers})
            .subscribe(
                (response) => {
                },
                (error) => {
                }
             );
     }

}
</code>```

Notice to adding file to FormData like below method with parameters

formData.append(name, fileValue, fileName)

Title: angular 2 formdata empty

Body:
I can not pass data to FormData. I searched. but I could not understand. Could you please help me.
  My aim; image file save using web API 2. I have not written more wep api 2.

I could not find a solution. is there any other way of using it?

myComponent

let fp = new fileUploadParametre();
let formData: FormData = new FormData();
var file;

if ($('#fileinput')[0] != undefined) {
  if ($('#fileinput')[0].files.length > 0) {
    file = $('#fileinput')[0].files[0];
    formData.append('uploadingFile', file);
    //fp.fileName = file.name;
    console.log(formData);
  }
  formData.append('siparisid', this.siparis.siparisid);
  formData.append('dokumantipi',this.form.controls.belgeTipiFormController.value);
  formData.append('aciklama',this.form.controls.aciklamaFormController.value);

  this.fileUploadService.kaydet(
    formData
  )
    .subscribe(result => {
      console.log(result);
      if (result === true) {
        this.errorMessages = [];
        this.dialogRef.close(true)
      }
      else
        this.errorMessages = ['Kayıt Yapılamadı'];
    },
    err => {
      if (err.status == 0) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 404) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 401) {
        this.errorMessages = ['Yetki Hatası.'];
      }

      else if (err.status == 400) {
        let errBody = JSON.parse(err._body);
        if (errBody
          && errBody['error'] == 'invalid_grant')
          this.errorMessages = ['Oturum Açılamadı Geçersiz Kullanıcı veya Şifre'];
        else
          this.errorMessages = [errBody.message];
      }
      else
        this.errorMessages = [err.statusTest]

    }
    );
}

 **my Service**

 public kaydet(
  formData: FormData
 ): Observable<any> {

let postFiles = {
  formData: formData
};

return this.http.post(
  this.apiUrl + '/dokumanlar/ResimKaydet',
  JSON.stringify(postFiles)
)
  .map(res => res.json());
}

formData=formData {} >> it is empty in this way.

Body:
For sending image(avatar) to the server or web api you can use FormData and if you want to follow this purpose please do these works step by step:

In html file use #avatar for accessing ElementRef in component:

<form (ngSubmit)="onSubmit()">
    <input type="file" accept=".png, .jpg, .jpeg" #avatar>
</form>

Create component and using for sending image to the server;

import {Component} from '@angular/core';
import {ElementRef} from '@angular/core';
import {ViewChild} from '@angular/core';

import {HttpClient} from '@angular/common/http';
import {HttpParams} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';

@Component({
    selector: 'app-avatar',
    templateUrl: './avatar.component.html',
    styleUrls: ['./avatar.component.css']
})
export class AvatarComponent {
    @ViewChild('avatar') avatar: ElementRef;

    constructor(private http: HttpClient) { }

    onSubmit() {
        const formData = new FormData();
        formData.append('avatar',
                        this.avatar.nativeElement.files[0],
                        this.avatar.nativeElement.files[0].name);

        const headers = new HttpHeaders();
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        this.http.post('api/upload', formData, {headers: headers})
            .subscribe(
                (response) => {
                },
                (error) => {
                }
             );
     }

}

Notice to adding file to FormData like below method with parameters

formData.append(name, fileValue, fileName)


问:
Laravel blade simple inline if statement
Is it possible with Laravel Blade templating to write a statement like this?

If alt image field exists in database, add. If not, leave out.  What is happening with the code below is the double quotes alt="text" get rendered.

```<code><img src="#" {{$product->extra_img1_alt ? 'alt="'. $product->extra_img1_alt .'"' : ''}}>
</code>```

答:
My dear friend, you just need to change the code</p>

```<code><img src="#" alt=" @if($product->extra_img1_alt) {{$product->extra_img1_alt}} @endif ">
</code>```

Body:
Is it possible with Laravel Blade templating to write a statement like this?

If alt image field exists in database, add. If not, leave out.  What is happening with the code below is the double quotes alt="text" get rendered.

extra_img1_alt ? 'alt="'. $product->extra_img1_alt .'"' : ''}}>

Body:
My dear friend, you just need to change the code

<img src="#" alt=" @if($product->extra_img1_alt) {{$product->extra_img1_alt}} @endif ">


问:
c++: search ignoring accented characters
So... I have a STL vector that I need to search/filter with a user-provided string. (Just mentioning this in case there's a specific/better way to do it in this particular use case)

Currently (this code is old) it's being done by just iterating through it and regex matching each element to see if it matches.

Our problem, however, stems from accented characters. Our desired behavior is for the search to match strings without regard to diacritics (i.e. "telefono" also matches "teléfono" and vice-versa)

Is there a decent way to do this, ideally without having to resort to libraries other than boost?

答: It would be helpful to know what the character encoding is when asking questions about string matching i.e. UTF-8 etc. That being said one of the approaches when dealing with diacritics is to substitute them for the plain character equivalent before doing the string compare. Your database of matches would not contain any diacritics and you would sanitize your search input string before comparing.</p>


问:
Directory for external files in the standard maven directory layout
In Java, we have two different approaches for loading data into the application.

If a file is packed into the jar (call it resource file) we get its InputStream by Class.getResourceAsStream() method.

If a file is not inside the jar (call it external file) we use new FileInputStream().

If I understand correctly, the distinction between resource and external files is due to the fact that the former are required for the application to launch and run properly (therefore packed into an executable jar - shouldn't be modified) and the latter are rather optional and may or may be not provided by the user.

In the standard maven directory layout we put our resource files in the src/main/resources directory so they are included in the jar when building a project. But I can't figure out what the proper directory for external files is.

In the distributed version of my application I want to provide a certain set of default external files, so I need to put them somewhere in the project structure. What is the best location?

So far, I've seen src/main/webapp (which doesn't seem appropriate for desktop applications) and src/main/conf (which seems to get out of use and besides the external files may be of different types - not only text).

A custom directory like src/main/assets or src/main/data? Or maybe there should be another source directory next to the main and test?

I'll be grateful for any suggestions!

答:
This is exactly not what maven is designed to do.

There is, however, a plugin designed to make deployment assemblies with executable jars and their wrappers called appassembler which we use to do this.  It consider what you call external files as configuration files, which are found in src/main/config.

See http://www.mojohaus.org/appassembler/appassembler-maven-plugin/


问:
IE9 fieldset rounded corners
I cannot seem to make IE9 render a fieldset with rounded corners whereas other browsers do.
Has anyone encountered this too ?</p>

答:
its only working in latest rc build , aint working in beta version of IE9
try</p>

```
<code>
.class {
 border-radius-right-bottom: 15px;
}
</code>
```

Title: IE9 fieldset rounded corners

Body:
its only working in latest rc build , aint working in beta version of IE9
try

.class {
 border-radius-right-bottom: 15px;
}


答:
Text in {{ tags are escaped automatically, so you need something more like this:

```<code><img src="#"
     @if($product->extra_img1_alt)
         alt="{{ $product->extra_img1_alt }}"
     @endif
>
</code>```

That said, while you seem to be trying to avoid it, there's nothing really wrong with an empty alt attribute:

```<code><img src="#" alt="{{ $product->extra_img1_alt }}">
</code>```

Title: Laravel blade simple inline if statement

Body:
Text in {{ tags are escaped automatically, so you need something more like this:

<img src="#"
     @if($product->extra_img1_alt)
         alt="{{ $product->extra_img1_alt }}"
     @endif
>

That said, while you seem to be trying to avoid it, there's nothing really wrong with an empty alt attribute:

<img src="#" alt="{{ $product->extra_img1_alt }}">


问:
JSON response optimization
When returning a json object which contains a large number of objects which each have the same property names, do those names contribute much to a larger response size, or will apache's compression de-duplicate the names

in other words, do "name", "height", "width" strings in the below object contribute significantly to the overall size of the response?

```<code>{
    "object1": {
    "name" : "fred1",
    "height" : 1,
    "width" : 2
    },
    "object2": {
    "name" : "fred2",
    "height" : 1,
    "width" : 2
    },
    "object3": {
    "name" : "fred3",
    "height" : 1,
    "width" : 2
    },
    "object4": {
    "name" : "fred4",
    "height" : 1,
    "width" : 2
    },
    "object5": {
    "name" : "fred5",
    "height" : 1,
    "width" : 2
    },
    "object6": {
    "name" : "fred6",
    "height" : 1,
    "width" : 2
    }
}
</code>```

If so, should I return a mapping of name to index and then just send them as a normal array?

答:
gzip compression should reduce the size a lot.
If you really want to find out how much, you could use Charles proxy. It will tell you the compression ratio in percentage.

Btw if you need an easy to use response mapping package for PHP, you can use the Marshal serializer.

Title: JSON response optimization

Body:
When returning a json object which contains a large number of objects which each have the same property names, do those names contribute much to a larger response size, or will apache's compression de-duplicate the names

in other words, do "name", "height", "width" strings in the below object contribute significantly to the overall size of the response?

{
    "object1": {
    "name" : "fred1",
    "height" : 1,
    "width" : 2
    },
    "object2": {
    "name" : "fred2",
    "height" : 1,
    "width" : 2
    },
    "object3": {
    "name" : "fred3",
    "height" : 1,
    "width" : 2
    },
    "object4": {
    "name" : "fred4",
    "height" : 1,
    "width" : 2
    },
    "object5": {
    "name" : "fred5",
    "height" : 1,
    "width" : 2
    },
    "object6": {
    "name" : "fred6",
    "height" : 1,
    "width" : 2
    }
}

If so, should I return a mapping of name to index and then just send them as a normal array?


问:
What version of Docker is my Kubernetes running on?
Kubernetes uses Docker, and kubelet dictates the compatible Docker versions for any given cluster.

My question is, given a Kubernetes cluster that is already configured and running, how would I find out what version of Docker is running in the cluster if I don't have direct access to the nodes?

答:
You can find container runtime and its version using the following:</p>

```<code>kubectl get node <node> -o jsonpath="{.status.nodeInfo.containerRuntimeVersion}"
</code>```

Body:
You can find container runtime and its version using the following:

kubectl get node <node> -o jsonpath="{.status.nodeInfo.containerRuntimeVersion}"


问:
Search in a implementation of LinkedList with Comparator
I have this interface:

```<code>class CustomLinkedList<T> {
    public void append(T dado);
    public void addFirst(T dado);
    public T search(Comparator<T> cmp);
    public void printObjects();
}
</code>```

I need to search in a linked list with a Comparator, but comparators have the compare(obj1, obj2) method with 2 parameters. Here is an example of a comparator:

```<code>public class SearchByEmail implements Comparator<Student> {

    public SearchByEmail(String email) {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        return 0;
    }

}
</code>```

Anyone have an idea of how to implement search method with the comparator?

答:
An example that is horrible:

```<code>public T search(Comparator<T> cmp) {
    Node<T> current = first;

    do {
        if(cmp.compare(current.getElement(), null) == 0){
            return current.getElement();
        }

        current = current.getNext();

    } while (current != null);

    return null;
}
</code>```

And the SearchByEmail:

```<code>public class SearchByEmail implements Comparator<Student> {
    private String email;

    public SearchByEmail(String email) {
        this.email = email;
    }

    @Override
    public int compare(Student o1, Student o2) {
        if(o1.getEmail().equals(email)) return 0;
        return 1;
    }

}
</code>```

Body:
I have this interface:

class CustomLinkedList<T> {
    public void append(T dado);
    public void addFirst(T dado);
    public T search(Comparator<T> cmp);
    public void printObjects();
}

I need to search in a linked list with a Comparator, but comparators have the compare(obj1, obj2) method with 2 parameters. Here is an example of a comparator:

public class SearchByEmail implements Comparator<Student> {

    public SearchByEmail(String email) {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        return 0;
    }

}

Anyone have an idea of how to implement search method with the comparator?

Body:
An example that is horrible:

public T search(Comparator<T> cmp) {
    Node<T> current = first;

    do {
        if(cmp.compare(current.getElement(), null) == 0){
            return current.getElement();
        }

        current = current.getNext();

    } while (current != null);

    return null;
}

And the SearchByEmail:

public class SearchByEmail implements Comparator<Student> {
    private String email;

    public SearchByEmail(String email) {
        this.email = email;
    }

    @Override
    public int compare(Student o1, Student o2) {
        if(o1.getEmail().equals(email)) return 0;
        return 1;
    }

}


问:
Install python 2.6 in CentOS
I have a shell that runs CentOS.

For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.

From what I've read, a number of things will break if you upgrade to 2.5.

I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a ./configure --prefix=/opt which is where I want it to end up. Can I now just make, make install ? Or is there more?

答:
Missing Dependency: libffi.so.5  is here :

ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/libffi-3.0.5-1.el5.kb.i386.rpm

Title: Install python 2.6 in CentOS


问:
ImportError: cannot import name np_utils
I'm trying to run the following example from keras

but I get this error:

```<code>ImportError
Traceback (most recent call last)
<ipython-input-58-50de27eea0f8> in <module>()
      8 import numpy as np
      9 import matplotlib.pyplot as plt
---> 10 from keras.models import Sequential
     11 from keras.layers import Dense, LSTM
     12

/usr/local/lib/python2.7/dist-packages/keras/__init__.py in <module>()
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

/usr/local/lib/python2.7/dist-packages/keras/utils/__init__.py in <module>()
      1 from __future__ import absolute_import
----> 2 from . import np_utils
      3 from . import generic_utils
      4 from . import data_utils
      5 from . import io_utils

ImportError: cannot import name np_utils
</code>```

I'm using Ubuntu and I installed keras with:

```<code>sudo pip install keras
</code>```

This question was already asked but there was no answer:
Keras: Cannot Import Name np_utils

答:
I had to install tensorflow to solve this problem.
(From virtualenv):</p>

```<code> pip install tensorflow
</code>```

Body:
I'm trying to run the following example from keras

but I get this error:

ImportError
Traceback (most recent call last)
<ipython-input-58-50de27eea0f8> in <module>()
      8 import numpy as np
      9 import matplotlib.pyplot as plt
---> 10 from keras.models import Sequential
     11 from keras.layers import Dense, LSTM
     12

/usr/local/lib/python2.7/dist-packages/keras/__init__.py in <module>()
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

/usr/local/lib/python2.7/dist-packages/keras/utils/__init__.py in <module>()
      1 from __future__ import absolute_import
----> 2 from . import np_utils
      3 from . import generic_utils
      4 from . import data_utils
      5 from . import io_utils

ImportError: cannot import name np_utils

I'm using Ubuntu and I installed keras with:

sudo pip install keras

This question was already asked but there was no answer:
Keras: Cannot Import Name np_utils

Body:
I had to install tensorflow to solve this problem.
(From virtualenv):

 pip install tensorflow


问:
Why isn't this javascript guessing game running correctly?
I'm trying to create this psychic game where the program essentially chooses and random letter and the user has 9 guesses to try and guess the random letter.

I feel like so much of the code that I wrote isn't being recognized and I'm feeling very lost and confused.

This is what I have so far.

Basically I expect that the guesses should be displaying and going down every time the user doesn't correctly guess the letter, and when the user tries 9 times, the losses go up.

When I run it though, the only thing that happens is the letters get stored in the array.

var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var wins = 0;
var losses = 0;
var guesses = 9;
var computerGuess = letters[Math.floor(Math.random() * letters.length)];
var userGuessSoFar = [];

document.onkeyup = function(event) {
  var userGuess = event.key;
  document.getElementById("guess-so-far").textContent = userGuess;
  if (userGuess == computerGuess) {
    wins++;
  } else {
    guesses--;
    userGuessSoFar.push(userGuess);
    document.getElementById("guess-so-far").textContent = userGuessSoFar;
  }
  updateWins();
  updateGuesses();
  updateLosses();
}
if (userGuessSoFar.length > 8) {
  losses++;
  userGuessSoFar = [];
  guesses = 9;
  updateLosses();
}

function updateWins() {
  var winPoints = document.getElementById("wins").textContent;
  updateWins.textContent = wins;
}

function updateGuesses() {
  var guessesLeft = document.getElementById("guessLeft").textContent;
  updateGuesses.textContent = guesses;
}

function updateLosses() {
  var losePoints = document.getElementById("losses").textContent;
  updateLosses.textContent = losses;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Psychic Game</h1>
<h2>Guess what letter I'm thinking of...</h2>
<p>Wins: </p><span id="wins"></span>
<p>Losses: <span id="losses"></span></p>
<p>Guesses Left: </p><span id="guessLeft"></span>
<p>Your guesses so far: </p><span id="guess-so-far"></span></code>```

答:
I see a couple immediate issues:

The part that checks userGuessSoFar should be inside the onkeyup handler.

The "update" functions each define a variable that is the textContent of an element. But a different variable (which is actually the name of the function) is set to the string value.

Here are a few optimizations:

As long as you are defining global variables, there's no need to define the "update" display elements every time the values are refreshed.

I also implemented the comment suggestion from @EliRichardson, a shorter way to define an alphabet array.

Also implemented suggestion from @LucaKiebel to call the display functions on first run.

Updated the "win" logic to reset the guesses and choose a new letter.

Combined all display updaters into one function.

var letters = "abcdefghijklmnopqrstuvwxyz".split("");
var wins = 0;
var losses = 0;
var guesses = 9;
var computerGuess = letters[Math.floor(Math.random() * letters.length)];
var userGuessSoFar = [];
var winPoints = document.getElementById("wins");
var guessesLeft = document.getElementById("guessLeft");
var losePoints = document.getElementById("losses");
var guessSoFar = document.getElementById("guess-so-far");

function updateDisplays() {
  winPoints.textContent = wins;
  guessesLeft.textContent = guesses;
  losePoints.textContent = losses;
}

document.onkeyup = function(event) {

  var userGuess = event.key;
  userGuessSoFar.push(userGuess);
  guessSoFar.textContent = userGuessSoFar;

  if (userGuess == computerGuess) {

    wins++;
    guesses = 9
    userGuessSoFar = [];
    computerGuess = letters[Math.floor(Math.random() * letters.length)];

  } else {

    guesses--;

    if (guesses == 0) {
      losses++;
      userGuessSoFar = [];
      guesses = 9;
    }

  }

  updateDisplays();

}

updateDisplays();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Guess what letter I'm thinking of...</p>
Wins: <span id="wins"></span><br>
Losses: <span id="losses"></span><br>
Guesses Remaining: <span id="guessLeft"></span>
<p>Guesses: <span id="guess-so-far"></span></p></code>```

Body:
I'm trying to create this psychic game where the program essentially chooses and random letter and the user has 9 guesses to try and guess the random letter.

I feel like so much of the code that I wrote isn't being recognized and I'm feeling very lost and confused.

This is what I have so far.

Basically I expect that the guesses should be displaying and going down every time the user doesn't correctly guess the letter, and when the user tries 9 times, the losses go up.

When I run it though, the only thing that happens is the letters get stored in the array.

var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var wins = 0;
var losses = 0;
var guesses = 9;
var computerGuess = letters[Math.floor(Math.random() * letters.length)];
var userGuessSoFar = [];

document.onkeyup = function(event) {
  var userGuess = event.key;
  document.getElementById("guess-so-far").textContent = userGuess;
  if (userGuess == computerGuess) {
    wins++;
  } else {
    guesses--;
    userGuessSoFar.push(userGuess);
    document.getElementById("guess-so-far").textContent = userGuessSoFar;
  }
  updateWins();
  updateGuesses();
  updateLosses();
}
if (userGuessSoFar.length > 8) {
  losses++;
  userGuessSoFar = [];
  guesses = 9;
  updateLosses();
}

function updateWins() {
  var winPoints = document.getElementById("wins").textContent;
  updateWins.textContent = wins;
}

function updateGuesses() {
  var guessesLeft = document.getElementById("guessLeft").textContent;
  updateGuesses.textContent = guesses;
}

function updateLosses() {
  var losePoints = document.getElementById("losses").textContent;
  updateLosses.textContent = losses;
}

Psychic Game

Guess what letter I'm thinking of...

Wins:

Losses:

Guesses Left:

Your guesses so far:

Body:
I see a couple immediate issues:

The part that checks userGuessSoFar should be inside the onkeyup handler.

The "update" functions each define a variable that is the textContent of an element. But a different variable (which is actually the name of the function) is set to the string value.

Here are a few optimizations:

As long as you are defining global variables, there's no need to define the "update" display elements every time the values are refreshed.

I also implemented the comment suggestion from @EliRichardson, a shorter way to define an alphabet array.

Also implemented suggestion from @LucaKiebel to call the display functions on first run.

Updated the "win" logic to reset the guesses and choose a new letter.

Combined all display updaters into one function.

var letters = "abcdefghijklmnopqrstuvwxyz".split("");
var wins = 0;
var losses = 0;
var guesses = 9;
var computerGuess = letters[Math.floor(Math.random() * letters.length)];
var userGuessSoFar = [];
var winPoints = document.getElementById("wins");
var guessesLeft = document.getElementById("guessLeft");
var losePoints = document.getElementById("losses");
var guessSoFar = document.getElementById("guess-so-far");

function updateDisplays() {
  winPoints.textContent = wins;
  guessesLeft.textContent = guesses;
  losePoints.textContent = losses;
}

document.onkeyup = function(event) {

  var userGuess = event.key;
  userGuessSoFar.push(userGuess);
  guessSoFar.textContent = userGuessSoFar;

  if (userGuess == computerGuess) {

    wins++;
    guesses = 9
    userGuessSoFar = [];
    computerGuess = letters[Math.floor(Math.random() * letters.length)];

  } else {

    guesses--;

    if (guesses == 0) {
      losses++;
      userGuessSoFar = [];
      guesses = 9;
    }

  }

  updateDisplays();

}

updateDisplays();

<p>Guess what letter I'm thinking of...</p>
Wins: <span id="wins"></span><br>
Losses: <span id="losses"></span><br>
Guesses Remaining: <span id="guessLeft"></span>
<p>Guesses: <span id="guess-so-far"></span></p>


问:
replace single quote in middle of string using regex
Have a string:

```<code>stringName= "'john's example'"
</code>```

Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript

have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work

Help is very appreciated! :)

答:
Use (^'|'$)|' as matching regular expression:

stringName = "'john's e'xam'ple'";
console.log(
  stringName.replace(/(^'|'$)|'/g, '$1')
);```

Body:
Have a string:

stringName= "'john's example'"

Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript

have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work

Help is very appreciated! :)


问:
How to write linq to get most recent incoming event records
var events = context.Events.........

Events has a property 'DueDate' (Datetime)

I want to select most recent 5 records, how to write such a query? Thanks

答:
One way to write it:

var events = context.Events.OrderByDescending(e=>e.DueDate).Take(5);


问:
How to split cell array values into two columns in MATLAB?
I have data in a cell array as shown in the variable viewer here:

```<code>{[2.13949546690144;56.9515770543056],
 [1.98550875192835;50.4110852121618],
 ...}
</code>```

I want to split it into two columns with two decimal-point numbers as:

```<code>2.13   56.95
1.98   50.41
</code>```

by removing opening and closing braces and semicolons such as [;]
(to do as like "Text to columns" in Excel).

答:
If your N-element cell array C has 2-by-1 numeric data in each cell, you can easily convert that into an N-by-2 numeric matrix M like so (using the round function to round each element to 2 significant digits):

```<code>M = round([C{:}].', 2);
</code>```

The syntax C{:} creates a comma-separated list of the contents of C, equivalent to C{1}, C{2}, ... C{N}. These are all horizontally concatenated using [ ... ], then the result is transposed using .'.

Body:
I have data in a cell array as shown in the variable viewer here:

{[2.13949546690144;56.9515770543056],
 [1.98550875192835;50.4110852121618],
 ...}

I want to split it into two columns with two decimal-point numbers as:

2.13   56.95
1.98   50.41

by removing opening and closing braces and semicolons such as [;]
(to do as like "Text to columns" in Excel).

Body:
If your N-element cell array C has 2-by-1 numeric data in each cell, you can easily convert that into an N-by-2 numeric matrix M like so (using the round function to round each element to 2 significant digits):

M = round([C{:}].', 2);

The syntax C{:} creates a comma-separated list of the contents of C, equivalent to C{1}, C{2}, ... C{N}. These are all horizontally concatenated using [ ... ], then the result is transposed using .'.


问:
Using 2D matrix without stack overflow

Hello.
I got a project about the Longest Common Subsequence

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

int max(int a, int b);

int lcs(char *X,char *Y,int m,int n){
    //int L[m+1][n+1];
    int i, j;
    int **L;

    L = (int **)malloc(1*sizeof(int));

    for(i=0;i<=m;i++){
        for(j=0;j<=n;j++){
            L = (int **) realloc(L[i],j*sizeof(int*));
            if(i==0 || j==0)
                L[i][j]=0;
            else if(X[i-1]==Y[j-1])
                L[i][j]=L[i-1][j-1]+1;
            else
                L[i][j]=max(L[i-1][j],L[i][j-1]);
        }
    }
/*
    printf("\n");
    for(i=0;i<=m;i++){
        for(j=0;j<=n;j++){
            printf("%d ",L[i][j]);
        }
        printf("\n");
    }
*/
   return L[m][n];
}

int max(int a, int b)
{
    int max;
    if(a>b)
        max=a;
    else
        max=b;
    return max;
}

int main(){
    FILE *file;
    char c;
    int m=0, n=0, flag=0;
    file=fopen("in1.txt","r");
    if(file==NULL){
        printf("Error opening file.\n");
        exit(0);
    }

    if(file){
        while((c=fgetc(file))!=EOF){
            if(c!=' ' && c!='\n' && flag==0)
                m++;
            if(c=='\n')
                flag=1;
            if(c!=' ' && c!='\n' && flag==1)
                n++;
        }
    }

    char X[m], Y[n];
    int i=0;
    rewind(file);
    flag=0;
    while((c=fgetc(file))!=EOF){
        if(c!=' ' && c!='\n' && flag==0){
            X[i]=c;
            i++;
        }
        if(c=='\n'){
            flag=1;
            i=0;
        }
        if(c!=' ' && c!='\n' && flag==1){
            Y[i]=c;
            i++;
        }
    }

    printf("Length of LCS is %d .\n", lcs( X, Y, m, n ) );
    fclose(file);
    return 0;
}
</code>```

For small matrixs it worked fine but for bigger sequences I get a stack overflow.
I was advised "You shouldn't store 2D-matrix inside main() function or any other function (it may cause stack overflow). Maybe move it outside of functions or allocate dynamically." but I dont know what the person means by moving it outside of functions and I dont know to allocate 2D matrix.

Sorry for the long post.
Thank you

答:
Replace

```<code>char X[m], Y[n];
</code>```

by

```<code>char *X = malloc(m * sizeof(char));
char *Y = malloc(n * sizeof(char));
</code>```

and at the end of your main add:

```<code>free(X);
free(Y);
</code>```

Now you have dynamic allocation on the heap. What you did isn't standard anyways (variable length array on the stack, see here). Apart from that I haven't checked your code. At a first glance, it seems strange that you first split into n and m when counting and then use i for both arrays when filling.

Update:

Now I see you edited your code from your original post. Here is how to do it with a double pointer.

Allocation:

```<code>int **L = malloc((m + 1) * sizeof(int*));
for (int i = 0; i < m + 1; i++)
    L[i] = malloc((n + 1) * sizeof(int));
</code>```

Freeing:

```<code>for (int i = 0; i < m + 1; i++)
    free(L[i]);
free(L);
</code>```

And remove the realloc. And don't forget that you can't return L[m][n] after freeing, so store that value, then free, then return the value.

Title: Using 2D matrix without stack overflow

Body:
Hello.
I got a project about the Longest Common Subsequence

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

int max(int a, int b);

int lcs(char *X,char *Y,int m,int n){
    //int L[m+1][n+1];
    int i, j;
    int **L;

    L = (int **)malloc(1*sizeof(int));

    for(i=0;i<=m;i++){
        for(j=0;j<=n;j++){
            L = (int **) realloc(L[i],j*sizeof(int*));
            if(i==0 || j==0)
                L[i][j]=0;
            else if(X[i-1]==Y[j-1])
                L[i][j]=L[i-1][j-1]+1;
            else
                L[i][j]=max(L[i-1][j],L[i][j-1]);
        }
    }
/*
    printf("\n");
    for(i=0;i<=m;i++){
        for(j=0;j<=n;j++){
            printf("%d ",L[i][j]);
        }
        printf("\n");
    }
*/
   return L[m][n];
}

int max(int a, int b)
{
    int max;
    if(a>b)
        max=a;
    else
        max=b;
    return max;
}

int main(){
    FILE *file;
    char c;
    int m=0, n=0, flag=0;
    file=fopen("in1.txt","r");
    if(file==NULL){
        printf("Error opening file.\n");
        exit(0);
    }

    if(file){
        while((c=fgetc(file))!=EOF){
            if(c!=' ' && c!='\n' && flag==0)
                m++;
            if(c=='\n')
                flag=1;
            if(c!=' ' && c!='\n' && flag==1)
                n++;
        }
    }

    char X[m], Y[n];
    int i=0;
    rewind(file);
    flag=0;
    while((c=fgetc(file))!=EOF){
        if(c!=' ' && c!='\n' && flag==0){
            X[i]=c;
            i++;
        }
        if(c=='\n'){
            flag=1;
            i=0;
        }
        if(c!=' ' && c!='\n' && flag==1){
            Y[i]=c;
            i++;
        }
    }

    printf("Length of LCS is %d .\n", lcs( X, Y, m, n ) );
    fclose(file);
    return 0;
}

For small matrixs it worked fine but for bigger sequences I get a stack overflow.
I was advised "You shouldn't store 2D-matrix inside main() function or any other function (it may cause stack overflow). Maybe move it outside of functions or allocate dynamically." but I dont know what the person means by moving it outside of functions and I dont know to allocate 2D matrix.

Sorry for the long post.
Thank you

Body:
Replace

char X[m], Y[n];

by

char *X = malloc(m * sizeof(char));
char *Y = malloc(n * sizeof(char));

and at the end of your main add:

free(X);
free(Y);

Now you have dynamic allocation on the heap. What you did isn't standard anyways (variable length array on the stack, see here). Apart from that I haven't checked your code. At a first glance, it seems strange that you first split into n and m when counting and then use i for both arrays when filling.

Update:

Now I see you edited your code from your original post. Here is how to do it with a double pointer.

Allocation:

int **L = malloc((m + 1) * sizeof(int*));
for (int i = 0; i < m + 1; i++)
    L[i] = malloc((n + 1) * sizeof(int));

Freeing:

for (int i = 0; i < m + 1; i++)
    free(L[i]);
free(L);

And remove the realloc. And don't forget that you can't return L[m][n] after freeing, so store that value, then free, then return the value.


问:
Query working differently on different servers
I've got a development server where my T-SQL code is working fine, but when I port it to my production server it's breaking. Here's the code:

```<code>DECLARE @ModelNumber AS int = 67787

;WITH UsedNumbers (clnum, clname1) AS
(
    SELECT
        clnum COLLATE SQL_Latin1_General_CP1_CI_AS AS clnum,
        clname1 COLLATE SQL_Latin1_General_CP1_CI_AS AS clname1
    FROM
        ELITE.son_db.dbo.client
    WHERE
        clnum NOT LIKE '%[A-Z]%'
),
OrderedNumbers (clnum, clnum_int, clname1) AS
(
    SELECT TOP 500000
        clnum, CAST(clnum AS int) AS clnum_int, clname1
    FROM
        UsedNumbers
    WHERE
        CAST(clnum AS int) >= @ModelNumber
    ORDER BY
        clnum
)
SELECT TOP 1
    REPLACE(STR(previd + 1, 6), ' ', '0') AS previd
FROM
    (SELECT
         clnum_int, LAG(clnum_int) OVER (ORDER BY clnum) previd
     FROM
         OrderedNumbers) q
WHERE
    previd <> clnum_int - 1
ORDER BY
    clnum_int
</code>```

When I run this code on the development server, it returns results without a problem. When I run it on the production server, I get this error:

Msg 245, Level 16, State 1, Line 3

  Conversion failed when converting the varchar value '57235A' to data type int.

On both servers, if I replace the last SELECT statement with:

```<code>SELECT *
FROM UsedNumbers
WHERE clnum LIKE '57%'
</code>```

I get no results on the development server or the production server, so I'm totally confused by the error message.

Side points: ELITE in the initial SELECT statement refers to linked servers found on both servers. Both linked servers point to the same database, i.e., there are not development and production versions pointed to by the linked servers. 67787 is a seed value that was given to me by the end users; it has no significance to the program other than they want to find the next number after that number.

Can anyone suggest what could be going on here?

答:
Obviously the error generated here when you are casting

```<code>OrderedNumbers (clnum, clnum_int, clname1)
AS
(
    SELECT TOP 500000 clnum, CAST(clnum AS int) AS clnum_int, clname1
    FROM UsedNumbers
    WHERE CAST(clnum AS int) >= @ModelNumber
    ORDER BY clnum
)
</code>```

some how clnum leaks VARCHARs and CAST() to int breaks. Production can execute cte in parallel. Try to use ISNUMERIC ( clnum ) = 1

```<code>OrderedNumbers (clnum, clnum_int, clname1)
    AS
    (
        SELECT TOP 500000 clnum, CAST(clnum AS int) AS clnum_int, clname1
        FROM UsedNumbers
        WHERE ISNUMERIC ( clnum ) = 1
            AND CAST(clnum AS int) >= @ModelNumber
        ORDER BY clnum
    )
</code>```

and maybe use ISNUMERIC() in the first cte

Body:
I've got a development server where my T-SQL code is working fine, but when I port it to my production server it's breaking. Here's the code:

DECLARE @ModelNumber AS int = 67787

;WITH UsedNumbers (clnum, clname1) AS
(
    SELECT
        clnum COLLATE SQL_Latin1_General_CP1_CI_AS AS clnum,
        clname1 COLLATE SQL_Latin1_General_CP1_CI_AS AS clname1
    FROM
        ELITE.son_db.dbo.client
    WHERE
        clnum NOT LIKE '%[A-Z]%'
),
OrderedNumbers (clnum, clnum_int, clname1) AS
(
    SELECT TOP 500000
        clnum, CAST(clnum AS int) AS clnum_int, clname1
    FROM
        UsedNumbers
    WHERE
        CAST(clnum AS int) >= @ModelNumber
    ORDER BY
        clnum
)
SELECT TOP 1
    REPLACE(STR(previd + 1, 6), ' ', '0') AS previd
FROM
    (SELECT
         clnum_int, LAG(clnum_int) OVER (ORDER BY clnum) previd
     FROM
         OrderedNumbers) q
WHERE
    previd <> clnum_int - 1
ORDER BY
    clnum_int

When I run this code on the development server, it returns results without a problem. When I run it on the production server, I get this error:

Msg 245, Level 16, State 1, Line 3

  Conversion failed when converting the varchar value '57235A' to data type int.

On both servers, if I replace the last SELECT statement with:

SELECT *
FROM UsedNumbers
WHERE clnum LIKE '57%'

I get no results on the development server or the production server, so I'm totally confused by the error message.

Side points: ELITE in the initial SELECT statement refers to linked servers found on both servers. Both linked servers point to the same database, i.e., there are not development and production versions pointed to by the linked servers. 67787 is a seed value that was given to me by the end users; it has no significance to the program other than they want to find the next number after that number.

Can anyone suggest what could be going on here?

Body:
Obviously the error generated here when you are casting

OrderedNumbers (clnum, clnum_int, clname1)
AS
(
    SELECT TOP 500000 clnum, CAST(clnum AS int) AS clnum_int, clname1
    FROM UsedNumbers
    WHERE CAST(clnum AS int) >= @ModelNumber
    ORDER BY clnum
)

some how clnum leaks VARCHARs and CAST() to int breaks. Production can execute cte in parallel. Try to use ISNUMERIC ( clnum ) = 1

OrderedNumbers (clnum, clnum_int, clname1)
    AS
    (
        SELECT TOP 500000 clnum, CAST(clnum AS int) AS clnum_int, clname1
        FROM UsedNumbers
        WHERE ISNUMERIC ( clnum ) = 1
            AND CAST(clnum AS int) >= @ModelNumber
        ORDER BY clnum
    )

and maybe use ISNUMERIC() in the first cte


问:
rewrite old url to new one
I have this is current url pattern for a group of urls

```<code>http://www.example.com/assets/img/banner.jpg
</code>```

which will be changing to

```<code>http://www.example.com/assets/img/all_banners/banner.jpg
</code>```

How do I use mod_rewrite to rewrite these urls to the new pattern using .htaccess file?

I have this so far but it is not working...

```<code>RewriteRule /assets/img/(.*) /assets/img/all_banners/$1 [R=301,NC,L,QSA]
</code>```

Maybe the flags are wrong?

答:
You can use this rule as your very first rule:

```<code>RewriteEngine On

RewriteRule ^/?(assets/img)/([\w-]+\.[a-z]+)$ /$1/all_banners/$2 [R=301,NC,L,NE]
</code>```

Make sure to clear your browser cache or use a new browser for testing.

Title: rewrite old url to new one

Body:
I have this is current url pattern for a group of urls

http://www.example.com/assets/img/banner.jpg

which will be changing to

http://www.example.com/assets/img/all_banners/banner.jpg

How do I use mod_rewrite to rewrite these urls to the new pattern using .htaccess file?

I have this so far but it is not working...

RewriteRule /assets/img/(.*) /assets/img/all_banners/$1 [R=301,NC,L,QSA]

Maybe the flags are wrong?

Body:
You can use this rule as your very first rule:

RewriteEngine On

RewriteRule ^/?(assets/img)/([\w-]+\.[a-z]+)$ /$1/all_banners/$2 [R=301,NC,L,NE]

Make sure to clear your browser cache or use a new browser for testing.


问:
Subscribe to Observable in Angular2
I have a function, which remembers a previous url

```<code>   prevId () {
     let name, id, lat, lng;
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {
        console.log('prev:', this.previousUrl);
        this.previousUrl = (e as NavigationEnd).url;
    }
</code>```

I would like to rewrite this in Observable-style, if it possible, but everything I try doesn't work.
Is it possible to solve?
Could you also please advice me some good articles about Observable, because I am just beginner and the topic seems to be pretty difficult.

UPD: I need to usr the data outside the function later, that is why I need Observer.

for example

```<code>myFun(a) {
console.log(a);
}

myFun(this.previousUrl);
</code>```

答:
If the only thing you need is use the url outside of your function, you may do this:

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/take';

prevId(): Observable<NavigationEnd> {
  return new Observable(observer => {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .take(1)
      .subscribe(e => {
        observer.next(e as NavigationEnd);
        observer.complete();
      });
  });
}
</code>```

Then you must call the function like this:

```<code>prevId().subscribe(navigationEndEvent => {
  this.previousUrl = navigationEndEvent.url;
});
</code>```

I made this example thinking that you just want the previousUrl information when you call the prevId(), because of this I put the .take(1) operator and called observer.complete().

The .take(1) will automatically unsubscribe the subscription made into this.router.event when the first value comes from it.

And the observer.complete() will also unsubscribe the all the subscriptions made whenever in the returned Observable.

Title: Subscribe to Observable in Angular2

Body:
I have a function, which remembers a previous url

   prevId () {
     let name, id, lat, lng;
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {
        console.log('prev:', this.previousUrl);
        this.previousUrl = (e as NavigationEnd).url;
    }

I would like to rewrite this in Observable-style, if it possible, but everything I try doesn't work.
Is it possible to solve?
Could you also please advice me some good articles about Observable, because I am just beginner and the topic seems to be pretty difficult.

UPD: I need to usr the data outside the function later, that is why I need Observer.

for example

myFun(a) {
console.log(a);
}

myFun(this.previousUrl);

Body:
If the only thing you need is use the url outside of your function, you may do this:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/take';

prevId(): Observable<NavigationEnd> {
  return new Observable(observer => {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .take(1)
      .subscribe(e => {
        observer.next(e as NavigationEnd);
        observer.complete();
      });
  });
}

Then you must call the function like this:

prevId().subscribe(navigationEndEvent => {
  this.previousUrl = navigationEndEvent.url;
});

I made this example thinking that you just want the previousUrl information when you call the prevId(), because of this I put the .take(1) operator and called observer.complete().

The .take(1) will automatically unsubscribe the subscription made into this.router.event when the first value comes from it.

And the observer.complete() will also unsubscribe the all the subscriptions made whenever in the returned Observable.


问:
Strophe XMPP using Angular 2
I want to create service for Strophe.JS XMPP library in angular2 project. That service is responsible for Open and Close connection and include handler to receive message. I am able to do in .Net MVC project but i did not found a way to implement in Angular2 framework.

Thanks,
Sanjeev

答:
First to install @types/strophe

```<code>npm install --save @types/strophe
</code>```

Second to download Strophe library from Strophe Site

Then, You should put the framework inside /src/assets/

Then, You should add the script tag to the index.html before polyfills.js and main.js

Thus

```<code><script src="assets/strophejs-1.2.14/strophe.js"></script>
</code>```

Last,

you should put this declare statement before to use the strophe.

```<code>declare var Strophe: any;
</code>```

It works for me!

I hope to help you.

Regards.

Title: Strophe XMPP using Angular 2

Body:
First to install @types/strophe

npm install --save @types/strophe

Second to download Strophe library from Strophe Site

Then, You should put the framework inside /src/assets/

Then, You should add the script tag to the index.html before polyfills.js and main.js

Thus

<script src="assets/strophejs-1.2.14/strophe.js"></script>

Last,

you should put this declare statement before to use the strophe.

declare var Strophe: any;

It works for me!

I hope to help you.

Regards.


问:
Iterating through a json file using map function in react
I'm new to react and trying to wrap my head around it. Currently, I'm trying to display a list of emails and usernames from a json file that look like this:

```<code>    {
"results":[
  {
     "gender":"female",
     "name":{
        "title":"mrs",
        "first":"maïssae",
        "last":"hummel"
     },
     "location":{
        "street":"7387 burgemeester reigerstraat",
        "city":"opsterland",
        "state":"utrecht",
        "postcode":49157
     },
     "email":"maïssae.hummel@example.com",
     "login":{
        "username":"bigladybug314",
        "password":"news",
        "salt":"4rnXJ7rr",
        "md5":"36c340d3a1f14b04ead5fa45899fa6d8",
        "sha1":"9303a71d951971500d8e01aa69bfb6b18a9c14ee",
        "sha256":"cad8fbc826f9add00262cd2e5850dc985b3da37a83d2603e14a700322738729a"
     },
     "dob":"1967-10-07 16:49:29",
     "registered":"2007-09-30 12:00:20",
     "phone":"(830)-232-0383",
     "cell":"(465)-588-8299",
     "id":{
        "name":"BSN",
        "value":"48491274"
     },
     "picture":{
        "large":"https://randomuser.me/api/portraits/women/12.jpg",
        "medium":"https://randomuser.me/api/portraits/med/women/12.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/women/12.jpg"
     },
     "nat":"NL"
  },
  ...
</code>```

This json file is the response from randomuser api (https://randomuser.me/api/?results=10). I want to iterate through the json objects, return and render a list of all the emails and usernames (under login) of each user.

Thanks in advance for the help. Also, any other useful information about mapping would be greatly appreciated.

答:
This is pretty standard and you should read the docs and probably go through the tutorial if this is your first time with React

Anyway, you have a list of results and you map over them like this:

```<code><ul>
  {results.map(user => <li key={user.id}>{user.login.username} - {user.login.email}</li>)}
</ul>
</code>```

I don't know what randomuser.me is about, but it seems that the id fields from each result is not very helpful. So you'll need to find a unique value for the key.

Body:
I'm new to react and trying to wrap my head around it. Currently, I'm trying to display a list of emails and usernames from a json file that look like this:

    {
"results":[
  {
     "gender":"female",
     "name":{
        "title":"mrs",
        "first":"maïssae",
        "last":"hummel"
     },
     "location":{
        "street":"7387 burgemeester reigerstraat",
        "city":"opsterland",
        "state":"utrecht",
        "postcode":49157
     },
     "email":"maïssae.hummel@example.com",
     "login":{
        "username":"bigladybug314",
        "password":"news",
        "salt":"4rnXJ7rr",
        "md5":"36c340d3a1f14b04ead5fa45899fa6d8",
        "sha1":"9303a71d951971500d8e01aa69bfb6b18a9c14ee",
        "sha256":"cad8fbc826f9add00262cd2e5850dc985b3da37a83d2603e14a700322738729a"
     },
     "dob":"1967-10-07 16:49:29",
     "registered":"2007-09-30 12:00:20",
     "phone":"(830)-232-0383",
     "cell":"(465)-588-8299",
     "id":{
        "name":"BSN",
        "value":"48491274"
     },
     "picture":{
        "large":"https://randomuser.me/api/portraits/women/12.jpg",
        "medium":"https://randomuser.me/api/portraits/med/women/12.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/women/12.jpg"
     },
     "nat":"NL"
  },
  ...

This json file is the response from randomuser api (https://randomuser.me/api/?results=10). I want to iterate through the json objects, return and render a list of all the emails and usernames (under login) of each user.

Thanks in advance for the help. Also, any other useful information about mapping would be greatly appreciated.

Body:
This is pretty standard and you should read the docs and probably go through the tutorial if this is your first time with React

Anyway, you have a list of results and you map over them like this:

<ul>
  {results.map(user => <li key={user.id}>{user.login.username} - {user.login.email}</li>)}
</ul>

I don't know what randomuser.me is about, but it seems that the id fields from each result is not very helpful. So you'll need to find a unique value for the key.

ContentLicense: CC BY-SA 4.0


问:
How to store different types of methods in a dictionary from different classes in C#

I'm building a windows app to be able to read a txt file that contains a lot of markup that explains what kind of information is provided. The markup used looks like "#FLAG xxx" where xxx is the information that is retrieved. The information is handled differently depending on the markup used and therefore I need different methods to extract it.

In my program I use a Dictionary to store all possible variations of markup that can be in the file can contain, and then I read every row in the file and compare if there is a hit in the Dictionary. As it is now, I hardcode what method to call but feel it must be a stupid way to solve this. I load everything contained in the Dictionaryn from another class (Settings), which means I can not access the methods I put in my first class (Form1).

I know I'm doing a lot of mistakes here, but I'm really new to C# and can't do a better solution myself. How would a better practise be to solve this problem. I don't want to write lots of if-statements if I don't need to.

The code below is a downward version of what I have written. Othervise it will be to messy to read. And yes, I removed the Excel-export part but hopefylly you can see what I'm trying to do anyway.

Forms1.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace MarkupReader
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "File (*.txt)|*.txt|All files (*.*)|*.*";

        ofd.Title = "Open file";
        ofd.Multiselect = false;

        if (ofd.ShowDialog() == DialogResult.OK)
        {

            StreamReader readFile = new StreamReader(File.OpenRead(ofd.FileName), Encoding.GetEncoding(437));
            ExportFile(readFile);
            readFile.Dispose();
        }
    }

    private void ExportFile(StreamReader readFile)
    {
        Dictionary<string, Tuple<string, int, string>> markup = new Dictionary<string, Tuple<string, int, string>>();

        readFile.DiscardBufferedData();
        readFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

        Settings settings = new Settings();
        settings.SetMarkup(markup);

        string fileMarkup = "";
        string fileMarkupValues = "";
        string line = "";

        while (line != null)
        {
            line = readFile.ReadLine();
            if (line != null)
            {
                //Get markup
                fileMarkup = line.Trim().Split(' ').First();
                fileMarkupValues = line.Replace(fileMarkup, "");

                if (markup.ContainsKey(fileMarkup))
                {
                    /* markupItemX = X is content
                     * Item1 = User flag
                     * Item2 = Export to worksheet number
                     * Item3 = Extract method to call
                     * Item4 =
                     */

                    //Export to excel sheet 1
                    if (markup[fileMarkup].Item2 == 1)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                    //Export to excel sheet 2
                    if (markup[fileMarkup].Item2 == 2)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                }
            }
        }
    }

    public void ExtractMethodOne(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodTwo(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodThree(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFour(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFive(string markupData)
    {
        //Extract stuff and write to Excel
    }

}
}
</code>```

Setting.cs (it really contains alot more, this is just a example)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkupReader
{
class Settings
{
    public void SetMarkup(Dictionary<string, Tuple<string, int, string>> markup)
    {
        int workSheet = 1;
        markup.Add("#FLAG", new Tuple<string, int, string>("User flag", workSheet, "extractDataOne"));
        markup.Add("#FORMAT", new Tuple<string, int, string>("User format", workSheet, "extractDataOne"));
        markup.Add("#TYPE", new Tuple<string, int, string>("User type", workSheet, "extractDataOne"));
    }
}
}
</code>```

答:
Based on the signature of your ExtractX methods (void with one string param), you can do something like this:

```<code>// Static field or whatever you want
Dictionary<string, Action<string>> methods = new Dictionary<string, Action<string>>()
{
    { "extractDataOne", ExtractMethodOne },
    { "extractDataTwo", ExtractMethodTwo },
    { "extractDataThree", ExtractMethodThree },
    { "extractDataFour", ExtractMethodFour },
    { "extractDataFive", ExtractMethodFive },
};

// And then use it like this
methods[markup[fileMarkup].Item3].Invoke(fileMarkupValues);
</code>```

Although I don't understand how you're gonna differienciate between sheet 1 and 2 since you use the same methods for both conditions.

Body:
I'm building a windows app to be able to read a txt file that contains a lot of markup that explains what kind of information is provided. The markup used looks like "#FLAG xxx" where xxx is the information that is retrieved. The information is handled differently depending on the markup used and therefore I need different methods to extract it.

In my program I use a Dictionary to store all possible variations of markup that can be in the file can contain, and then I read every row in the file and compare if there is a hit in the Dictionary. As it is now, I hardcode what method to call but feel it must be a stupid way to solve this. I load everything contained in the Dictionaryn from another class (Settings), which means I can not access the methods I put in my first class (Form1).

I know I'm doing a lot of mistakes here, but I'm really new to C# and can't do a better solution myself. How would a better practise be to solve this problem. I don't want to write lots of if-statements if I don't need to.

The code below is a downward version of what I have written. Othervise it will be to messy to read. And yes, I removed the Excel-export part but hopefylly you can see what I'm trying to do anyway.

Forms1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace MarkupReader
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "File (*.txt)|*.txt|All files (*.*)|*.*";

        ofd.Title = "Open file";
        ofd.Multiselect = false;

        if (ofd.ShowDialog() == DialogResult.OK)
        {

            StreamReader readFile = new StreamReader(File.OpenRead(ofd.FileName), Encoding.GetEncoding(437));
            ExportFile(readFile);
            readFile.Dispose();
        }
    }

    private void ExportFile(StreamReader readFile)
    {
        Dictionary<string, Tuple<string, int, string>> markup = new Dictionary<string, Tuple<string, int, string>>();

        readFile.DiscardBufferedData();
        readFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

        Settings settings = new Settings();
        settings.SetMarkup(markup);

        string fileMarkup = "";
        string fileMarkupValues = "";
        string line = "";

        while (line != null)
        {
            line = readFile.ReadLine();
            if (line != null)
            {
                //Get markup
                fileMarkup = line.Trim().Split(' ').First();
                fileMarkupValues = line.Replace(fileMarkup, "");

                if (markup.ContainsKey(fileMarkup))
                {
                    /* markupItemX = X is content
                     * Item1 = User flag
                     * Item2 = Export to worksheet number
                     * Item3 = Extract method to call
                     * Item4 =
                     */

                    //Export to excel sheet 1
                    if (markup[fileMarkup].Item2 == 1)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                    //Export to excel sheet 2
                    if (markup[fileMarkup].Item2 == 2)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                }
            }
        }
    }

    public void ExtractMethodOne(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodTwo(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodThree(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFour(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFive(string markupData)
    {
        //Extract stuff and write to Excel
    }

}
}

Setting.cs (it really contains alot more, this is just a example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkupReader
{
class Settings
{
    public void SetMarkup(Dictionary<string, Tuple<string, int, string>> markup)
    {
        int workSheet = 1;
        markup.Add("#FLAG", new Tuple<string, int, string>("User flag", workSheet, "extractDataOne"));
        markup.Add("#FORMAT", new Tuple<string, int, string>("User format", workSheet, "extractDataOne"));
        markup.Add("#TYPE", new Tuple<string, int, string>("User type", workSheet, "extractDataOne"));
    }
}
}

Body:
Based on the signature of your ExtractX methods (void with one string param), you can do something like this:

// Static field or whatever you want
Dictionary<string, Action<string>> methods = new Dictionary<string, Action<string>>()
{
    { "extractDataOne", ExtractMethodOne },
    { "extractDataTwo", ExtractMethodTwo },
    { "extractDataThree", ExtractMethodThree },
    { "extractDataFour", ExtractMethodFour },
    { "extractDataFive", ExtractMethodFive },
};

// And then use it like this
methods[markup[fileMarkup].Item3].Invoke(fileMarkupValues);

Although I don't understand how you're gonna differienciate between sheet 1 and 2 since you use the same methods for both conditions.