问:
Subscribe Observable value
When I'm logging the value of my variable inside the subscribe i have a value but when doing it outside it i get undefined ???:

```<code>this._postService.getConf("app/conf/conf.json")
   .subscribe(res =>{
      this.home = JSON.stringify(res);
      console.log("value :" + this.home);
</code>```

i want to initialize my home variable with a certain value I'm doing it on ngOnInit but it get the value undefined when I'm trying to get it outside:

This is my function :

```<code>getConf(url) {
   return this._http.get(url).
      map(res => {return res.json()});
}

ngOnInit() {

  this._postService.getConf("app/conf/conf.json")
   .subscribe(res => {
        this.home = JSON.stringify(res);
        console.log("hahowaaaaaaaa" + this.home);
   }
  );

  this._postService.getPosts(this.home)
  .subscribe(result =>{
    this.loading = false;
    this.actionsG = result;
    var count = JSON.stringify(result);

    this.aCount = count.substring(count.indexOf(','),23);

  },error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsG'));

  this._postService.getPosts(this.home ).subscribe(result => this.actionsV =
    result, error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsV ngOnInit' + this.page));
}
</code>```

答:
My ngOnInit() had called a process that gets data from a DB.
I expected the this.## variables which were updated in the method to be available after the call.   As was described above, the call passes to observable, which means the variables are not available in ngOnInit().   But they were all populated when the HTML page displayed.

So the solution is to do all the needed work inside the method and then refer to variables which will be populated in HTML.

```<code>this.service.getCity(zip).subscribe(
    data => {
        if (data.errStatus == 0) {
            console.log("data: " +   data.xx.List);

            this.xx.List = data.xx.List;
            console.log("data2: " + this.xxList);
        } else {
            data.errText;
            console.log(data.errText);
        }
    },
    err => console.error(err),
    () => console.log('done')
);
</code>```

Title: Subscribe Observable value

Body:
When I'm logging the value of my variable inside the subscribe i have a value but when doing it outside it i get undefined ???:

this._postService.getConf("app/conf/conf.json")
   .subscribe(res =>{
      this.home = JSON.stringify(res);
      console.log("value :" + this.home);

i want to initialize my home variable with a certain value I'm doing it on ngOnInit but it get the value undefined when I'm trying to get it outside:

This is my function :

getConf(url) {
   return this._http.get(url).
      map(res => {return res.json()});
}

ngOnInit() {

  this._postService.getConf("app/conf/conf.json")
   .subscribe(res => {
        this.home = JSON.stringify(res);
        console.log("hahowaaaaaaaa" + this.home);
   }
  );

  this._postService.getPosts(this.home)
  .subscribe(result =>{
    this.loading = false;
    this.actionsG = result;
    var count = JSON.stringify(result);

    this.aCount = count.substring(count.indexOf(','),23);

  },error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsG'));

  this._postService.getPosts(this.home ).subscribe(result => this.actionsV =
    result, error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsV ngOnInit' + this.page));
}

Body:
My ngOnInit() had called a process that gets data from a DB.
I expected the this.## variables which were updated in the method to be available after the call.   As was described above, the call passes to observable, which means the variables are not available in ngOnInit().   But they were all populated when the HTML page displayed.

So the solution is to do all the needed work inside the method and then refer to variables which will be populated in HTML.

this.service.getCity(zip).subscribe(
    data => {
        if (data.errStatus == 0) {
            console.log("data: " +   data.xx.List);

            this.xx.List = data.xx.List;
            console.log("data2: " + this.xxList);
        } else {
            data.errText;
            console.log(data.errText);
        }
    },
    err => console.error(err),
    () => console.log('done')
);


来源: stackexchange

问:
Serializable header error reading a file
im trying to make a translator (it's homework) using a serializable file, I did write one object and it worked, but when I want to have multiple entrances on the file it gives a header error, I use a custom ObjectInputStreamClass and the program is WIP yet and this stops me from finishing it.
    //Main class

```<code>package basesYficheros;

import java.io.*;
import java.util.*;

public class Ser3Main {
static Scanner inNum = new Scanner(System.in);
static Scanner inText = new Scanner(System.in);
static String ruta = "C:/Users/Richard/Desktop/diccionario.dat";

public static void main(String[] args) {
    int opcion = menu();

    switch (opcion) {
    case 1:
        MiObjectOutputStream escribir = crearArchivo(ruta);
        System.out.println("Introduce la palabra en español que quieras agregar");
        String esp = inText.next();
        Ser3Palabra pEsp = new Ser3Palabra(esp);
        // TODO comprobar que no existe
        System.out.println("Introduce su traducción");
        String ing = inText.next();
        Ser3Palabra pIng = new Ser3Palabra(ing);
        Ser3Trad conjunto = new Ser3Trad(pEsp, pIng);
        guardarTrad(conjunto, escribir);
        try {
            escribir.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;
    case 2:
        leerArchivo();

        break;

    default:
        break;
    }
}

private static int menu() {
    int opc = 0;
    while (opc < 1 | opc > 2) {
        System.out.println("Elige una opción\n" + "1.Agregar una traducción\n" + "2.Traducir una palabra");
        opc = inNum.nextInt();
    }
    return opc;

}

private static MiObjectOutputStream crearArchivo(String rutaArchivo) {
    try {

        File archivo = new File(rutaArchivo);

        MiObjectOutputStream escribir = new MiObjectOutputStream(new FileOutputStream(archivo));

        return escribir;

    } catch (IOException e) {
        System.out.println("Error I/O");

        System.exit(0);
    }
    return null;
} // FIN CREARARCHIVO

private static void guardarTrad(Ser3Trad trad, MiObjectOutputStream escribir) {

    try {

        escribir.writeObject(trad);

    } catch (IOException e) {

        System.out.println("Error I/O");

        System.exit(0);
    }

}

private static void leerArchivo() {

    File archivo = new File(ruta);

    boolean finalArchivo = false;

    try {

        ObjectInputStream leer=new ObjectInputStream(new FileInputStream(ruta));

        while (!finalArchivo) {
            Ser3Trad trad =(Ser3Trad) leer.readObject();
            System.out.println( trad);
        }
        leer.close();
        // para que salga del bucle
    } catch (ClassNotFoundException e) {
        System.out.println("clase no encontrada");
        finalArchivo = true;
    } catch (EOFException e) {
        System.out.println("Final del archivo");
        finalArchivo = true;
    } catch (FileNotFoundException e) {
        System.out.println("Archivo no encontrado");
        finalArchivo = true;
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error I/O");
        System.exit(0);
    }

}
</code>```

Word class

```<code>package basesYficheros;

import java.io.Serializable;

public class Ser3Palabra implements Serializable {
    String palabra;
    public String getPalabra() {
    return palabra;
    }
    public void setPalabra(String palabra) {
        this.palabra = palabra;
    }

    public Ser3Palabra(String palabra) {
        this.palabra = palabra;
     }}
</code>```

The translate class

```<code>package basesYficheros;

import java.io.Serializable;

public class Ser3Trad implements Serializable {
    Ser3Palabra español;
    Ser3Palabra inglés;
    public Ser3Palabra getEspañol() {
        return español;
    }
    public void setEspañol(Ser3Palabra español) {
        this.español = español;
    }
    public Ser3Palabra getInglés() {
        return inglés;
    }
    public void setInglés(Ser3Palabra inglés) {
        this.inglés = inglés;
    }
    public Ser3Trad(Ser3Palabra español, Ser3Palabra inglés) {
        super();
        this.español = español;
        this.inglés = inglés;
    }
    @Override
    public String toString() {
        return "Ser3Trad [español=" + español.getPalabra() + ", inglés=" + inglés.getPalabra() + "]";
    }

}
</code>```

And my custom ObjectOutputStream in order to remove the headers

```<code>package basesYficheros;
import java.io.*;
//Esta clase hereda sus propiedades de ObjectOutputStream
public class MiObjectOutputStream extends ObjectOutputStream  {
    //Sobrescribimos el método que crea la cabecera
    protected void writeStreamHeader() throws IOException{
        // No hacer nada.
    }

    //Constructores
    public MiObjectOutputStream () throws IOException{
        super();
    }
    public MiObjectOutputStream(OutputStream out) throws IOException{
                super(out);
        }
</code>```

The error is the following

```<code>java.io.StreamCorruptedException: invalid stream header: 73720017
Error I/O
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at basesYficheros.Ser3Main.leerArchivo(Ser3Main.java:93)
at basesYficheros.Ser3Main.main(Ser3Main.java:34)
</code>```

答: So you've written a custom ObjectOutputStream derived class to remove the stream header, and now you're getting an error reading the missing stream header. Why are you surprised? Put back the stream header, or remove your class altogether.

ContentLicense: CC BY-SA 3.0

Body:
im trying to make a translator (it's homework) using a serializable file, I did write one object and it worked, but when I want to have multiple entrances on the file it gives a header error, I use a custom ObjectInputStreamClass and the program is WIP yet and this stops me from finishing it.
    //Main class

package basesYficheros;

import java.io.*;
import java.util.*;

public class Ser3Main {
static Scanner inNum = new Scanner(System.in);
static Scanner inText = new Scanner(System.in);
static String ruta = "C:/Users/Richard/Desktop/diccionario.dat";

public static void main(String[] args) {
    int opcion = menu();

    switch (opcion) {
    case 1:
        MiObjectOutputStream escribir = crearArchivo(ruta);
        System.out.println("Introduce la palabra en español que quieras agregar");
        String esp = inText.next();
        Ser3Palabra pEsp = new Ser3Palabra(esp);
        // TODO comprobar que no existe
        System.out.println("Introduce su traducción");
        String ing = inText.next();
        Ser3Palabra pIng = new Ser3Palabra(ing);
        Ser3Trad conjunto = new Ser3Trad(pEsp, pIng);
        guardarTrad(conjunto, escribir);
        try {
            escribir.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;
    case 2:
        leerArchivo();

        break;

    default:
        break;
    }
}

private static int menu() {
    int opc = 0;
    while (opc < 1 | opc > 2) {
        System.out.println("Elige una opción\n" + "1.Agregar una traducción\n" + "2.Traducir una palabra");
        opc = inNum.nextInt();
    }
    return opc;

}

private static MiObjectOutputStream crearArchivo(String rutaArchivo) {
    try {

        File archivo = new File(rutaArchivo);

        MiObjectOutputStream escribir = new MiObjectOutputStream(new FileOutputStream(archivo));

        return escribir;

    } catch (IOException e) {
        System.out.println("Error I/O");

        System.exit(0);
    }
    return null;
} // FIN CREARARCHIVO

private static void guardarTrad(Ser3Trad trad, MiObjectOutputStream escribir) {

    try {

        escribir.writeObject(trad);

    } catch (IOException e) {

        System.out.println("Error I/O");

        System.exit(0);
    }

}

private static void leerArchivo() {

    File archivo = new File(ruta);

    boolean finalArchivo = false;

    try {

        ObjectInputStream leer=new ObjectInputStream(new FileInputStream(ruta));

        while (!finalArchivo) {
            Ser3Trad trad =(Ser3Trad) leer.readObject();
            System.out.println( trad);
        }
        leer.close();
        // para que salga del bucle
    } catch (ClassNotFoundException e) {
        System.out.println("clase no encontrada");
        finalArchivo = true;
    } catch (EOFException e) {
        System.out.println("Final del archivo");
        finalArchivo = true;
    } catch (FileNotFoundException e) {
        System.out.println("Archivo no encontrado");
        finalArchivo = true;
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error I/O");
        System.exit(0);
    }

}

Word class

package basesYficheros;

import java.io.Serializable;

public class Ser3Palabra implements Serializable {
    String palabra;
    public String getPalabra() {
    return palabra;
    }
    public void setPalabra(String palabra) {
        this.palabra = palabra;
    }

    public Ser3Palabra(String palabra) {
        this.palabra = palabra;
     }}

The translate class

package basesYficheros;

import java.io.Serializable;

public class Ser3Trad implements Serializable {
    Ser3Palabra español;
    Ser3Palabra inglés;
    public Ser3Palabra getEspañol() {
        return español;
    }
    public void setEspañol(Ser3Palabra español) {
        this.español = español;
    }
    public Ser3Palabra getInglés() {
        return inglés;
    }
    public void setInglés(Ser3Palabra inglés) {
        this.inglés = inglés;
    }
    public Ser3Trad(Ser3Palabra español, Ser3Palabra inglés) {
        super();
        this.español = español;
        this.inglés = inglés;
    }
    @Override
    public String toString() {
        return "Ser3Trad [español=" + español.getPalabra() + ", inglés=" + inglés.getPalabra() + "]";
    }

}

And my custom ObjectOutputStream in order to remove the headers

package basesYficheros;
import java.io.*;
//Esta clase hereda sus propiedades de ObjectOutputStream
public class MiObjectOutputStream extends ObjectOutputStream  {
    //Sobrescribimos el método que crea la cabecera
    protected void writeStreamHeader() throws IOException{
        // No hacer nada.
    }

    //Constructores
    public MiObjectOutputStream () throws IOException{
        super();
    }
    public MiObjectOutputStream(OutputStream out) throws IOException{
                super(out);
        }

The error is the following

java.io.StreamCorruptedException: invalid stream header: 73720017
Error I/O
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at basesYficheros.Ser3Main.leerArchivo(Ser3Main.java:93)
at basesYficheros.Ser3Main.main(Ser3Main.java:34)


问:
Internet Explorer makes HEAD and GET requests for same <object>svg
I have an external svg file in my MVC project like this:

```<code><object id="demo" type="image/svg+xml" data="/Content/images/demo.svg" style="width: 100%; height: 100%; display:block; right:0; position:absolute "></object>
</code>```

There is only GET request in FF, ME and Chrome but if I open my project in IE 11, it makes HEAD and GET requests same time. I couldn't find how to avoid. Is it normal? or am I in trouble? Saying trouble, because that svg file size is approximately 4.5 Mb. Network monitor looks like :

```<code>File     Protocol  Method    Type         Transferred   Cause
---------------------------------------------------------------
demo.svg  HTTP/2    HEAD  image/svg+xml     4.55 MB       -
demo.svg  HTTP/2    GET   image/svg+xml     4.55 MB    document
</code>```

UPDATE-Workaround:

Well, i found an odd way. In fact a bit lagging while trying to get DOM elements but still better than make people download extra 4.5Mb every visit, right ?

I removed object element, loaded svg file via XMLHttpRequest  object and set the content of a div with responseText(returns whole svg file as text) property. Inevitably a loading image added just before call function to say: "hey it's gonna be lag for a sec don't worry."

By the way, i tried to use Blob object to create url for <object> element's data attribute but it doesn't work in IE with <object>.

I still want to know how to prevent HEAD request in IE.

答:
This is because of <object>. Try using  instead:

```<code><img src="/Content/images/demo.svg" style="width: 100%; height: 100%; display:block; right:0; position:absolute ">
</code>```

Body:
I have an external svg file in my MVC project like this:

<object id="demo" type="image/svg+xml" data="/Content/images/demo.svg" style="width: 100%; height: 100%; display:block; right:0; position:absolute "></object>

There is only GET request in FF, ME and Chrome but if I open my project in IE 11, it makes HEAD and GET requests same time. I couldn't find how to avoid. Is it normal? or am I in trouble? Saying trouble, because that svg file size is approximately 4.5 Mb. Network monitor looks like :

File     Protocol  Method    Type         Transferred   Cause
---------------------------------------------------------------
demo.svg  HTTP/2    HEAD  image/svg+xml     4.55 MB       -
demo.svg  HTTP/2    GET   image/svg+xml     4.55 MB    document

UPDATE-Workaround:

Well, i found an odd way. In fact a bit lagging while trying to get DOM elements but still better than make people download extra 4.5Mb every visit, right ?

I removed object element, loaded svg file via XMLHttpRequest  object and set the content of a div with responseText(returns whole svg file as text) property. Inevitably a loading image added just before call function to say: "hey it's gonna be lag for a sec don't worry."

By the way, i tried to use Blob object to create url for <object> element's data attribute but it doesn't work in IE with <object>.

I still want to know how to prevent HEAD request in IE.

Body:
This is because of <object>. Try using <img> instead:

<img src="/Content/images/demo.svg" style="width: 100%; height: 100%; display:block; right:0; position:absolute ">


问:
Is it possible to use assignment in a if statement?
I'd like to do something like below in Python 3:

import re

s = "abcde"

if match = re.search("abc(de)", s):
    print(match.group(1))
elif match = re.search("abc(fg)", s):
    print(match.group(1))
elif match = re.search("abc(hi)", s):
    print(match.group(1))
...
```

However, Python does not allow assignment in the condition clause of if statement and the code above cannot be executed.

How can I achieve this goal without getting errors? Thank you in advance.

答:
You can represent the regex patterns in better ways to perform this.

Something like:

```<code>match = re.search("abc(de|fg|hi)", s)

if match:
    print(match.group(1))
</code>```

If your regex patterns are slightly more complex, you can loop through the patterns to match individually and check:

```<code>patterns = [r"abc(de)", r"abc(fg)", r"abc(hi)"]

for pattern in patterns:
    match = re.search(pattern, s)
    if match:
        print(match.group(1))
</code>```

Body:
I'd like to do something like below in Python 3:

import re

s = "abcde"

if match = re.search("abc(de)", s):
    print(match.group(1))
elif match = re.search("abc(fg)", s):
    print(match.group(1))
elif match = re.search("abc(hi)", s):
    print(match.group(1))
...

However, Python does not allow assignment in the condition clause of if statement and the code above cannot be executed.

How can I achieve this goal without getting errors? Thank you in advance.

Body:
You can represent the regex patterns in better ways to perform this.

Something like:

match = re.search("abc(de|fg|hi)", s)

if match:
    print(match.group(1))

If your regex patterns are slightly more complex, you can loop through the patterns to match individually and check:

patterns = [r"abc(de)", r"abc(fg)", r"abc(hi)"]

for pattern in patterns:
    match = re.search(pattern, s)
    if match:
        print(match.group(1))


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答:
If you're the one creating the Exception, you shouldn't do anything with it.

Exceptions are your way of letting your consumers know that something went wrong that you can't properly recover from. You're giving them the chance to either correct the issue, log the error, or pass the Exception up the chain until something useful can be done with it.

ContentLicense: CC BY-SA 2.5


问:
Visual Studio NuGet Cannot Restore Packages
I have a large project that has about a dozen dependencies. I have tried to install them all but ran into an error from VS. I am using Visual Studio 2015

"An error occurred while trying to restore packages: Unable to find version '3.0.3.1' of package'Lucene.Net.Core'."

Now I have a solution which I can use that is by the same name as this package, but VS refuses to let me updates, remove, or change ANYTHING related to these packages and asks that I restore the packages. I am entirely lost here friends, what should I do?

P.S. the two sources I am using for my package sources are:

https://www.nuget.org/api/v2/

https://www.nuget.org/api/v2/curated-feeds/microsoftdotnet/

The same error occurs for Lucene.Net.Contrib, pstsdk.net, and various packages.

答:
One thing to check for is if your project is built on a version of the NET framework that is less than or equal to the target framework the package has.

If your project is a NET 4.5 based project, but the nuget package has a NET 4.5.2... then the package manager will error out.


问:
aggregate and concatenate the remaining unique elements in the output
I want to aggregate based on two columns and get the output with all the unique elements in each column. For example, in the dataset below, the blank space are NAs and I want to sum the trips based on o and d (which I did). But the element A in both o and d column does not have its other pair and hence not appearing in output. How can I include A once in both column and make trips 0 (corresponding to all As). The output matrix I want is also attached.
Thanks in advance!

CODE

```<code>df<-read.csv("smallexample.csv",header = TRUE)
df[["trips"]][is.na(df[["trips"]])] <- 0
#aggregating the trips
result1<-aggregate(trips ~o+d, data=df,sum)
#change from long to wide format
result2<-dcast(result1, o ~ d)
</code>```

DATA

```<code>structure(list(o = structure(c(2L, 1L, 4L, 2L, 1L, 5L, 1L, 6L,
2L, 1L, 4L, 5L, 2L, 4L, 6L, 3L), .Label = c("", "A", "B", "C",
"D", "E"), class = "factor"), d = structure(c(1L, 2L, 3L, 1L,
2L, 1L, 2L, 3L, 1L, 2L, 5L, 1L, 1L, 3L, 3L, 4L), .Label = c("",
"A", "B", "C", "E"), class = "factor"), trips = c(2, 3, 4, 5,
1.5, NA, NA, 1, 4, NA, 6, NA, 0.5, 6, 2, 1)), .Names = c("o",
"d", "trips"), class = "data.frame", row.names = c(NA, -16L))
</code>```

OUPUT:

```<code>structure(list(X = structure(1:5, .Label = c("A", "B", "C", "D",
"E"), class = "factor"), A = c(0L, 0L, 0L, 0L, 0L), B = c(0L,
0L, 10L, 0L, 3L), C = c(0L, 1L, 0L, 0L, 0L), D = c(0L, 0L, 0L,
0L, 0L), E = c(0L, 0L, 6L, 0L, 0L)), .Names = c("X", "A", "B",
"C", "D", "E"), class = "data.frame", row.names = c(NA, -5L))
</code>```

答:
```<code>library(dplyr)
library(reshape2)
lev <- LETTERS[1:5]
# Change the columns into factor to prevent dropping
df %>%
  mutate(o=factor(o, lev), d=factor(d, lev)) %>%
  filter(!is.na(o), !is.na(d)) %>%
  dcast(o ~ d, sum, drop=FALSE)

  o A  B C D E
1 A 0  0 0 0 0
2 B 0  0 1 0 0
3 C 0 10 0 0 6
4 D 0  0 0 0 0
5 E 0  3 0 0 0
</code>```

Body:
I want to aggregate based on two columns and get the output with all the unique elements in each column. For example, in the dataset below, the blank space are NAs and I want to sum the trips based on o and d (which I did). But the element A in both o and d column does not have its other pair and hence not appearing in output. How can I include A once in both column and make trips 0 (corresponding to all As). The output matrix I want is also attached.
Thanks in advance!

CODE

df<-read.csv("smallexample.csv",header = TRUE)
df[["trips"]][is.na(df[["trips"]])] <- 0
#aggregating the trips
result1<-aggregate(trips ~o+d, data=df,sum)
#change from long to wide format
result2<-dcast(result1, o ~ d)

DATA

structure(list(o = structure(c(2L, 1L, 4L, 2L, 1L, 5L, 1L, 6L,
2L, 1L, 4L, 5L, 2L, 4L, 6L, 3L), .Label = c("", "A", "B", "C",
"D", "E"), class = "factor"), d = structure(c(1L, 2L, 3L, 1L,
2L, 1L, 2L, 3L, 1L, 2L, 5L, 1L, 1L, 3L, 3L, 4L), .Label = c("",
"A", "B", "C", "E"), class = "factor"), trips = c(2, 3, 4, 5,
1.5, NA, NA, 1, 4, NA, 6, NA, 0.5, 6, 2, 1)), .Names = c("o",
"d", "trips"), class = "data.frame", row.names = c(NA, -16L))

OUPUT:

structure(list(X = structure(1:5, .Label = c("A", "B", "C", "D",
"E"), class = "factor"), A = c(0L, 0L, 0L, 0L, 0L), B = c(0L,
0L, 10L, 0L, 3L), C = c(0L, 1L, 0L, 0L, 0L), D = c(0L, 0L, 0L,
0L, 0L), E = c(0L, 0L, 6L, 0L, 0L)), .Names = c("X", "A", "B",
"C", "D", "E"), class = "data.frame", row.names = c(NA, -5L))


问:
Using C# get content from URL get this error “WebRequest does not contain a definition for GetRespone and …”
This code comes from Microsoft's documentation. I put this code in a Console app and a Windows Form app separately.

In the Console app, there is an error : “WebRequest does not contain a definition for GetRespone and …”

But in the Windows Form app, there is no error.

I really don't know why this happen. I am a beginner of C#, so this question may be stupid. But I feel very confused. Please explain to me.
Thank you!

Below are two screenshots for these two situation:

Here is the code.

```<code>using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}
</code>```

Update 1:

I was using Macbook Pro by the parallel virtual machine and the VS version is Enterprise 2017, .net framework is 4.5.2.

But after I shifted to a windows laptop, and the code is running perfect. Maybe the problem is the virtual machine ? ... It's very strange. It seems that I can't just trust to the virtual machine... Anyway, Thanks for helping !

Update 2:

It seems that I was too optimistic. When I use Visual Studio 2017, even I build it on Windows Laptop, the error still shown. So, I think there is a high chance that the problem is Visual Studio 2017...

答: It looks like reader.Close() is also complaining, which leads me to believe one or more of your referenced assemblies is missing.  Can you check the References folder in your project and see if any have a yellow warning icon on them?

Body:
This code comes from Microsoft's documentation. I put this code in a Console app and a Windows Form app separately.

In the Console app, there is an error : “WebRequest does not contain a definition for GetRespone and …”

But in the Windows Form app, there is no error.

I really don't know why this happen. I am a beginner of C#, so this question may be stupid. But I feel very confused. Please explain to me.
Thank you!

Below are two screenshots for these two situation:

Here is the code.

using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}

Update 1:

I was using Macbook Pro by the parallel virtual machine and the VS version is Enterprise 2017, .net framework is 4.5.2.

But after I shifted to a windows laptop, and the code is running perfect. Maybe the problem is the virtual machine ? ... It's very strange. It seems that I can't just trust to the virtual machine... Anyway, Thanks for helping !

Update 2:

It seems that I was too optimistic. When I use Visual Studio 2017, even I build it on Windows Laptop, the error still shown. So, I think there is a high chance that the problem is Visual Studio 2017...


问:
Converting numpy array into dataframe column?
How do I convert a numpy array into a dataframe column. Let's say I have created an empty dataframe, df, and I loop through code to create 5 numpy arrays. Each iteration of my for loop, I want to convert the numpy array I have created in that iteration into a column in my dataframe. Just to clarify, I do not want to create a new dataframe every iteration of my loop, I only want to add a column to the existing one. The code I have below is sketchy and not syntactically correct, but illustrates my point.

```<code>df = pd.dataframe()
for i in range(5):
   arr = create_numpy_arr(blah) # creates a numpy array
   df[i] = # convert arr to df column
</code>```

答:
That will work

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame()

for i in range(5):
    arr = np.random.rand(10)
    df[i] = arr
</code>```

Maybe a simpler way is to use the vectorization

```<code>arr = np.random.rand(10, 5)
df = pd.DataFrame(arr)
</code>```

Body:
How do I convert a numpy array into a dataframe column. Let's say I have created an empty dataframe, df, and I loop through code to create 5 numpy arrays. Each iteration of my for loop, I want to convert the numpy array I have created in that iteration into a column in my dataframe. Just to clarify, I do not want to create a new dataframe every iteration of my loop, I only want to add a column to the existing one. The code I have below is sketchy and not syntactically correct, but illustrates my point.

df = pd.dataframe()
for i in range(5):
   arr = create_numpy_arr(blah) # creates a numpy array
   df[i] = # convert arr to df column

Body:
That will work

import pandas as pd
import numpy as np

df = pd.DataFrame()

for i in range(5):
    arr = np.random.rand(10)
    df[i] = arr

Maybe a simpler way is to use the vectorization

arr = np.random.rand(10, 5)
df = pd.DataFrame(arr)


问:
Print to the same line and not a new line?
Basically I want to do the opposite of what this guy did... hehe.

Python Script: Print new line each time to shell rather than update existing line

I have a program that is telling me how far along it is.

```<code>for i in some_list:
    #do a bunch of stuff.
    print i/len(some_list)*100," percent complete"
</code>```

So if len(some_list) was 50, I'd get that last line printed 50 times over. I want to print one line and keep updating that line. I know I know this is probably the lamest question you'll read all day. I just can't figure out the four words I need to put into google to get the answer.

Update! I tried mvds' suggestion which SEEMED right. The new code

```<code>print percent_complete,"           \r",
</code>```

Percent complete is just a string (I was abstracting the first time now I an trying to be literal). The result now is that it runs the program, doesn't print ANYTHING until after the program is over, and then prints "100 percent complete" on one and only one line.

Without the carriage return (but with the comma, half of mvds' suggestion) it prints nothing until the end. And then prints:

```<code>0 percent complete     2 percent complete     3 percent complete     4 percent complete
</code>```

And so on. So now the new issue is that with the comma it doesn't print until the program is finished.

With the carriage return and no comma it behaves the exact same as with neither.

答:
```<code>import time
import sys

def update_pct(w_str):
    w_str = str(w_str)
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(" " * len(w_str))
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(w_str)
    sys.stdout.flush()

for pct in range(0, 101):
    update_pct("{n}%".format(n=str(pct)))
    time.sleep(0.1)
</code>```

\b will move the location of the cursor back one space

So we move it back all the way to the beginning of the line

We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one

So then we have to move the cursor back at the beginning of the line before we write our new data

Tested on Windows cmd using Python 2.7

ContentLicense: CC BY-SA 4.0

Body:
Basically I want to do the opposite of what this guy did... hehe.

Python Script: Print new line each time to shell rather than update existing line

I have a program that is telling me how far along it is.

for i in some_list:
    #do a bunch of stuff.
    print i/len(some_list)*100," percent complete"

So if len(some_list) was 50, I'd get that last line printed 50 times over. I want to print one line and keep updating that line. I know I know this is probably the lamest question you'll read all day. I just can't figure out the four words I need to put into google to get the answer.

Update! I tried mvds' suggestion which SEEMED right. The new code

print percent_complete,"           \r",

Percent complete is just a string (I was abstracting the first time now I an trying to be literal). The result now is that it runs the program, doesn't print ANYTHING until after the program is over, and then prints "100 percent complete" on one and only one line.

Without the carriage return (but with the comma, half of mvds' suggestion) it prints nothing until the end. And then prints:

0 percent complete     2 percent complete     3 percent complete     4 percent complete

And so on. So now the new issue is that with the comma it doesn't print until the program is finished.

With the carriage return and no comma it behaves the exact same as with neither.

Body:
import time
import sys

def update_pct(w_str):
    w_str = str(w_str)
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(" " * len(w_str))
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(w_str)
    sys.stdout.flush()

for pct in range(0, 101):
    update_pct("{n}%".format(n=str(pct)))
    time.sleep(0.1)

\b will move the location of the cursor back one space

So we move it back all the way to the beginning of the line

We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one

So then we have to move the cursor back at the beginning of the line before we write our new data

Tested on Windows cmd using Python 2.7


问:
C# - How to get Program Files (x86) on Windows 64 bit
I'm using:

```<code>FileInfo(
    System.Environment.GetFolderPath(
        System.Environment.SpecialFolder.ProgramFiles)
    + @"\MyInstalledApp"
</code>```

In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).

On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?

Body:
I'm using:

FileInfo(
    System.Environment.GetFolderPath(
        System.Environment.SpecialFolder.ProgramFiles)
    + @"\MyInstalledApp"

In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).

On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?

Body: Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)


问:
AngularCli Preconfigured build parameters
In an AngularCli project, there is the command ng build which works fine in a dev environment, but for release I need a few extra options like

```<code>ng build -prod --base-href /serversubfolder/ -aot
</code>```

Is there any way to add a sub script to angular cli so I can make a shorter command so I don't have to remember all these parameters. I.e.

```<code>ng build-release
</code>```

Which would be equivalent to the first statement? or am I stuck making a batch file for now?

答:
Configure in your package.json file.

```<code> "scripts": {
    "release":"ng build -prod --base-href /serversubfolder/ --aot"
  },
</code>```

now you need enter

```<code>npm run release
</code>```

Body:
In an AngularCli project, there is the command ng build which works fine in a dev environment, but for release I need a few extra options like

ng build -prod --base-href /serversubfolder/ -aot

Is there any way to add a sub script to angular cli so I can make a shorter command so I don't have to remember all these parameters. I.e.

ng build-release

Which would be equivalent to the first statement? or am I stuck making a batch file for now?

Body:
Configure in your package.json file.

 "scripts": {
    "release":"ng build -prod --base-href /serversubfolder/ --aot"
  },

now you need enter

npm run release


问:
python pexpect connected to server how to get the exact output of commands
In python I am connecting to a different server using

```<code>child = pexpect.spawn('ssh username@systemname')
</code>```

once it is connected, I would like to execute some other commands. how to get the exact output of other child commands like?

```<code> child.sendline("hostname")
</code>```

or Let me know if there is another way to do this.

答:
You may try the following and it would write to the filename mentioned:</p>

```<code>child.sendline('hostname')
child.logfile_read = open("<filename>", 'a')
child.expect('<what ever you expect after the command execution>')
</code>```

Body:
In python I am connecting to a different server using

child = pexpect.spawn('ssh username@systemname')

once it is connected, I would like to execute some other commands. how to get the exact output of other child commands like?

 child.sendline("hostname")

or Let me know if there is another way to do this.

Body:
You may try the following and it would write to the filename mentioned:

child.sendline('hostname')
child.logfile_read = open("<filename>", 'a')
child.expect('<what ever you expect after the command execution>')


问:
Implementation of Array data type in OCaml
I have very little knowledge about OCaml as a whole and just received an assignment to take one of the source files in the project and allow it to take a new data type (Array). I am not asking for someone to solve this problem for me, but instead I would appreciate someone walking me through this code. I would also appreciate any input on how difficult it is going to be to implement this new data type.

The file itself lacks a lot of documentation which doesn't make it any easier either.

```<code>(* * Types (hashconsed) *)

(* ** Imports *)
open Abbrevs
open Util

(* ** Identifiers *)

module Lenvar : (module type of Id) = Id

module Tysym : (module type of Id) = Id

module Groupvar : (module type of Id) = Id

module Permvar : (module type of Id) = Id

(* ** Types and type nodes *)

type ty = {
  ty_node : ty_node;
  ty_tag : int
}
and ty_node =
  | BS of Lenvar.id
  | Bool
  | G of Groupvar.id
  | TySym of Tysym.id
  | Fq
  | Prod of ty list
  | Int

(* ** Equality, hashing, and hash consing *)

let equal_ty : ty -> ty -> bool = (==)
let hash_ty t = t.ty_tag
let compare_ty t1 t2 = t1.ty_tag - t2.ty_tag

module Hsty = Hashcons.Make (struct
  type t = ty

  let equal t1 t2 =
    match t1.ty_node, t2.ty_node with
    | BS lv1, BS lv2                 -> Lenvar.equal lv1 lv2
    | Bool, Bool                     -> true
    | G gv1, G gv2                   -> Groupvar.equal gv1 gv2
    | TySym ts1, TySym ts2           -> Tysym.equal ts1 ts2
    | Fq, Fq                         -> true
    | Prod ts1, Prod ts2             -> list_eq_for_all2 equal_ty ts1 ts2
    | _                              -> false

  let hash t =
    match t.ty_node with
    | BS lv         -> hcomb 1 (Lenvar.hash lv)
    | Bool          -> 2
    | G gv          -> hcomb 3 (Groupvar.hash gv)
    | TySym gv      -> hcomb 4 (Tysym.hash gv)
    | Fq            -> 5
    | Prod ts       -> hcomb_l hash_ty 6 ts
    | Int           -> 7

  let tag n t = { t with ty_tag = n }
end)

(** Create [Map], [Set], and [Hashtbl] modules for types. *)
module Ty = StructMake (struct
  type t = ty
  let tag = hash_ty
end)
module Mty = Ty.M
module Sty = Ty.S
module Hty = Ty.H

(* ** Constructor functions *)

let mk_ty n = Hsty.hashcons {
  ty_node = n;
  ty_tag  = (-1)
}

let mk_BS lv = mk_ty (BS lv)

let mk_G gv = mk_ty (G gv)

let mk_TySym ts = mk_ty (TySym ts)

let mk_Fq = mk_ty Fq

let mk_Bool = mk_ty Bool

let mk_Int = mk_ty Int

let mk_Prod tys =
  match tys with
  | [t] -> t
  | _   -> mk_ty (Prod tys)

(* ** Indicator and destructor functions *)

let is_G ty = match ty.ty_node with
  | G _ -> true
  | _   -> false

let is_Fq ty = match ty.ty_node with
  | Fq -> true
  | _  -> false

let is_Prod ty = match ty.ty_node with
  | Prod _ -> true
  | _      -> false

let destr_G_exn ty =
  match ty.ty_node with
  | G gv -> gv
  | _    -> raise Not_found

let destr_BS_exn ty =
  match ty.ty_node with
  | BS lv -> lv
  | _     -> raise Not_found

let destr_Prod_exn ty =
  match ty.ty_node with
  | Prod ts -> ts
  | _       -> raise Not_found

let destr_Prod ty =
  match ty.ty_node with
  | Prod ts -> Some ts
  | _       -> None

(* ** Pretty printing *)

let pp_group fmt gv =
  if Groupvar.name gv = ""
  then F.fprintf fmt "G"
  else F.fprintf fmt "G_%s" (Groupvar.name gv)

let rec pp_ty fmt ty =
  match ty.ty_node with
  | BS lv             -> F.fprintf fmt "BS_%s" (Lenvar.name lv)
  | Bool              -> F.fprintf fmt "Bool"
  | Fq                -> F.fprintf fmt "Fq"
  | TySym ts          -> F.fprintf fmt "%s" (Tysym.name ts)
  | Prod ts           -> F.fprintf fmt "(%a)" (pp_list " * " pp_ty) ts
  | Int               -> F.fprintf fmt "Int"
  | G gv ->
    if Groupvar.name gv = ""
    then F.fprintf fmt "G"
    else F.fprintf fmt "G_%s" (Groupvar.name gv)
</code>```

答:
It's hard to walk through this code because quite a bit is missing (definitions of Id, Hashcons, StructMake). But in general this code manipulates data structures that represent types.

You can read about hash consing here: https://en.wikipedia.org/wiki/Hash_consing (which is what I just did myself). In essence it is a way of maintaining a canonical representation for a set of structures (in this case, structures representing types) so that two structures that are equal (having constituents that are equal) are represented by the identical value. This allows constant-time comparison for equality. When you do this with strings, it's called "interning" (a technique from Lisp I've used many times).

To add arrays, you need to know whether the array type will include the length of the array or just the type of its elements. The semi-mysterious type BS seems to include a length, which suggests you may want to include the length in your reprsentation.

If I were doing this project I would look for every occurence of Prod (which represents tuples) and I'd add a type representing Array in an analogous way. Instead of a list of constituent types (as for a tuple) you have one constituent type and (I would guess) a variable representing the length of the array.

Before starting out I'd look for some documentation, on what BS represents for one thing. I also have no idea what "groups" are, but maybe you could worry about it later.

Update

Here's what I mean by copying Prod. Keep in mind that I am basing this almost entirely on guesswork. So, many details (or even the entire idea) could be wrong.

The current definition of a type looks like this:

```<code>and ty_node =
  | BS of Lenvar.id
  | Bool
  | G of Groupvar.id
  | TySym of Tysym.id
  | Fq
  | Prod of ty list
  | Int
</code>```

If you add a representation for Array after Prod you get something like this:

```<code>and ty_node =
  | BS of Lenvar.id
  | Bool
  | G of Groupvar.id
  | TySym of Tysym.id
  | Fq
  | Prod of ty list
  | Array of Lenvar.id * ty
  | Int
</code>```

You would then go through the rest of the code adding support for the new Array variant. The compiler will help you find many of the places that need fixing.

Body:
I have very little knowledge about OCaml as a whole and just received an assignment to take one of the source files in the project and allow it to take a new data type (Array). I am not asking for someone to solve this problem for me, but instead I would appreciate someone walking me through this code. I would also appreciate any input on how difficult it is going to be to implement this new data type.

The file itself lacks a lot of documentation which doesn't make it any easier either.

(* * Types (hashconsed) *)

(* ** Imports *)
open Abbrevs
open Util

(* ** Identifiers *)

module Lenvar : (module type of Id) = Id

module Tysym : (module type of Id) = Id

module Groupvar : (module type of Id) = Id

module Permvar : (module type of Id) = Id

(* ** Types and type nodes *)

type ty = {
  ty_node : ty_node;
  ty_tag : int
}
and ty_node =
  | BS of Lenvar.id
  | Bool
  | G of Groupvar.id
  | TySym of Tysym.id
  | Fq
  | Prod of ty list
  | Int

(* ** Equality, hashing, and hash consing *)

let equal_ty : ty -> ty -> bool = (==)
let hash_ty t = t.ty_tag
let compare_ty t1 t2 = t1.ty_tag - t2.ty_tag

module Hsty = Hashcons.Make (struct
  type t = ty

  let equal t1 t2 =
    match t1.ty_node, t2.ty_node with
    | BS lv1, BS lv2                 -> Lenvar.equal lv1 lv2
    | Bool, Bool                     -> true
    | G gv1, G gv2                   -> Groupvar.equal gv1 gv2
    | TySym ts1, TySym ts2           -> Tysym.equal ts1 ts2
    | Fq, Fq                         -> true
    | Prod ts1, Prod ts2             -> list_eq_for_all2 equal_ty ts1 ts2
    | _                              -> false

  let hash t =
    match t.ty_node with
    | BS lv         -> hcomb 1 (Lenvar.hash lv)
    | Bool          -> 2
    | G gv          -> hcomb 3 (Groupvar.hash gv)
    | TySym gv      -> hcomb 4 (Tysym.hash gv)
    | Fq            -> 5
    | Prod ts       -> hcomb_l hash_ty 6 ts
    | Int           -> 7

  let tag n t = { t with ty_tag = n }
end)

(** Create [Map], [Set], and [Hashtbl] modules for types. *)
module Ty = StructMake (struct
  type t = ty
  let tag = hash_ty
end)
module Mty = Ty.M
module Sty = Ty.S
module Hty = Ty.H

(* ** Constructor functions *)

let mk_ty n = Hsty.hashcons {
  ty_node = n;
  ty_tag  = (-1)
}

let mk_BS lv = mk_ty (BS lv)

let mk_G gv = mk_ty (G gv)

let mk_TySym ts = mk_ty (TySym ts)

let mk_Fq = mk_ty Fq

let mk_Bool = mk_ty Bool

let mk_Int = mk_ty Int

let mk_Prod tys =
  match tys with
  | [t] -> t
  | _   -> mk_ty (Prod tys)

(* ** Indicator and destructor functions *)

let is_G ty = match ty.ty_node with
  | G _ -> true
  | _   -> false

let is_Fq ty = match ty.ty_node with
  | Fq -> true
  | _  -> false

let is_Prod ty = match ty.ty_node with
  | Prod _ -> true
  | _      -> false

let destr_G_exn ty =
  match ty.ty_node with
  | G gv -> gv
  | _    -> raise Not_found

let destr_BS_exn ty =
  match ty.ty_node with
  | BS lv -> lv
  | _     -> raise Not_found

let destr_Prod_exn ty =
  match ty.ty_node with
  | Prod ts -> ts
  | _       -> raise Not_found

let destr_Prod ty =
  match ty.ty_node with
  | Prod ts -> Some ts
  | _       -> None

(* ** Pretty printing *)

let pp_group fmt gv =
  if Groupvar.name gv = ""
  then F.fprintf fmt "G"
  else F.fprintf fmt "G_%s" (Groupvar.name gv)

let rec pp_ty fmt ty =
  match ty.ty_node with
  | BS lv             -> F.fprintf fmt "BS_%s" (Lenvar.name lv)
  | Bool              -> F.fprintf fmt "Bool"
  | Fq                -> F.fprintf fmt "Fq"
  | TySym ts          -> F.fprintf fmt "%s" (Tysym.name ts)
  | Prod ts           -> F.fprintf fmt "(%a)" (pp_list " * " pp_ty) ts
  | Int               -> F.fprintf fmt "Int"
  | G gv ->
    if Groupvar.name gv = ""
    then F.fprintf fmt "G"
    else F.fprintf fmt "G_%s" (Groupvar.name gv)

Body:
It's hard to walk through this code because quite a bit is missing (definitions of Id, Hashcons, StructMake). But in general this code manipulates data structures that represent types.

You can read about hash consing here: https://en.wikipedia.org/wiki/Hash_consing (which is what I just did myself). In essence it is a way of maintaining a canonical representation for a set of structures (in this case, structures representing types) so that two structures that are equal (having constituents that are equal) are represented by the identical value. This allows constant-time comparison for equality. When you do this with strings, it's called "interning" (a technique from Lisp I've used many times).

To add arrays, you need to know whether the array type will include the length of the array or just the type of its elements. The semi-mysterious type BS seems to include a length, which suggests you may want to include the length in your reprsentation.

If I were doing this project I would look for every occurence of Prod (which represents tuples) and I'd add a type representing Array in an analogous way. Instead of a list of constituent types (as for a tuple) you have one constituent type and (I would guess) a variable representing the length of the array.

Before starting out I'd look for some documentation, on what BS represents for one thing. I also have no idea what "groups" are, but maybe you could worry about it later.

Update

Here's what I mean by copying Prod. Keep in mind that I am basing this almost entirely on guesswork. So, many details (or even the entire idea) could be wrong.

The current definition of a type looks like this:

and ty_node =
  | BS of Lenvar.id
  | Bool
  | G of Groupvar.id
  | TySym of Tysym.id
  | Fq
  | Prod of ty list
  | Int

If you add a representation for Array after Prod you get something like this:

and ty_node =
  | BS of Lenvar.id
  | Bool
  | G of Groupvar.id
  | TySym of Tysym.id
  | Fq
  | Prod of ty list
  | Array of Lenvar.id * ty
  | Int

You would then go through the rest of the code adding support for the new Array variant. The compiler will help you find many of the places that need fixing.


问:
bash extglob range-or-value matching same file name twice
Given these files:

```<code>$ ls
file1  file2  file21  file3  fileFoo
</code>```

I expected this globbing pattern (bash with extglob enabled):

```<code>$ ls file?({1..2}|Foo)
</code>```

to output:

```<code>file1  file2  fileFoo
</code>```

but instead I got this with fileFoo listed twice:

```<code>$ ls file?({1..2}|Foo)
file1  file2  fileFoo  fileFoo
</code>```

Neither side of the "or" produces unexpected results:

```<code>$ ls file?({1..2})
file1  file2

$ ls file?(Foo)
fileFoo
</code>```

so why is fileFoo printed twice when I "or" the expressions and what would be the correct globbing pattern to match a range (e.g. 1-2 above but could be 17-593 or any other range) or some other unrelated string (e.g. Foo above)?

```<code>$ bash --version
GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin)
</code>```

答:
Expansion is performed before globbing:

```<code>file?({1..2}|Foo)
</code>```

becomes

```<code>file?(1|Foo) file?(2|Foo)
</code>```

and then both arguments are globbed.

Using only expansion as follows works as expected, but will trip up nullglob and the like:

```<code>file{{1..2},Foo}
</code>```

Body:
Given these files:

$ ls
file1  file2  file21  file3  fileFoo

I expected this globbing pattern (bash with extglob enabled):

$ ls file?({1..2}|Foo)

to output:

file1  file2  fileFoo

but instead I got this with fileFoo listed twice:

$ ls file?({1..2}|Foo)
file1  file2  fileFoo  fileFoo

Neither side of the "or" produces unexpected results:

$ ls file?({1..2})
file1  file2

$ ls file?(Foo)
fileFoo

so why is fileFoo printed twice when I "or" the expressions and what would be the correct globbing pattern to match a range (e.g. 1-2 above but could be 17-593 or any other range) or some other unrelated string (e.g. Foo above)?

$ bash --version
GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin)

Body:
Expansion is performed before globbing:

file?({1..2}|Foo)

becomes

file?(1|Foo) file?(2|Foo)

and then both arguments are globbed.

Using only expansion as follows works as expected, but will trip up nullglob and the like:

file{{1..2},Foo}


答: Another thing to check is that the package manager configuration settings in visual studio list the public nuget feed (and if the feed is enabled too).</p>

Title: Visual Studio NuGet Cannot Restore Packages

Body:
I have a large project that has about a dozen dependencies. I have tried to install them all but ran into an error from VS. I am using Visual Studio 2015

"An error occurred while trying to restore packages: Unable to find version '3.0.3.1' of package'Lucene.Net.Core'."

Now I have a solution which I can use that is by the same name as this package, but VS refuses to let me updates, remove, or change ANYTHING related to these packages and asks that I restore the packages. I am entirely lost here friends, what should I do?

P.S. the two sources I am using for my package sources are:

https://www.nuget.org/api/v2/

https://www.nuget.org/api/v2/curated-feeds/microsoftdotnet/

The same error occurs for Lucene.Net.Contrib, pstsdk.net, and various packages.


答: In short, the point is to indicate that something which shouldn't have happened did indeed happen.</p>

Title: What's the point of throwing an exception?

Body: I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!?


问:
MySQL optimization for insert and retrieve only
Our applications read data from sensor complexes and write them to a database, together with their timestamp. New data are inserted about 5 times per second per sensor complex (1..10 complexes per database server; data contain 2 blobs of typically 25kB and 50kB, resp.), they are read from 1..3 machines (simple reads like: select * from table where sensorId=?sensorId and timestamp>?lastTimestamp). Rows are never updated; no reports are created on the database side; old rows are deleted after several days. Only one of the tables receives occasional updates.

The primary index of that main table is an autogenerated id, with additional indices for sensorid and timestamp.

The performance is currently abysmal. The deletion of old data takes hours(!), and many data packets are not sent to the database because the insertion process takes longer than the interval between sensor reads. How can we optimize the performance of the database in such a specific scenario?

Setting the transaction isolation level to READ_COMMITTED looks promising, and also innodb_lock_timeout seems useful. Can you suggest further settings useful in our specific scenario?

Can we gain further possibilities when we get rid of the table which receives updates?

答:
Deleting old data -- PARTITION BY RANGE(TO_DAYS(...)) lets you DROP PARTITION a looooot faster than doing DELETEs.

More details:  http://mysql.rjweb.org/doc.php/partitionmaint

And that SELECT you mentioned needs this 'composite' index:

```<code>INDEX(sensorId, timestamp)
</code>```

Body:
Deleting old data -- PARTITION BY RANGE(TO_DAYS(...)) lets you DROP PARTITION a looooot faster than doing DELETEs.

More details:  http://mysql.rjweb.org/doc.php/partitionmaint

And that SELECT you mentioned needs this 'composite' index:

INDEX(sensorId, timestamp)


问:
Casting unix time to date in Presto
I have timestamps stored in time since epoch (ms) and I would like to query and display results using a date formatted like 'yyyy-mm-dd'.</p>

答:
cast(from_unixtime(unixtime) as date)

See https://prestodb.io/docs/current/functions/datetime.html for more datetime functions.

Title: Casting unix time to date in Presto


问:
polymer-cli installation failure on Ubuntu
No matter what I try, every time I try to install polymer-cli, it always comes up with a PERMISSION_DENIED error.

```<code>bradley@gurulaptop:~$ sudo npm -g install polymer-cli
npm WARN deprecated bower@1.8.0: ..psst! While Bower is maintained, we recommend Yarn and Webpack for *new* front-end projects! Yarn's advantage is security and reliability, and Webpack's is support for both CommonJS and AMD projects. Currently there's no migration path but we hope you'll help us figure out one.
npm WARN deprecated @types/assert@0.0.29: See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/12826
/usr/bin/polymer -> /usr/lib/node_modules/polymer-cli/bin/polymer.js

> wd@1.2.0 install /usr/lib/node_modules/polymer-cli/node_modules/wd
> node scripts/build-browser-scripts

/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:90
                    throw err0;
                    ^

Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/polymer-cli/node_modules/wd/build'
    at Object.fs.mkdirSync (fs.js:877:18)
    at sync (/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:71:13)
    at Object.<anonymous> (/usr/lib/node_modules/polymer-cli/node_modules/wd/scripts/build-browser-scripts.js:6:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! wd@1.2.0 install: `node scripts/build-browser-scripts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the wd@1.2.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bradley/.npm/_logs/2017-06-06T13_10_23_400Z-debug.log
</code>```

How can I solve this?

答:
There seems to be a problem installing the package wd as root. One way to work around this fact is to do a non global npm install of polymer-cli and use the local bin path.

```<code>$ cd ~
$ npm install polymer-cli
$ ~/node_modules/.bin/polymer --version
1.1.0
</code>```

After which you may either copy all dependencies to /usr/lib/node_modules and /usr/bin/ or create symbolic links to the executables (which may be easier for a singe user system).

```<code>$ sudo ln -s "$(readlink -f ~/node_modules/.bin/wd)" /usr/bin/wd
$ sudo ln -s "$(readlink -f ~/node_modules/.bin/polymer)" /usr/bin/polymer
</code>```

When the path /usr/bin/polymer exists you should be able to use the polymer command as expected.

Body:
No matter what I try, every time I try to install polymer-cli, it always comes up with a PERMISSION_DENIED error.

bradley@gurulaptop:~$ sudo npm -g install polymer-cli
npm WARN deprecated bower@1.8.0: ..psst! While Bower is maintained, we recommend Yarn and Webpack for *new* front-end projects! Yarn's advantage is security and reliability, and Webpack's is support for both CommonJS and AMD projects. Currently there's no migration path but we hope you'll help us figure out one.
npm WARN deprecated @types/assert@0.0.29: See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/12826
/usr/bin/polymer -> /usr/lib/node_modules/polymer-cli/bin/polymer.js

> wd@1.2.0 install /usr/lib/node_modules/polymer-cli/node_modules/wd
> node scripts/build-browser-scripts

/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:90
                    throw err0;
                    ^

Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/polymer-cli/node_modules/wd/build'
    at Object.fs.mkdirSync (fs.js:877:18)
    at sync (/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:71:13)
    at Object.<anonymous> (/usr/lib/node_modules/polymer-cli/node_modules/wd/scripts/build-browser-scripts.js:6:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! wd@1.2.0 install: `node scripts/build-browser-scripts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the wd@1.2.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bradley/.npm/_logs/2017-06-06T13_10_23_400Z-debug.log

How can I solve this?

Body:
There seems to be a problem installing the package wd as root. One way to work around this fact is to do a non global npm install of polymer-cli and use the local bin path.

$ cd ~
$ npm install polymer-cli
$ ~/node_modules/.bin/polymer --version
1.1.0

After which you may either copy all dependencies to /usr/lib/node_modules and /usr/bin/ or create symbolic links to the executables (which may be easier for a singe user system).

$ sudo ln -s "$(readlink -f ~/node_modules/.bin/wd)" /usr/bin/wd
$ sudo ln -s "$(readlink -f ~/node_modules/.bin/polymer)" /usr/bin/polymer

When the path /usr/bin/polymer exists you should be able to use the polymer command as expected.


问:
google-api-python-client bug with media downloading
Used google-api-python-client==1.6.2

```<code>fh = io.BytesIO()
request = self.drive_service.files().export_media(
    fileId='1fwshPVKCACXgNxJtmGN94X-9RRrukiDs9q4s-n0nGlM',
    mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
downloader = MediaIoBaseDownload(fh, request, chunksize=1024)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download ", status.progress(), downloader._progress, downloader._total_size, done
</code>```

Output:

```<code>Download  0.0 973060 None False
Download  0.0 1946120 None False
Download  0.0 2919180 None False
Download  0.0 3892240 None False
Download  0.0 4865300 None False
Download  0.0 5838360 None False
Download  0.0 6811420 None False
Download  0.0 7784480 None False
Download  0.0 8757540 None False
...
</code>```

File size of downloading file is 973060 bytes. So, the library ignores chunksize parameter and did not stop. Never stop.

So, anyone can tell me Are my requirements too high or Is the library so bad?

答:
How about following sample?

Sample :

```<code>request = self.drive_service.files().export_media(
    fileId='1fwshPVKCACXgNxJtmGN94X-9RRrukiDs9q4s-n0nGlM',
    mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
).execute()
with open('sample.docx', 'wb') as f:
    f.write(request)
</code>```

If this doesn't work, I'm sorry.

Body:
Used google-api-python-client==1.6.2

fh = io.BytesIO()
request = self.drive_service.files().export_media(
    fileId='1fwshPVKCACXgNxJtmGN94X-9RRrukiDs9q4s-n0nGlM',
    mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
downloader = MediaIoBaseDownload(fh, request, chunksize=1024)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download ", status.progress(), downloader._progress, downloader._total_size, done

Output:

Download  0.0 973060 None False
Download  0.0 1946120 None False
Download  0.0 2919180 None False
Download  0.0 3892240 None False
Download  0.0 4865300 None False
Download  0.0 5838360 None False
Download  0.0 6811420 None False
Download  0.0 7784480 None False
Download  0.0 8757540 None False
...

File size of downloading file is 973060 bytes. So, the library ignores chunksize parameter and did not stop. Never stop.

So, anyone can tell me Are my requirements too high or Is the library so bad?

Body:
How about following sample?

Sample :

request = self.drive_service.files().export_media(
    fileId='1fwshPVKCACXgNxJtmGN94X-9RRrukiDs9q4s-n0nGlM',
    mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
).execute()
with open('sample.docx', 'wb') as f:
    f.write(request)

If this doesn't work, I'm sorry.


问:
Concept of functional interface
When I'm shooting a glance at lambda expressions, the book touches on a functional interface that has only one abstract method. My issue addresses on that quiz question

```<code>/* Which of these interfaces are functional interfaces? */
public interface Adder{
   int add(int a, int b);
}
public interface SmartAdder extends Adder{
   int add(double a, double b);
}
public interface Nothing{
}
</code>```

I know the last one is not, but I think the first and second ones should be functional interface. But the book says second one is not. Why? Doesn't it overrides add method? So even in second, isn't there only one abstract method?

答:
In Java, a method in a subtype overrides a method of a parent type when it has the same signature. Signature means both name and arguments of the method. In particular, arguments must be of the same exact type and must be declared in the same exact order in both methods, i.e. the types of the arguments of the method declared in the subtype can't be subtypes or types wider than the types of the arguments declared in the parent type's method.

So, in your SmartAdder interface, the method with signature add(double a, double b) does not override the method add(int a, int b) of your Adder interface, because double is wider than int. When a type has two or more methods with the same name but with different arguments, it is called method overloading, and it's totally different than method overriding.

This is why SmartAdder ends up having two abstract methods, hence it's not a functional interface (which requires the type to have only one abstract method).

Title: Concept of functional interface

Body:
When I'm shooting a glance at lambda expressions, the book touches on a functional interface that has only one abstract method. My issue addresses on that quiz question

/* Which of these interfaces are functional interfaces? */
public interface Adder{
   int add(int a, int b);
}
public interface SmartAdder extends Adder{
   int add(double a, double b);
}
public interface Nothing{
}

I know the last one is not, but I think the first and second ones should be functional interface. But the book says second one is not. Why? Doesn't it overrides add method? So even in second, isn't there only one abstract method?


问:
Import Unity Classes into Existing Android Project
As the title says, I have an existing Android project and I want to import Unity classes.jar so I can access the UnityPlayer.UnitySendMessage.

I found this other question with similar goal, but the answers were unintelligible or unhelpful.

I also found this on the Unity forums, but it is apparently very outdated (2011).

Essentially, all I'm trying to do is:

Open up an Android application.

Select which scene (or, preferably, more than one scene) I want to view from the Unity app.

Launch the Unity GearVR application.

Play the selected scene(s).

I've already got steps 1 and 3 working, and steps 2 and 4 I'm making work by loading each scene up as a different APK and launching a specific APK depending on which scene I want to view, but, ideally, I could host all the scenes in a single application so I could then watch several off the scenes in a row (and also so I could cut down significantly on memory usage).

I've found some tutorials on using UnityPlayer.UnitySendMessage, so I think I can get it working if I can only get Android Studio to recognize and use UnityPlayer.UnitySendMessage, but if you have any other ideas, I appreciate those as well!

答:
I've found some tutorials on using UnityPlayer.UnitySendMessage, so I
  think I can get it working if I can only get Android Studio to
  recognize and use UnityPlayer.UnitySendMessage

Get classes.jar from one of the sub-folders from

```<code><UnityInstallationDirectory>\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono
</code>```

or

```<code><UnityInstallationDirectory>\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp
</code>```

depending on if you are using mono or IL2CPP as Scripting Backend to build your Android Project.

Import it into Android Studio. Right-click on it and click Add As library and Android Studio should add it as library. See this if you are still confused. You can now use UnityPlayer.UnitySendMessage.

As for the rest of your question, I think that you should look into this answer. It explains how you can show Unity scene in a sub-view. That is another way to get what you want.

Body:
I've found some tutorials on using UnityPlayer.UnitySendMessage, so I
  think I can get it working if I can only get Android Studio to
  recognize and use UnityPlayer.UnitySendMessage

Get classes.jar from one of the sub-folders from

<UnityInstallationDirectory>\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono

or

<UnityInstallationDirectory>\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp

depending on if you are using mono or IL2CPP as Scripting Backend to build your Android Project.

Import it into Android Studio. Right-click on it and click Add As library and Android Studio should add it as library. See this if you are still confused. You can now use UnityPlayer.UnitySendMessage.

As for the rest of your question, I think that you should look into this answer. It explains how you can show Unity scene in a sub-view. That is another way to get what you want.


答:
It's being interpreted as:

```<code>ls file?(1|Foo) file?(2|Foo)
</code>```

The range is being expanded and then each value is combined with |Foo.

So when each pattern is expanded, you get both the file ending with a number and the file ending with Foo.

Try:

```<code>ls file{{1..2},Foo)
</code>```

Title: bash extglob range-or-value matching same file name twice

Body:
It's being interpreted as:

ls file?(1|Foo) file?(2|Foo)

The range is being expanded and then each value is combined with |Foo.

So when each pattern is expanded, you get both the file ending with a number and the file ending with Foo.

Try:

ls file{{1..2},Foo)


问:
String Manipulation: Find the discount of a price/number while in a String in JavaScript
I had a technical interview and this question was particularly hard for me to answer. Not sure how to go about this issue, would really appreciate if someone helped me figure out this question.

You have a string that states the price of an item. You want to return a string with the all the numbers 15% off the original number.

```<code>example.)

if an item was 15% off

input string:

str1 = "This person bought an iphone for $500 and a macbook for $1400"

output string:

str2 = "This person bought an iphone for $425 and a macbook for $1190"
</code>```

I know I should split the string, and probably locate all the numbers that proceeds a "$" symbol but I am not sure how to go from there.

答:
Based on @goat's idea</p>

```<code>var x = "This person bought an iphone for $500 and a macbook for $1400";

function getDiscount(str) {
  var origPrices = str.match(/(\d{1,})/gi);
  var discountPrices = origPrices.map(function(value) {
     return value - value * 0.15;
  });
  origPrices.forEach(function(currentvalue, index){
    str = str.replace(currentvalue, discountPrices[index]);
  });
  return str;
}
getDiscount(x);
</code>```

Body:
I had a technical interview and this question was particularly hard for me to answer. Not sure how to go about this issue, would really appreciate if someone helped me figure out this question.

You have a string that states the price of an item. You want to return a string with the all the numbers 15% off the original number.

example.)

if an item was 15% off

input string:

str1 = "This person bought an iphone for $500 and a macbook for $1400"

output string:

str2 = "This person bought an iphone for $425 and a macbook for $1190"

I know I should split the string, and probably locate all the numbers that proceeds a "$" symbol but I am not sure how to go from there.

Body:
Based on @goat's idea

var x = "This person bought an iphone for $500 and a macbook for $1400";

function getDiscount(str) {
  var origPrices = str.match(/(\d{1,})/gi);
  var discountPrices = origPrices.map(function(value) {
     return value - value * 0.15;
  });
  origPrices.forEach(function(currentvalue, index){
    str = str.replace(currentvalue, discountPrices[index]);
  });
  return str;
}
getDiscount(x);


问:
Where does `yarn run react` fit into the Relay workflow?
I'm trying to get Relay working with my React Native app and talking to my GraphQL server. I think I'm missing some pieces of understanding.

I'm following the instructions at https://facebook.github.io/relay/docs/relay-modern.html

It details the yarn commands to set up relay and the babel plugin. I added the "relay" script to my package.json like this:

"relay": "relay-compiler --src ./App --schema ./App/Data/schema.graphql"

But, when I run yarn run relay I get

Error: --schema path does not exist: /Users/user/dev/react-native-app/App/Data/schema.graphql.

Yeah. It doesn't exist. Isn't that what this command is supposed to generate? That documentation page doesn't explain what this command outputs, nor what it needs as input. How can I get this command working correctly? Do I really have to hand-write a schema when it already exists on the server?

答:
EDIT, for php

Given that you are generating your schema on a PHP server, you can generate the .graphql file by creating a Node.js script to:

Send an introspection query to your /graphql endpoint

Pass the result to buildClientSchema

Call printSchema with it and write it on the disk

General usage with graphql-js

As far as I know, you effectively need your schema printed in GraphQL language. You can have a look at printSchema for this, to provide it to the relay-compiler.

printSchema will do the JS Object -> Schema Language conversion. If you already have your schema in Schema Language, this is what you need to provide to the relay-compiler.

It may be possible to use directly the JS Object schema, but I don't know how.

For a detailed explanation of the complete setup, you can look at my other answer here.


问:
Store a number in an integer string and recall it in a later action
I'm currently trying to get a UISlider to work.

I'm trying to set the strings value as 8 to start off with on view load.

Then when the slider changes value I want the string to update with that number, and then later on I can use the value in the string for a setDuration:## later on in another action.

Any ideas?

答: I ended up using CAFloat..</p>

LastEditorDisplayName: Chris Hanson

Body: I ended up using CAFloat..


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答: To signal to the next level up of abstraction that there is a problem, and alter its logical flow to account for the problem.</p>


问:
Using C# get content from URL get this error “WebRequest does not contain a definition for GetRespone and …”
This code comes from Microsoft's documentation. I put this code in a Console app and a Windows Form app separately.

In the Console app, there is an error : “WebRequest does not contain a definition for GetRespone and …”

But in the Windows Form app, there is no error.

I really don't know why this happen. I am a beginner of C#, so this question may be stupid. But I feel very confused. Please explain to me.
Thank you!

Below are two screenshots for these two situation:

Here is the code.

```<code>using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}
</code>```

Update 1:

I was using Macbook Pro by the parallel virtual machine and the VS version is Enterprise 2017, .net framework is 4.5.2.

But after I shifted to a windows laptop, and the code is running perfect. Maybe the problem is the virtual machine ? ... It's very strange. It seems that I can't just trust to the virtual machine... Anyway, Thanks for helping !

Update 2:

It seems that I was too optimistic. When I use Visual Studio 2017, even I build it on Windows Laptop, the error still shown. So, I think there is a high chance that the problem is Visual Studio 2017...

答:
You must use an HttpWebRequest and HttpWebResponse, not a WebRequest:

```<code>using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}
</code>```

WebRequest.Create will create a derived class of WebRequest with the exact implementation (HttpWebRequest, FtpWebRequest and so on) for the specified address, so you must cast to the concrete implementation to access the concrete functions.

Also, as HttpWebRequest.GetResponse returns the concrete implementation of WebResponse you must cast it, in this case to HttpWebResponse.

Body:
This code comes from Microsoft's documentation. I put this code in a Console app and a Windows Form app separately.

In the Console app, there is an error : “WebRequest does not contain a definition for GetRespone and …”

But in the Windows Form app, there is no error.

I really don't know why this happen. I am a beginner of C#, so this question may be stupid. But I feel very confused. Please explain to me.
Thank you!

Below are two screenshots for these two situation:

Here is the code.

using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}

Update 1:

I was using Macbook Pro by the parallel virtual machine and the VS version is Enterprise 2017, .net framework is 4.5.2.

But after I shifted to a windows laptop, and the code is running perfect. Maybe the problem is the virtual machine ? ... It's very strange. It seems that I can't just trust to the virtual machine... Anyway, Thanks for helping !

Update 2:

It seems that I was too optimistic. When I use Visual Studio 2017, even I build it on Windows Laptop, the error still shown. So, I think there is a high chance that the problem is Visual Studio 2017...

Body:
You must use an HttpWebRequest and HttpWebResponse, not a WebRequest:

using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}

WebRequest.Create will create a derived class of WebRequest with the exact implementation (HttpWebRequest, FtpWebRequest and so on) for the specified address, so you must cast to the concrete implementation to access the concrete functions.

Also, as HttpWebRequest.GetResponse returns the concrete implementation of WebResponse you must cast it, in this case to HttpWebResponse.


问:
What is the fastest way to insert a new has relation to an existing entry?
I need to insert a finance_entity for each club in a one to one relationship.
I decided to run this in the mysql server, because single inserts are even slower. How could I optimize this to run faster? Is there some way to hack insert select to do this?

I cannot put the club_id on finance_entity, since more then one relation points to it.

```<code>alter table clubs add column finance_entity_id int unsigned null after id;
DELIMITER !
drop procedure if exists create_entities!
create procedure create_entities()
begin
    create_entities_for_club: loop
        set @club_key = (select id from clubs where finance_entity_id is null limit 1);

        insert into finance_entity (id) value (null);
        update clubs set finance_entity_id = last_insert_id() where id = @club_key;

        if @club_key is null then
            leave create_entities_for_club;
        end if;
    end loop create_entities_for_club;
end!
call create_entities_for_club()!

DELIMITER ;

alter table clubs change column finance_entity_id finance_entity_id int unsigned not null;
alter table clubs add unique (finance_entity_id);
</code>```

答: If it is 1:1 with an existing table, simply have the same PRIMARY KEY, but without calling it AUTO_INCREMENT.

Body:
I need to insert a finance_entity for each club in a one to one relationship.
I decided to run this in the mysql server, because single inserts are even slower. How could I optimize this to run faster? Is there some way to hack insert select to do this?

I cannot put the club_id on finance_entity, since more then one relation points to it.

alter table clubs add column finance_entity_id int unsigned null after id;
DELIMITER !
drop procedure if exists create_entities!
create procedure create_entities()
begin
    create_entities_for_club: loop
        set @club_key = (select id from clubs where finance_entity_id is null limit 1);

        insert into finance_entity (id) value (null);
        update clubs set finance_entity_id = last_insert_id() where id = @club_key;

        if @club_key is null then
            leave create_entities_for_club;
        end if;
    end loop create_entities_for_club;
end!
call create_entities_for_club()!

DELIMITER ;

alter table clubs change column finance_entity_id finance_entity_id int unsigned not null;
alter table clubs add unique (finance_entity_id);


问:
How to pre sort Firebase Database for faster performance (Android)
I want my Firebase Database to be sorted right at the moment a new variable enters.
My goal is to sort an integer representing the subscriber ammount from biggest to lowest, so that when I populate my recyclerview (Top subscribed account) I don't have to check against every value in my Database.

Is there a way of doing something like that, or a way better solution to my problem?

答:
The Firebase database sort all the childs using alphabetical order. So using only the Firebase reference, you always get yours "Top subscribed accounts" in the alphabetical order of his Ids.

Firebase provide helpful methods to filter or order your querys. Check firebase.database.Reference especially the method orderByChild

Making querys with the correct filtering (order), it's the way to get the Firebase data in the way you want.


问:
Explain lambda expression with new class instance
In Echo bot with state example Post([FromBody] Activity activity) method calls Func<IDialog<object>> type delegate:

```<code>await Conversation.SendAsync(activity, () => new EchoDialog());
</code>```

where EchoDialog has protected int count = 1; member which counts each call to Task StartAsync(). Correct wor only possible if new EchoDialog() executes only once so lambda deals with same object every call of await Conversation.SendAsync(). So lambda created only once and remains the same for each Post([FromBody] Activity activity) call, right? How lambda works here? Thanks in advance!

Have not find right answer in Troelsen book, :) Stackoverflow, MS docs, etc.

答:
A new EchoDialog will be created each time the delegate is executed, which will be an implementation detail of SendAsync.  Basically, you're passing a method definition to SendAsync and it will call that method one or more times.  Each time it calls delegate, the code on the right side of the => will be executed.

If you want to ensure the same instance of EchoDialog is returned for all calls, you could do this:

```<code>var myDialog = new EchoDialog();

await Conversation.SendAsync(activity, () => myDialog);
</code>```

This will return the myDialog instance every time instead of creating a new instance each time.

Update

According to the documentation of Conversation.SendAsyc, the delegate (which is referred to as the parameter MakeRoot ) is only called for new conversations and that the EchoDialog object is serialized and stored for future calls on that conversation.

The MakeRoot factory method is invoked for new conversations only, because existing conversations have the dialog stack and state serialized in the IMessageActivity data.

Body:
In Echo bot with state example Post([FromBody] Activity activity) method calls Func<IDialog<object>> type delegate:

await Conversation.SendAsync(activity, () => new EchoDialog());

where EchoDialog has protected int count = 1; member which counts each call to Task StartAsync(). Correct wor only possible if new EchoDialog() executes only once so lambda deals with same object every call of await Conversation.SendAsync(). So lambda created only once and remains the same for each Post([FromBody] Activity activity) call, right? How lambda works here? Thanks in advance!

Have not find right answer in Troelsen book, :) Stackoverflow, MS docs, etc.

Body:
A new EchoDialog will be created each time the delegate is executed, which will be an implementation detail of SendAsync.  Basically, you're passing a method definition to SendAsync and it will call that method one or more times.  Each time it calls delegate, the code on the right side of the => will be executed.

If you want to ensure the same instance of EchoDialog is returned for all calls, you could do this:

var myDialog = new EchoDialog();

await Conversation.SendAsync(activity, () => myDialog);

This will return the myDialog instance every time instead of creating a new instance each time.

Update

According to the documentation of Conversation.SendAsyc, the delegate (which is referred to as the parameter MakeRoot ) is only called for new conversations and that the EchoDialog object is serialized and stored for future calls on that conversation.

The MakeRoot factory method is invoked for new conversations only, because existing conversations have the dialog stack and state serialized in the IMessageActivity data.


问:
Generic id-referenced json parsing in javascript
In a project I'm working on I'm calling an rest-api that returns json as follows:

```<code>[
   {
      "id":0,
      "username":"someone0",
      "areas":[

      ],
      "role":{
         "id":2,
         "name":"somerole2",
         "users":null
      }
   },
   {
      "id":1,
      "username":"someone1",
      "areas":[

      ],
      "role":{
         "id":1,
         "name":"somerole1",
         "users":null
      }
   },
   {
      "id":3,
      "username":"someone3",
      "areas":[

      ],
      "role":1
   }
]
</code>```

As you can see user 'someone1' and 'someone3' both carry the same role object, but the second time it's referenced (at someone3) it is only referenced by it's id.

Because every response from this api is formatted this way, I'm looking for a generic way to fix this (replace the id-reference with the full object) in pure javascript.

Any common solutions to the seemingly common issue?

PS: I'm sorry for the title, I don't know the right term (suggestions are welcome).

答:
You could simply map a function that makes these corrections to the initial value. Something like this should work if I understand what you are going for:

```<code>response = response.map( function(x){
    if( (typeof x.role) == "number"  )
        x.role = { id : x.role };
    return x;
});
</code>```

This however will not give you the names and users field. If this is important, I recommend we iterate through the data once and make a list of roles, then go back and fill in the gaps. This would look like:

```<code>roles = {};

response.forEach( function(x){
    if( (typeof x.role) != "number" )
        roles[x.role.id] = x.role;
});

response = response.map( function(x){
    if( (typeof x.role) == "number"  )
        x.role = roles[x.role];
    return x;
});
</code>```

The output of running that on your data is:

```<code>[
  { id: 0,
    username: 'someone0',
    areas: [],
    role: { id: 2, name: 'somerole2', users: null }
  },
  { id: 1,
    username: 'someone1',
    areas: [],
    role: { id: 1, name: 'somerole1', users: null }
  },
  { id: 3,
    username: 'someone3',
    areas: [],
    role: { id: 1, name: 'somerole1', users: null }
  }
]
</code>```

Body:
In a project I'm working on I'm calling an rest-api that returns json as follows:

[
   {
      "id":0,
      "username":"someone0",
      "areas":[

      ],
      "role":{
         "id":2,
         "name":"somerole2",
         "users":null
      }
   },
   {
      "id":1,
      "username":"someone1",
      "areas":[

      ],
      "role":{
         "id":1,
         "name":"somerole1",
         "users":null
      }
   },
   {
      "id":3,
      "username":"someone3",
      "areas":[

      ],
      "role":1
   }
]

As you can see user 'someone1' and 'someone3' both carry the same role object, but the second time it's referenced (at someone3) it is only referenced by it's id.

Because every response from this api is formatted this way, I'm looking for a generic way to fix this (replace the id-reference with the full object) in pure javascript.

Any common solutions to the seemingly common issue?

PS: I'm sorry for the title, I don't know the right term (suggestions are welcome).

Body:
You could simply map a function that makes these corrections to the initial value. Something like this should work if I understand what you are going for:

response = response.map( function(x){
    if( (typeof x.role) == "number"  )
        x.role = { id : x.role };
    return x;
});

This however will not give you the names and users field. If this is important, I recommend we iterate through the data once and make a list of roles, then go back and fill in the gaps. This would look like:

roles = {};

response.forEach( function(x){
    if( (typeof x.role) != "number" )
        roles[x.role.id] = x.role;
});

response = response.map( function(x){
    if( (typeof x.role) == "number"  )
        x.role = roles[x.role];
    return x;
});

The output of running that on your data is:

[
  { id: 0,
    username: 'someone0',
    areas: [],
    role: { id: 2, name: 'somerole2', users: null }
  },
  { id: 1,
    username: 'someone1',
    areas: [],
    role: { id: 1, name: 'somerole1', users: null }
  },
  { id: 3,
    username: 'someone3',
    areas: [],
    role: { id: 1, name: 'somerole1', users: null }
  }
]