问:
Docker not reflecting changes to html file
I'm building a Webassembly app and Docker does not reflect changes to html file.
Before I build the Docker file I prune the system, hoping this would force a brand new build.
Any pointers?

```<code>FROM golang:alpine AS builder
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

COPY . .
COPY ./server.go .
COPY ./favicon.ico .
COPY ./assets /assets
EXPOSE 8989
CMD ["go", "run", "./server.go"]
</code>```

This is how I run build the container.

```<code>docker system prune -a -f
docker build --no-cache -t test3 .
docker run -it test3
</code>```

The html file runs on localhost as the first version I started out with.
This is the server.go

```<code>package main

import (
    "flag"
    "fmt"
    "net/http"
    "strings"
)

type FileSystem struct {
    fs http.FileSystem
}

var listen = flag.String("listen", ":8989", "listen address")
var dir = flag.String("dir", ".", "directory to serve")

func main() {
    flag.Parse()
    directory := "./"

    fileServer := http.FileServer(FileSystem{http.Dir(directory)})
    http.Handle("/", fileServer)

    fmt.Printf("Web server running. Listening on %q", *listen)
    err := http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))
    fmt.Printf("%v\n", err)
}

func (fs FileSystem) Open(path string) (http.File, error) {
    f, err := fs.fs.Open(path)
    if err != nil {
        return nil, err
    }

    s, err := f.Stat()
    if s.IsDir() {
        index := strings.TrimSuffix(path, "/") + "/index.html"
        if _, err := fs.fs.Open(index); err != nil {
            return nil, err
        }
    }

    return f, nil
}
</code>```

Finally the html file.

```<code><!DOCTYPE HTML>
<html>
    <head>
        <title>Wasm 1.0</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
        <link rel="stylesheet" href="./assets/css/main.css" />
        <link rel="icon" href="./favicon.ico?v=1">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-96x96.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-128x128.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-144x144.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-152x152.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-192x192.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-384x384.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-384x384.png">
        <link rel="manifest" href="./assests/manifest.json">
        <meta name="msapplication-TileColor" content="#ffffff">
        <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
        <meta name="theme-color" content="#ffffff">
    </head>
    <body class="is-preload">
        <script src="./assets/js/wasm_exec.js"></script>
        <script>
        wasm_filename = "./assets/main.wasm";
        function message(s){
            document.getElementById("message").textContent = s;
        }

        function load_wasm(){
            if (!WebAssembly.instantiateStreaming) { // polyfill
                WebAssembly.instantiateStreaming = async (resp, importObject) => {
                    const source = await (await resp).arrayBuffer();
                    return await WebAssembly.instantiate(source, importObject);
                };
            }

            const go = new Go();

            WebAssembly.instantiateStreaming(fetch(wasm_filename), go.importObject)
            .then(results => { go.run(results.instance); })
            .catch((err) => {
                message("Error Loading WebAssembly - " + err);
                console.error(err);
        //      location.reload(true);
                });
        }

        load_wasm()
    </script>
    <nav id="nav">
        <ul class="container">
            <li><a href="/">Reload</a></li>
        </ul>
    </nav>

    <div id="message" class="message"></div>
    <article id="top" class="wrapper style1">
        <div class="container">
            <div class="row">
                <div class="col-4 col-5-large col-12-medium">

                </div>
                <div class="col-8 col-7-large col-12-medium">
                    <header>
                        <h1><strong>Wasm</strong>.</h1>
                    </header>
                    <a class="button large" onclick="sum();">Calculate</a>
                    <div><input type="text" id="num1"></div>
                    <div><input type="text" id="num2"></div>
                    <div><input type="text" id="result"></div>
                </div>
            </div>
        </div>
    </article>

    <script src="./assets/js/jquery.min.js"></script>
    <script src="./assets/js/jquery.scrolly.min.js"></script>
    <script src="./assets/js/browser.min.js"></script>
    <script src="./assets/js/breakpoints.min.js"></script>
    <script src="./assets/js/util.js"></script>
    <script src="./assets/js/main.js"></script>
    <script src="./assets/js/app.js"></script>
    </body>
</html>
</code>```

答:
The problem was that I needed to do port forwarding:

docker run -p 8989:8989 test3

It works now.

Body:
I'm building a Webassembly app and Docker does not reflect changes to html file.
Before I build the Docker file I prune the system, hoping this would force a brand new build.
Any pointers?

FROM golang:alpine AS builder
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

COPY . .
COPY ./server.go .
COPY ./favicon.ico .
COPY ./assets /assets
EXPOSE 8989
CMD ["go", "run", "./server.go"]

This is how I run build the container.

docker system prune -a -f
docker build --no-cache -t test3 .
docker run -it test3

The html file runs on localhost as the first version I started out with.
This is the server.go

package main

import (
    "flag"
    "fmt"
    "net/http"
    "strings"
)

type FileSystem struct {
    fs http.FileSystem
}

var listen = flag.String("listen", ":8989", "listen address")
var dir = flag.String("dir", ".", "directory to serve")

func main() {
    flag.Parse()
    directory := "./"

    fileServer := http.FileServer(FileSystem{http.Dir(directory)})
    http.Handle("/", fileServer)

    fmt.Printf("Web server running. Listening on %q", *listen)
    err := http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))
    fmt.Printf("%v\n", err)
}

func (fs FileSystem) Open(path string) (http.File, error) {
    f, err := fs.fs.Open(path)
    if err != nil {
        return nil, err
    }

    s, err := f.Stat()
    if s.IsDir() {
        index := strings.TrimSuffix(path, "/") + "/index.html"
        if _, err := fs.fs.Open(index); err != nil {
            return nil, err
        }
    }

    return f, nil
}

Finally the html file.

<!DOCTYPE HTML>

        <title>Wasm 1.0</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
        <link rel="stylesheet" href="./assets/css/main.css" />
        <link rel="icon" href="./favicon.ico?v=1">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-96x96.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-128x128.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-144x144.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-152x152.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-192x192.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-384x384.png">
        <link rel="icon" type="image/png" sizes="96x96" href="./assets/images/icons/icon-384x384.png">
        <link rel="manifest" href="./assests/manifest.json">
        <meta name="msapplication-TileColor" content="#ffffff">
        <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
        <meta name="theme-color" content="#ffffff">

Reload

Wasm.

                    Calculate

<input type="text" id="num1">

<input type="text" id="num2">

<input type="text" id="result">


来源: stackexchange

问:
How to get PromiseValue in XMLHttpRequest. JSON
How to get array that is located on PromiseValue instead of getting Promise {<pending>}
While I'm using .then(data => console.log(data)) I'm getting array in console log.
However, I need to get an array to place it on the html page so I changet code to .then(data => data) and started to get Promise {<pending>}

```<code>const baseUrl = 'http://localhost:3000';

function sendRequest(method, url, data = null) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open(method, url);

        xhr.responseType = 'json';
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = () => {
            if (xhr.status >= 400) {
                reject(xhr.response);
            } else {
                resolve(xhr.response);
            }
        }

        xhr.onerror = () => {
            reject(xhr.response);
        }

        xhr.send(JSON.stringify(data));
    });
}

let getData = sendRequest('GET', baseUrl + '/users')
.then(data => data)
.catch(err => console.log(err));

console.log(getData);
</code>```

Thanks in advance.

答:
I think you will have to return the value of data as mentioned here to complete the promise

When promise returned by sendRequest is resolved, it will immediately pass a new promise to getData .

```<code>.then(data => {
      return data;
})
.catch (err => {
      console.log(err);
})
</code>```

looks something like this

```<code>function sendRequest(s){
  return new Promise((resolve, reject) => {
       resolve(s) ;
  });
}

let getData = sendRequest("test")
 .then(value => {
    return value;
})

getData.then(value => {
    console.log( value);
    //access value
})
</code>```

Have a look at this question

ContentLicense: CC BY-SA 4.0

Body:
How to get array that is located on PromiseValue instead of getting Promise {<pending>}
While I'm using .then(data => console.log(data)) I'm getting array in console log.
However, I need to get an array to place it on the html page so I changet code to .then(data => data) and started to get Promise {<pending>}

const baseUrl = 'http://localhost:3000';

function sendRequest(method, url, data = null) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open(method, url);

        xhr.responseType = 'json';
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = () => {
            if (xhr.status >= 400) {
                reject(xhr.response);
            } else {
                resolve(xhr.response);
            }
        }

        xhr.onerror = () => {
            reject(xhr.response);
        }

        xhr.send(JSON.stringify(data));
    });
}

let getData = sendRequest('GET', baseUrl + '/users')
.then(data => data)
.catch(err => console.log(err));

console.log(getData);

Thanks in advance.

Body:
I think you will have to return the value of data as mentioned here to complete the promise

When promise returned by sendRequest is resolved, it will immediately pass a new promise to getData .

.then(data => {
      return data;
})
.catch (err => {
      console.log(err);
})

looks something like this

function sendRequest(s){
  return new Promise((resolve, reject) => {
       resolve(s) ;
  });
}

let getData = sendRequest("test")
 .then(value => {
    return value;
})

getData.then(value => {
    console.log( value);
    //access value
})

Have a look at this question


问:
Using Material Button gives ClassNotFound runtime error
I am in the process of replacing the buttons in my app with Material Buttons using <com.google.android.material.button.MaterialButton in the XML file and private MaterialButton dateButton; in the Java fragment file.
I studied the Code Lab "MDC-101 Android: Material Components (MDC) Basics (Java)" to see how a Material Button is used. In the gradle.build (Module:app) file I added the dependencies like in the code lab.
The code lab compiles and runs fine. My app compiles fine but gives an error when inflating the fragment layout:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: nl.kl_solutions.schedulecompareforzermelo, PID: 16708
              android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class com.google.android.material.button.MaterialButton
              Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class com.google.android.material.button.MaterialButton
              Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.material.button.MaterialButton" on path: DexPathList[[zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/base.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_dependencies_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_resources_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_0_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_1_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_2_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_3_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_4_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_5_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_6_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_7_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_8_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/lib/x86_64, /system/lib64]]
                  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
</code>```

This is a snippet from my layout file:

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/primaryLightColor"
    android:paddingLeft="@dimen/rasterleftpadding"
    android:paddingRight="@dimen/rasterrightpadding" >

    <Button
        android:id="@+id/btn_previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="left"
        android:text="prev" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_week"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
         />

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1"
        android:text="next" />

</LinearLayout>
</code>```

And here is a snippet from the onCreateView:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View fragmentLayout = inflater.inflate(R.layout.fragment_week_schedule, container, false);
    //get references to the buttonBar buttons.
    leftButton = fragmentLayout.findViewById(R.id.btn_previous);
    rightButton = fragmentLayout.findViewById(R.id.btn_next);
    dateButton = fragmentLayout.findViewById(R.id.btn_week);
</code>```

I only changed the datebutton to a Material Button which gives me the error. The app runs fine when using an ordinary Button for the dateButton.

This is my gradle.build file:

```<code>dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.android.support:appcompat-v7:$rootProject.supportVersion"
implementation "com.android.support:preference-v7:$rootProject.supportVersion"
implementation "com.android.support:recyclerview-v7:$rootProject.supportVersion"
implementation "com.android.support:cardview-v7:$rootProject.supportVersion"
implementation "com.android.support.constraint:constraint-layout:1.1.3"
implementation "com.android.support:design:$rootProject.supportVersion"
implementation "com.android.support:support-v4:$rootProject.supportVersion"
implementation 'com.google.code.gson:gson:2.8.5'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

//database components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

// Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"
//QR library
implementation 'me.dm7.barcodescanner:zxing:1.9.8'
</code>```

where $rootProject.supportVersion is 28.0.0-beta01. I know that rc-01 and rc02 for some libraries are available but I ran the code lab with the beta01 dependencies so decided to keep this version to minimize changes.

Anybody knows what is causing the runtime error?

答: You should use textAppearance and your font style instead of fontFamily & textSize

Body:
I am in the process of replacing the buttons in my app with Material Buttons using <com.google.android.material.button.MaterialButton in the XML file and private MaterialButton dateButton; in the Java fragment file.
I studied the Code Lab "MDC-101 Android: Material Components (MDC) Basics (Java)" to see how a Material Button is used. In the gradle.build (Module:app) file I added the dependencies like in the code lab.
The code lab compiles and runs fine. My app compiles fine but gives an error when inflating the fragment layout:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: nl.kl_solutions.schedulecompareforzermelo, PID: 16708
              android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class com.google.android.material.button.MaterialButton
              Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class com.google.android.material.button.MaterialButton
              Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.material.button.MaterialButton" on path: DexPathList[[zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/base.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_dependencies_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_resources_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_0_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_1_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_2_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_3_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_4_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_5_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_6_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_7_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_8_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/lib/x86_64, /system/lib64]]
                  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)

This is a snippet from my layout file:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/primaryLightColor"
    android:paddingLeft="@dimen/rasterleftpadding"
    android:paddingRight="@dimen/rasterrightpadding" >

    <Button
        android:id="@+id/btn_previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="left"
        android:text="prev" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_week"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
         />

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1"
        android:text="next" />

</LinearLayout>

And here is a snippet from the onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View fragmentLayout = inflater.inflate(R.layout.fragment_week_schedule, container, false);
    //get references to the buttonBar buttons.
    leftButton = fragmentLayout.findViewById(R.id.btn_previous);
    rightButton = fragmentLayout.findViewById(R.id.btn_next);
    dateButton = fragmentLayout.findViewById(R.id.btn_week);

I only changed the datebutton to a Material Button which gives me the error. The app runs fine when using an ordinary Button for the dateButton.

This is my gradle.build file:

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.android.support:appcompat-v7:$rootProject.supportVersion"
implementation "com.android.support:preference-v7:$rootProject.supportVersion"
implementation "com.android.support:recyclerview-v7:$rootProject.supportVersion"
implementation "com.android.support:cardview-v7:$rootProject.supportVersion"
implementation "com.android.support.constraint:constraint-layout:1.1.3"
implementation "com.android.support:design:$rootProject.supportVersion"
implementation "com.android.support:support-v4:$rootProject.supportVersion"
implementation 'com.google.code.gson:gson:2.8.5'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

//database components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

// Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"
//QR library
implementation 'me.dm7.barcodescanner:zxing:1.9.8'

where $rootProject.supportVersion is 28.0.0-beta01. I know that rc-01 and rc02 for some libraries are available but I ran the code lab with the beta01 dependencies so decided to keep this version to minimize changes.

Anybody knows what is causing the runtime error?


问:
Making left-most-derivations of a input string. How to predict which production to use from?
Let's say I have the following grammar:

```<code>Expr -> Expr plus Expr  (1)
     |  Expr minus Expr (2)
     |  num             (3)
</code>```

When doing a left-most-derivation, after "expanding" Expr, how should one know what production to use?

For instance, if I want to parse 1 + 2 - 3 I'd start off with:

```<code>Expr => Expr minus Expr
</code>```

but this would only happen because this is a small example and it is easy to see that the (3) would rapidly lead to nowhere and (2) wouldn't fit in the next step. Would the example be a bit more complex and I'd have to make things basically be trial and error. Is this the "right" approach or am I missing something?

答: Because parsing CFG's is essentially non-deterministic, there is no general way to "know" beforehand which of the possible rules is the correct one.  Basically at the simplest level it really is trial and error.  Just like a disjunction boolean expression if(a OR b OR c), the individual terms will be evaluated one by one until there is a success, otherwise the rule as a whole fails.  So your parser should just start with rule (1), attempt to parse the input and if it fails, restart from that point with rule (2) and so on.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have the following grammar:

Expr -> Expr plus Expr  (1)
     |  Expr minus Expr (2)
     |  num             (3)

When doing a left-most-derivation, after "expanding" Expr, how should one know what production to use?

For instance, if I want to parse 1 + 2 - 3 I'd start off with:

Expr => Expr minus Expr

but this would only happen because this is a small example and it is easy to see that the (3) would rapidly lead to nowhere and (2) wouldn't fit in the next step. Would the example be a bit more complex and I'd have to make things basically be trial and error. Is this the "right" approach or am I missing something?


问:
How to keep log of all users who are visiting site or page on site Sharepoint 2007
We have sharepoint site and we are using sharepoint 2007.
We want to keep track of all users who are accessing the site and pages of the site.
We are checking sharepoin site usage report but we are getting some unexpected results.
Is there any alternate solution(or programatically) we can use to find out the users log?
Thanks in advance,
Rushikesh</p>

答:
Based on similar requirement in sharepoint 2016, We were able to get the user details from IIS logs, IIS log has the user ID , site URL , date and many other details.

Once you get the IIS logs you can use log parser tool (The tool is very powerful I could parse logs which were almost 100 GB) to parse the logs and then export the data to a csv file which can be then imported into SQL database and you can run queries on the data.

Log parser is a command line tool, you could even automate it if needed.

https://www.microsoft.com/en-gb/download/details.aspx?id=24659

alternate solution is, you could use Splunk and export the IIS logs to splunk, and then created a splunk dashboard to view all the details.


问:
How to use function expression values in other functions?
I'm learning Javascript and I make a rock, scissors, paper project. I already make it work with the sample code but now I want to use a function expression to use its value in other functions. When I load the code it gave me undefined and I don't know why. I assign all the values.
Here is my code.

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {

  console.log('You threw: ' + userChoice('rock'));
  console.log('The computer threw: ' + computerChoice());
  console.log(determineWinner(userChoice, computerChoice));
}
playGame();```

Please help me.

答:
You're passing the function userChoice as a param, you should store the result of calling the function userChoice and pass the result as a param in the function determineWinner

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {

  let uc = userChoice('rock');

  console.log('You threw: ' + uc);
  console.log('The computer threw: ' + computerChoice());
  console.log(determineWinner(uc, computerChoice));
}
playGame();```

Body:
I'm learning Javascript and I make a rock, scissors, paper project. I already make it work with the sample code but now I want to use a function expression to use its value in other functions. When I load the code it gave me undefined and I don't know why. I assign all the values.
Here is my code.

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {

  console.log('You threw: ' + userChoice('rock'));
  console.log('The computer threw: ' + computerChoice());
  console.log(determineWinner(userChoice, computerChoice));
}
playGame();

Please help me.


问:
Background URLSession + Combine?
When attempting to send a background request with URLSession's dataTaskPublisher method:

URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
     .dataTaskPublisher(for: URL(string: "https://google.com")!)
     .map(\.data)
     .sink(receiveCompletion: { print($0) }) { print($0) }
```

<p>I receive the error</p>

```Completion handler blocks are not supported in background sessions. Use a delegate instead.
```

<p>This makes sense to me, <code>sink</code> is a bunch of completion handlers. So, I tried to build a <code>Subscriber</code>:</p>

<pre class="lang-swift prettyprint-override"><code>class ExampleSubscriber: Subscriber {
    typealias Input = Data

    typealias Failure = URLError

    func receive(subscription: Subscription) {
        subscription.request(.max(1))
    }

    func receive(_ input: Data) -> Subscribers.Demand {
        print(input)

        return Subscribers.Demand.none
    }

    func receive(completion: Subscribers.Completion<URLError>) {}

}
</code>```

and subscribe with the Subscriber:

URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
    .dataTaskPublisher(for: URL(string: "https://google.com")!)
    .map(\.data)
    .subscribe(ExampleSubscriber())
```

<p>and I receive the same error:</p>

```Completion handler blocks are not supported in background sessions. Use a delegate instead.
```

Is it possible to perform a background request using dataTaskPublisher or do I have to use a delegate to URLSession?

答:
URLSession.DataTaskPublisher is built on top of URLSessionDataTask and sets a completion handler on the task. So you cannot use DataTaskPublisher with a background session.

You can find the source code of DataTaskPublisher in the Swift project repo. Here are the relevant lines:

```<code>let task = p.session.dataTask(
    with: p.request,
    completionHandler: handleResponse(data:response:error:)
)
</code>```

Title: Background URLSession + Combine?

Body:
When attempting to send a background request with URLSession's dataTaskPublisher method:

URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
     .dataTaskPublisher(for: URL(string: "https://google.com")!)
     .map(\.data)
     .sink(receiveCompletion: { print($0) }) { print($0) }

I receive the error

Completion handler blocks are not supported in background sessions. Use a delegate instead.

This makes sense to me, sink is a bunch of completion handlers. So, I tried to build a Subscriber:

class ExampleSubscriber: Subscriber {
    typealias Input = Data

    typealias Failure = URLError

    func receive(subscription: Subscription) {
        subscription.request(.max(1))
    }

    func receive(_ input: Data) -> Subscribers.Demand {
        print(input)

        return Subscribers.Demand.none
    }

    func receive(completion: Subscribers.Completion<URLError>) {}

}

and subscribe with the Subscriber:

URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
    .dataTaskPublisher(for: URL(string: "https://google.com")!)
    .map(\.data)
    .subscribe(ExampleSubscriber())

and I receive the same error:

Completion handler blocks are not supported in background sessions. Use a delegate instead.

Is it possible to perform a background request using dataTaskPublisher or do I have to use a delegate to URLSession?

Body:
URLSession.DataTaskPublisher is built on top of URLSessionDataTask and sets a completion handler on the task. So you cannot use DataTaskPublisher with a background session.

You can find the source code of DataTaskPublisher in the Swift project repo. Here are the relevant lines:

let task = p.session.dataTask(
    with: p.request,
    completionHandler: handleResponse(data:response:error:)
)


答:
You should assign the outputs of userChoice and computerChoice to variables before passing them to determineWinner

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {
  const userChose = userChoice('rock')
  const computerChose = computerChoice()
  console.log('You threw: ' + userChose);
  console.log('The computer threw: ' + computerChose);
  console.log(determineWinner(userChose, computerChose));
}
playGame();```

Title: How to use function expression values in other functions?


答:
Try This

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {

  console.log('You threw: ' + userChoice('rock'));
  console.log('The computer threw: ' + computerChoice());
  console.log(determineWinner(userChoice('rock'), computerChoice()));
}
playGame();```


问:
How can I run an asyncio loop as long as there are pending cancellation-shielded tasks left but no longer?
I'm trying to add some code to my existing asyncio loop to provide for a clean shutdown on Ctrl-C.  Below is an abstraction of the sort of thing it's doing.

```<code>import asyncio, signal

async def task1():
    print("Starting simulated task1")
    await asyncio.sleep(5)
    print("Finished simulated task1")

async def task2():
    print("Starting simulated task2")
    await asyncio.sleep(5)
    print("Finished simulated task2")

async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            await asyncio.shield(tasks())
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop")
        raise

async def aiomain():
    loop = asyncio.get_running_loop()
    task = asyncio.Task(task_loop())
    loop.add_signal_handler(signal.SIGINT, task.cancel)
    await task

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        pass

#def main():
#    try:
#        loop = asyncio.get_event_loop()
#        loop.create_task(aiomain())
#        loop.run_forever()
#    except asyncio.CancelledError:
#        pass

if __name__ == '__main__':
    main()
</code>```

In this example, imagine that the sequence of task1 and task2 needs to be finished once it's started, or some artifacts will be left in an inconsistent state.  (Hence the asyncio.shield wrapper around calling tasks.)

With the code as above, if I interrupt the script soon after it starts and it's just printed Starting simulated task1 then the loop stops and task2 never gets started.  If I try switching to the version of main that's commented out then that one never exits, even though the loop is properly cancelled and nothing further happens at least for several minutes.  It does have a bit of progress in that it at least finishes any in-progress sequence of task1 and task2.

Some possible solutions from brainstorming, though I still get the feeling there must be something simpler that I'm missing:

Create a wrapper around asyncio.shield which increments a variable synchronized by an asyncio.Condition object, runs the shielded function, then decrements the variable.  Then, in aiomain in a CancelledError handler, wait for the variable to reach zero before reraising the exception.  (In an implementation, I would probably go for combining all the parts of this into one class with __aexit__ implementing the wait for zero on CancelledError logic.)

Skip using asyncio's cancellation mechanism entirely, and instead use an asyncio.Event or similar to allow for interruption points or interruptible sleeps.  Though this does seem like it would be more invasive requiring me to specify what points are considered interruptible, as opposed to declaring what sequences need to be shielded from cancellation.

答:
This is a very good question.  I have learned some things while working out an answer, so I hope you are still monitoring this thread.

The first thing to investigate is, how does the shield() method work?  On this point, the docs are confusing to say the least.  I couldn't figure it out until I read the standard library test code in test_tasks.py.  Here is my understanding:

Consider this code fragment:

```<code>async def coro_a():
    await asyncio.sheild(task_b())
    ...
task_a = asyncio.create_task(coro_a())
task_a.cancel()
</code>```

When the task_a.cancel() statement is executed, task_a is indeed cancelled.  The await statement throws a CancelledError immediately, without waiting for task_b to finish.  But task_b continues to run.  The outer task (a) stops but the inner task (b) doesn't.

Here is a modified version of your program that illustrates this.  The major change is to insert a wait in your CancelledError exception handler, to keep your program alive a few seconds longer.  I'm running on Windows and that's why I changed your signal handler a little bit also, but that's a minor point.  I also added time stamps to the print statements.

```<code>import asyncio
import signal
import time

async def task1():
    print("Starting simulated task1", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task1", time.time())

async def task2():
    print("Starting simulated task2", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task2", time.time())

async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            await asyncio.shield(tasks())
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop", time.time())
        raise

async def aiomain():
    task = asyncio.create_task(task_loop())
    KillNicely(task)
    try:
        await task
    except asyncio.CancelledError:
        print("Caught CancelledError", time.time())
        await asyncio.sleep(5.0)
        raise

class KillNicely:
    def __init__(self, cancel_me):
        self.cancel_me = cancel_me
        self.old_sigint = signal.signal(signal.SIGINT,
                                        self.trap_control_c)

    def trap_control_c(self, signum, stack):
        if signum != signal.SIGINT:
            self.old_sigint(signum, stack)
        else:
            print("Got Control-C", time.time())
            print(self.cancel_me.cancel())

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        print("Program exit, cancelled", time.time())

# Output when ctrlC is struck during task1
#
# Starting simulated task1 1590871747.8977509
# Got Control-C 1590871750.8385916
# True
# Shutting down task loop 1590871750.8425908
# Caught CancelledError 1590871750.8435903
# Finished simulated task1 1590871752.908434
# Starting simulated task2 1590871752.908434
# Program exit, cancelled 1590871755.8488846

if __name__ == '__main__':
    main()
</code>```

You can see that your program didn't work because it exited as soon as task_loop was cancelled, before task1 and task2 had a chance to finish.  They were still there all along (or rather they would have been there, if the program continued to run).

This illustrates how shield() and cancel() interact, but it doesn't actually solve your stated problem.  For that, I think, you need to have an awaitable object that you can use to keep the program alive until the vital tasks are finished.  This object needs to be created at the top level and passed down the stack to the place where the vital tasks are executing.  Here is a program that is similar to yours, but preforms the way you want.

I did three runs: (1) control-C during task1, (2) control-C during task2, (3) control-C after both tasks were finished.  In the first two cases the program continued until task2 was finished.  In the third case it ended immediately.

```<code>import asyncio
import signal
import time

async def task1():
    print("Starting simulated task1", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task1", time.time())

async def task2():
    print("Starting simulated task2", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task2", time.time())

async def tasks(kwrap):
    fut = asyncio.get_running_loop().create_future()
    kwrap.awaitable = fut
    await task1()
    await task2()
    fut.set_result(1)

async def task_loop(kwrap):
    try:
        while True:
            await asyncio.shield(tasks(kwrap))
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop", time.time())
        raise

async def aiomain():
    kwrap = KillWrapper()
    task = asyncio.create_task(task_loop(kwrap))
    KillNicely(task)
    try:
        await task
    except asyncio.CancelledError:
        print("Caught CancelledError", time.time())
        await kwrap.awaitable
        raise

class KillNicely:
    def __init__(self, cancel_me):
        self.cancel_me = cancel_me
        self.old_sigint = signal.signal(signal.SIGINT,
                                        self.trap_control_c)

    def trap_control_c(self, signum, stack):
        if signum != signal.SIGINT:
            self.old_sigint(signum, stack)
        else:
            print("Got Control-C", time.time())
            print(self.cancel_me.cancel())

class KillWrapper:
    def __init__(self):
        self.awaitable = asyncio.get_running_loop().create_future()
        self.awaitable.set_result(0)

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        print("Program exit, cancelled", time.time())

# Run 1 Control-C during task1
# Starting simulated task1 1590872408.6737766
# Got Control-C 1590872410.7344952
# True
# Shutting down task loop 1590872410.7354996
# Caught CancelledError 1590872410.7354996
# Finished simulated task1 1590872413.6747622
# Starting simulated task2 1590872413.6747622
# Finished simulated task2 1590872418.6750958
# Program exit, cancelled 1590872418.6750958
#
# Run 1 Control-C during task2
# Starting simulated task1 1590872492.927735
# Finished simulated task1 1590872497.9280624
# Starting simulated task2 1590872497.9280624
# Got Control-C 1590872499.5973852
# True
# Shutting down task loop 1590872499.5983844
# Caught CancelledError 1590872499.5983844
# Finished simulated task2 1590872502.9274273
# Program exit, cancelled 1590872502.9287038
#
# Run 1 Control-C after task2 -> immediate exit
# Starting simulated task1 1590873694.2925708
# Finished simulated task1 1590873699.2928336
# Starting simulated task2 1590873699.2928336
# Finished simulated task2 1590873704.2938952
# Got Control-C 1590873706.0790765
# True
# Shutting down task loop 1590873706.0804725
# Caught CancelledError 1590873706.0804725
# Program exit, cancelled 1590873706.0814824
</code>```

Body:
I'm trying to add some code to my existing asyncio loop to provide for a clean shutdown on Ctrl-C.  Below is an abstraction of the sort of thing it's doing.

import asyncio, signal

async def task1():
    print("Starting simulated task1")
    await asyncio.sleep(5)
    print("Finished simulated task1")

async def task2():
    print("Starting simulated task2")
    await asyncio.sleep(5)
    print("Finished simulated task2")

async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            await asyncio.shield(tasks())
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop")
        raise

async def aiomain():
    loop = asyncio.get_running_loop()
    task = asyncio.Task(task_loop())
    loop.add_signal_handler(signal.SIGINT, task.cancel)
    await task

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        pass

#def main():
#    try:
#        loop = asyncio.get_event_loop()
#        loop.create_task(aiomain())
#        loop.run_forever()
#    except asyncio.CancelledError:
#        pass

if __name__ == '__main__':
    main()

In this example, imagine that the sequence of task1 and task2 needs to be finished once it's started, or some artifacts will be left in an inconsistent state.  (Hence the asyncio.shield wrapper around calling tasks.)

With the code as above, if I interrupt the script soon after it starts and it's just printed Starting simulated task1 then the loop stops and task2 never gets started.  If I try switching to the version of main that's commented out then that one never exits, even though the loop is properly cancelled and nothing further happens at least for several minutes.  It does have a bit of progress in that it at least finishes any in-progress sequence of task1 and task2.

Some possible solutions from brainstorming, though I still get the feeling there must be something simpler that I'm missing:

Create a wrapper around asyncio.shield which increments a variable synchronized by an asyncio.Condition object, runs the shielded function, then decrements the variable.  Then, in aiomain in a CancelledError handler, wait for the variable to reach zero before reraising the exception.  (In an implementation, I would probably go for combining all the parts of this into one class with __aexit__ implementing the wait for zero on CancelledError logic.)

Skip using asyncio's cancellation mechanism entirely, and instead use an asyncio.Event or similar to allow for interruption points or interruptible sleeps.  Though this does seem like it would be more invasive requiring me to specify what points are considered interruptible, as opposed to declaring what sequences need to be shielded from cancellation.

Body:
This is a very good question.  I have learned some things while working out an answer, so I hope you are still monitoring this thread.

The first thing to investigate is, how does the shield() method work?  On this point, the docs are confusing to say the least.  I couldn't figure it out until I read the standard library test code in test_tasks.py.  Here is my understanding:

Consider this code fragment:

async def coro_a():
    await asyncio.sheild(task_b())
    ...
task_a = asyncio.create_task(coro_a())
task_a.cancel()

When the task_a.cancel() statement is executed, task_a is indeed cancelled.  The await statement throws a CancelledError immediately, without waiting for task_b to finish.  But task_b continues to run.  The outer task (a) stops but the inner task (b) doesn't.

Here is a modified version of your program that illustrates this.  The major change is to insert a wait in your CancelledError exception handler, to keep your program alive a few seconds longer.  I'm running on Windows and that's why I changed your signal handler a little bit also, but that's a minor point.  I also added time stamps to the print statements.

import asyncio
import signal
import time

async def task1():
    print("Starting simulated task1", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task1", time.time())

async def task2():
    print("Starting simulated task2", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task2", time.time())

async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            await asyncio.shield(tasks())
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop", time.time())
        raise

async def aiomain():
    task = asyncio.create_task(task_loop())
    KillNicely(task)
    try:
        await task
    except asyncio.CancelledError:
        print("Caught CancelledError", time.time())
        await asyncio.sleep(5.0)
        raise

class KillNicely:
    def __init__(self, cancel_me):
        self.cancel_me = cancel_me
        self.old_sigint = signal.signal(signal.SIGINT,
                                        self.trap_control_c)

    def trap_control_c(self, signum, stack):
        if signum != signal.SIGINT:
            self.old_sigint(signum, stack)
        else:
            print("Got Control-C", time.time())
            print(self.cancel_me.cancel())

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        print("Program exit, cancelled", time.time())

# Output when ctrlC is struck during task1
#
# Starting simulated task1 1590871747.8977509
# Got Control-C 1590871750.8385916
# True
# Shutting down task loop 1590871750.8425908
# Caught CancelledError 1590871750.8435903
# Finished simulated task1 1590871752.908434
# Starting simulated task2 1590871752.908434
# Program exit, cancelled 1590871755.8488846

if __name__ == '__main__':
    main()

You can see that your program didn't work because it exited as soon as task_loop was cancelled, before task1 and task2 had a chance to finish.  They were still there all along (or rather they would have been there, if the program continued to run).

This illustrates how shield() and cancel() interact, but it doesn't actually solve your stated problem.  For that, I think, you need to have an awaitable object that you can use to keep the program alive until the vital tasks are finished.  This object needs to be created at the top level and passed down the stack to the place where the vital tasks are executing.  Here is a program that is similar to yours, but preforms the way you want.

I did three runs: (1) control-C during task1, (2) control-C during task2, (3) control-C after both tasks were finished.  In the first two cases the program continued until task2 was finished.  In the third case it ended immediately.

import asyncio
import signal
import time

async def task1():
    print("Starting simulated task1", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task1", time.time())

async def task2():
    print("Starting simulated task2", time.time())
    await asyncio.sleep(5)
    print("Finished simulated task2", time.time())

async def tasks(kwrap):
    fut = asyncio.get_running_loop().create_future()
    kwrap.awaitable = fut
    await task1()
    await task2()
    fut.set_result(1)

async def task_loop(kwrap):
    try:
        while True:
            await asyncio.shield(tasks(kwrap))
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop", time.time())
        raise

async def aiomain():
    kwrap = KillWrapper()
    task = asyncio.create_task(task_loop(kwrap))
    KillNicely(task)
    try:
        await task
    except asyncio.CancelledError:
        print("Caught CancelledError", time.time())
        await kwrap.awaitable
        raise

class KillNicely:
    def __init__(self, cancel_me):
        self.cancel_me = cancel_me
        self.old_sigint = signal.signal(signal.SIGINT,
                                        self.trap_control_c)

    def trap_control_c(self, signum, stack):
        if signum != signal.SIGINT:
            self.old_sigint(signum, stack)
        else:
            print("Got Control-C", time.time())
            print(self.cancel_me.cancel())

class KillWrapper:
    def __init__(self):
        self.awaitable = asyncio.get_running_loop().create_future()
        self.awaitable.set_result(0)

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        print("Program exit, cancelled", time.time())

# Run 1 Control-C during task1
# Starting simulated task1 1590872408.6737766
# Got Control-C 1590872410.7344952
# True
# Shutting down task loop 1590872410.7354996
# Caught CancelledError 1590872410.7354996
# Finished simulated task1 1590872413.6747622
# Starting simulated task2 1590872413.6747622
# Finished simulated task2 1590872418.6750958
# Program exit, cancelled 1590872418.6750958
#
# Run 1 Control-C during task2
# Starting simulated task1 1590872492.927735
# Finished simulated task1 1590872497.9280624
# Starting simulated task2 1590872497.9280624
# Got Control-C 1590872499.5973852
# True
# Shutting down task loop 1590872499.5983844
# Caught CancelledError 1590872499.5983844
# Finished simulated task2 1590872502.9274273
# Program exit, cancelled 1590872502.9287038
#
# Run 1 Control-C after task2 -> immediate exit
# Starting simulated task1 1590873694.2925708
# Finished simulated task1 1590873699.2928336
# Starting simulated task2 1590873699.2928336
# Finished simulated task2 1590873704.2938952
# Got Control-C 1590873706.0790765
# True
# Shutting down task loop 1590873706.0804725
# Caught CancelledError 1590873706.0804725
# Program exit, cancelled 1590873706.0814824


问:
vue-material mdAutocomplete inside electron-vue app - setup problems
I am experimenting with electron-vue seed app and have upgraded electron to 8 and vue to the latest versions. I am installing vue-material components in my src/renderer/router/index.js:

```<code>import Vue from 'vue'
import Router from 'vue-router'
import { MdButton, MdContent, MdTabs, MdAutocomplete } from 'vue-material/dist/components'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default-dark.css'

Vue.use(Router)
Vue.use(MdButton)
Vue.use(MdContent)
Vue.use(MdTabs)
Vue.use(MdAutocomplete)
</code>```

I then have src/renderer/App.vue with

```<code><template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name: 'pdq-app'
  }
</script>

<style>

  @import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;600&display=swap|Roboto:400,500,700,400italic|Material+Icons');

  html {
    font-family: 'Source Code Pro', monospace;
  }

</style>
</code>```

I'm drawing the autocomplete on the CommandLine.vue template, with the Command.vue component:

```<code><template>
  <main>
    <main-menu></main-menu>
    <command></command>
  </main>
</template>

<script>
  import MainMenu from './MainMenu'
  import Command from './CommandLine/Command'

  export default {
    name: 'command-line',
    components: { MainMenu, Command },
    methods: {
      open (link) {
        this.$electron.shell.openExternal(link)
      }
    }
  }
</script>

<style>

</style>
</code>```

The autocomplete component is thus:

```<code><template>
  <div>
    <md-autocomplete v-model="selectedCountry" :md-options="countries">
      <label>Country</label>
    </md-autocomplete>

    <md-autocomplete v-model="selectedEmployee" :md-options="employees" md-dense>
      <label>Employees</label>
    </md-autocomplete>
  </div>
</template>

<script>
  export default {
    name: 'AutocompleteStatic',
    data: () => ({
      selectedCountry: null,
      selectedEmployee: null,
      countries: [
        'Algeria',
        'Argentina',
        'Brazil',
        'Canada',
        'Italy',
        'Japan',
        'United Kingdom',
        'United States'
      ],
      employees: [
        'Jim Halpert',
        'Dwight Schrute',
        'Michael Scott',
        'Pam Beesly',
        'Angela Martin',
        'Kelly Kapoor',
        'Ryan Howard',
        'Kevin Malone',
        'Creed Bratton',
        'Oscar Nunez',
        'Toby Flenderson',
        'Stanley Hudson',
        'Meredith Palmer',
        'Phyllis Lapin-Vance'
      ]
    })
  }
</script>
</code>```

The issue is I am not sure what I am missing to display the input control - it's rendering invisible. There exists an md-input tag in the rendered HTML, but it seems I'm missing some dependency to draw stuff:

What am I missing to draw the full autocomplete?

答:
Looks like I needed to add some dependencies: MdField, MdMenu, and MdList. It's difficult to see this in the documentation; I guess if I was importing the entirety of VueMaterial it wouldn't be an issue.

```<code>import Vue from 'vue'
import Router from 'vue-router'
import {
  MdButton,
  MdCard,
  MdContent,
  MdTabs,
  MdAutocomplete,
  MdField,
  MdMenu,
  MdList
} from 'vue-material/dist/components'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default-dark.css'

Vue.use(Router)
Vue.use(MdAutocomplete)
Vue.use(MdField)
Vue.use(MdMenu)
Vue.use(MdList)
Vue.use(MdButton)
Vue.use(MdCard)
Vue.use(MdContent)
Vue.use(MdTabs)

// export default new Router({
// ...
</code>```

Body:
I am experimenting with electron-vue seed app and have upgraded electron to 8 and vue to the latest versions. I am installing vue-material components in my src/renderer/router/index.js:

import Vue from 'vue'
import Router from 'vue-router'
import { MdButton, MdContent, MdTabs, MdAutocomplete } from 'vue-material/dist/components'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default-dark.css'

Vue.use(Router)
Vue.use(MdButton)
Vue.use(MdContent)
Vue.use(MdTabs)
Vue.use(MdAutocomplete)

I then have src/renderer/App.vue with

<template>

    <router-view></router-view>

</template>

I'm drawing the autocomplete on the CommandLine.vue template, with the Command.vue component:

<template>

    <command></command>

</template>

The autocomplete component is thus:

<template>

    <md-autocomplete v-model="selectedCountry" :md-options="countries">
      Country
    </md-autocomplete>

    <md-autocomplete v-model="selectedEmployee" :md-options="employees" md-dense>
      Employees
    </md-autocomplete>

</template>

The issue is I am not sure what I am missing to display the input control - it's rendering invisible. There exists an md-input tag in the rendered HTML, but it seems I'm missing some dependency to draw stuff:

What am I missing to draw the full autocomplete?

Body:
Looks like I needed to add some dependencies: MdField, MdMenu, and MdList. It's difficult to see this in the documentation; I guess if I was importing the entirety of VueMaterial it wouldn't be an issue.

import Vue from 'vue'
import Router from 'vue-router'
import {
  MdButton,
  MdCard,
  MdContent,
  MdTabs,
  MdAutocomplete,
  MdField,
  MdMenu,
  MdList
} from 'vue-material/dist/components'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default-dark.css'

Vue.use(Router)
Vue.use(MdAutocomplete)
Vue.use(MdField)
Vue.use(MdMenu)
Vue.use(MdList)
Vue.use(MdButton)
Vue.use(MdCard)
Vue.use(MdContent)
Vue.use(MdTabs)

// export default new Router({
// ...


问:
Image jaggerred edges while applying perspective, C#
Facing some issues with image warping. My application (C#, VS2010) takes as input an image and tiles it and applies perspective using a homography matrix. All that works fine and I get a tiled output image with the required perspective. But the output image has some jaggered edges and missing pixels.

This is a sample output from my application:
http://www.4shared.com/photo/vIeRhc9y/InterPol.html
(Enlarge the image to see the problem clearly)

Check out the jaggered edges and some missing white lines towards the top left corner of the image. I tried applying bicubic interpolation to the pixels based on the explanation provided here:
http://paulbourke.net/texture_colour/imageprocess/

The output is slightly better, but most of the missing lines and jaggered edges remain. What can I do to solve the issue?

Thanks in advance.

Regards

答:
You need to do better ;) are you using System.Drawing or something else? I know how to make the quality really good with GDI+ but you should be able to get better results with bicubic interpolation. Are you doing any filtering?

For simple comparsion, just opening the image in Paint.NET and doing some resizing I'm not experiencing the same problem.


问:
unable to build grpc v1.28.1 inside a container
I am getting c++: fatal errors when trying to build grpc inside a container. Tried it with GNU CC 7, and 10, on three different machines, all running Docker Desktop for Windows.

the basic Dockerfile is mimicing the grpc building docs:

```<code>FROM gcc:10.1.0

RUN apt-get update && apt-get upgrade -y && \
    apt-get install -y build-essential autoconf libtool pkg-config git curl cmake

RUN cd /tmp && \
    git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc && \
    cd grpc && \
    git submodule update --init && \
    mkdir -p cmake/build && \
    mkdir -p /opt/grpc && \
    cd cmake/build && \
    cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=/opt/grpc ../.. && \
    make -j && \
    make install
</code>```

but can't get to a successful build as on all systems, I get this:

```<code>c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc.dir/build.make:2130: CMakeFiles/grpc.dir/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc.o] Error 1
make[2]: *** Waiting for unfinished jobs....
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2182: CMakeFiles/grpc_cronet.dir/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** Waiting for unfinished jobs....
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc.dir/build.make:2182: CMakeFiles/grpc.dir/src/core/ext/transport/chttp2/transport/chttp2_transport.cc.o] Error 1
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2598: CMakeFiles/grpc_cronet.dir/src/core/ext/filters/client_channel/client_channel.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc_unsecure.dir/build.make:2208: CMakeFiles/grpc_unsecure.dir/src/core/ext/transport/chttp2/transport/chttp2_transport.cc.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2819: CMakeFiles/grpc_cronet.dir/src/core/ext/filters/client_channel/resolving_lb_policy.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc.dir/build.make:2520: CMakeFiles/grpc.dir/src/core/lib/security/context/security_context.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
[ 89%] Building C object CMakeFiles/grpc.dir/src/core/ext/upb-generated/envoy/api/v2/cluster.upb.c.o
make[2]: *** [CMakeFiles/grpc.dir/build.make:2546: CMakeFiles/grpc.dir/src/core/lib/security/credentials/composite/composite_credentials.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc_unsecure.dir/build.make:2858: CMakeFiles/grpc_unsecure.dir/src/core/ext/filters/client_channel/resolving_lb_policy.cc.o] Error 1
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2234: CMakeFiles/grpc_cronet.dir/src/core/ext/transport/chttp2/transport/chttp2_transport.cc.o] Error 1
...
</code>```

The terminations happen at different stages in the build. Any ideas what is terminating the compiler?

答: Aha, the failures were caused by memory constraints; the make -j without arguments is too aggressive for Windows. Constraining it to a given value solves the problem.</p>

Body:
I am getting c++: fatal errors when trying to build grpc inside a container. Tried it with GNU CC 7, and 10, on three different machines, all running Docker Desktop for Windows.

the basic Dockerfile is mimicing the grpc building docs:

FROM gcc:10.1.0

RUN apt-get update && apt-get upgrade -y && \
    apt-get install -y build-essential autoconf libtool pkg-config git curl cmake

RUN cd /tmp && \
    git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc && \
    cd grpc && \
    git submodule update --init && \
    mkdir -p cmake/build && \
    mkdir -p /opt/grpc && \
    cd cmake/build && \
    cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=/opt/grpc ../.. && \
    make -j && \
    make install

but can't get to a successful build as on all systems, I get this:

c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc.dir/build.make:2130: CMakeFiles/grpc.dir/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc.o] Error 1
make[2]: *** Waiting for unfinished jobs....
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2182: CMakeFiles/grpc_cronet.dir/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** Waiting for unfinished jobs....
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc.dir/build.make:2182: CMakeFiles/grpc.dir/src/core/ext/transport/chttp2/transport/chttp2_transport.cc.o] Error 1
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2598: CMakeFiles/grpc_cronet.dir/src/core/ext/filters/client_channel/client_channel.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc_unsecure.dir/build.make:2208: CMakeFiles/grpc_unsecure.dir/src/core/ext/transport/chttp2/transport/chttp2_transport.cc.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2819: CMakeFiles/grpc_cronet.dir/src/core/ext/filters/client_channel/resolving_lb_policy.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc.dir/build.make:2520: CMakeFiles/grpc.dir/src/core/lib/security/context/security_context.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
[ 89%] Building C object CMakeFiles/grpc.dir/src/core/ext/upb-generated/envoy/api/v2/cluster.upb.c.o
make[2]: *** [CMakeFiles/grpc.dir/build.make:2546: CMakeFiles/grpc.dir/src/core/lib/security/credentials/composite/composite_credentials.cc.o] Error 1
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
c++: fatal error: Killed signal terminated program cc1plus
compilation terminated.
make[2]: *** [CMakeFiles/grpc_unsecure.dir/build.make:2858: CMakeFiles/grpc_unsecure.dir/src/core/ext/filters/client_channel/resolving_lb_policy.cc.o] Error 1
make[2]: *** [CMakeFiles/grpc_cronet.dir/build.make:2234: CMakeFiles/grpc_cronet.dir/src/core/ext/transport/chttp2/transport/chttp2_transport.cc.o] Error 1
...

The terminations happen at different stages in the build. Any ideas what is terminating the compiler?


问:
MacOS Can't start MySQL Server
I have MacOS Sierra. I have installed MySQL Server which has been working, however, after a reboot of the Mac Book, I cannot start the MySQL Server.

I have tried changing the port from 3306 to 3307 in the my.cnf file.

Question

I would appreciate any help on how to start the MySQL Server, and also have it so it starts automatically on MacOS Boot up.

(I am new to Mac, so apologies if this is a basic question).

UPDATE

Looking for error logs, I can't find anything with todays (2/2/2017) timestamp.

Nothing in the data dir:

No files with "mysql" have been modified since I've tried to start the MySQL Server (2/2/2017 after 09:00).

答:
In my case, ownership of the msyql directory had somehow changed to admin:admin. I use ares suggestion to run mysqld from the terminal:

```<code>sudo /usr/local/mysql/support-files/mysql.server start
</code>```

Which showed a permissions error writing to a msyql file.

I fixed with this command:

```<code>sudo chown -R _mysql:wheel /usr/local/mysql/data
</code>```

from this post:

What user should own /usr/local/mysql on Mac?

Title: MacOS Can't start MySQL Server

Body:
In my case, ownership of the msyql directory had somehow changed to admin:admin. I use ares suggestion to run mysqld from the terminal:

sudo /usr/local/mysql/support-files/mysql.server start

Which showed a permissions error writing to a msyql file.

I fixed with this command:

sudo chown -R _mysql:wheel /usr/local/mysql/data

from this post:

What user should own /usr/local/mysql on Mac?


问:
Make Right Answers Green and Wrong Answers Red for JS Quiz
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.

Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899

HTML:

```<code><!DOCTYPE html>
<html>
<head>

<link href ="style.css" rel ="stylesheet">
<!-- <link href="https://fonts.googleapis.com/css?family=OpenSans" rel="stylesheet"> -->
<script src = "main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
<h1>Chapter 1 Quiz</h1>

<form id = "quiz" name = "quiz">
<p class = "questions">What is the capital of Rhode Island?</p>
<input id = "textbox" type = "text" name = "question1">

<p class = "questions">What is the capital of Connecticut?</p>
<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford<br>

<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford<br>

<p class = "questions">What is the capital of New York?</p>
<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany<br>
<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's<br>

<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>

<div id = "after_submit">
<p id = "number_correct"></p>
<p id = "message"></p>
</div>
</html>

</body>

</code>```

JAVASCRIPT:

```<code>
function check(){

    var question1 = document.quiz.question1.value;
    var question2 = document.quiz.question2.value;
    var question3 = document.quiz.question3.value;
    var correct = 0;
    var total_questions = 3;

    if (question1 == "Providence") {
        correct++;
}
    if (question2 == "Hartford") {
        correct++;
}
    if (question3 == "Albany") {
        correct++;
    }

    var score;

    if (correct == 0) {
        score = 2;
    }

    if (correct > 0 && correct < total_questions) {
        score = 1;
    }

    if (correct == total_questions) {
        score = 0;
    }

    $( "input" ).each(function( index ) {
        console.log( index + ": " + $( this ).val() );
        // CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

</code>```

I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.

答:
why simple don't use class:

if(ans == correct) { $(this).toggleClass(corect); correct ++; } if(ans != correct) { $(this).toggleClass(wrong); }

// whidth text color you need on css

Body:
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.

Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899

HTML:

<!DOCTYPE html>

<link href ="style.css" rel ="stylesheet">

Chapter 1 Quiz

<form id = "quiz" name = "quiz">

What is the capital of Rhode Island?

<input id = "textbox" type = "text" name = "question1">

What is the capital of Connecticut?

<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford

<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford

What is the capital of New York?

<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany

<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's

<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>

JAVASCRIPT:

function check(){

    var question1 = document.quiz.question1.value;
    var question2 = document.quiz.question2.value;
    var question3 = document.quiz.question3.value;
    var correct = 0;
    var total_questions = 3;

    if (question1 == "Providence") {
        correct++;
}
    if (question2 == "Hartford") {
        correct++;
}
    if (question3 == "Albany") {
        correct++;
    }

    var score;

    if (correct == 0) {
        score = 2;
    }

    if (correct > 0 && correct < total_questions) {
        score = 1;
    }

    if (correct == total_questions) {
        score = 0;
    }

    $( "input" ).each(function( index ) {
        console.log( index + ": " + $( this ).val() );
        // CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.


问:
I can't use a static std::queue?
I would like to use a static std::queue (static std::queue<Efeito*> efeitos;) to be called in my static functions in the same class, but I tried several ways and the one thing I got is a error:

undefined reference to EfeitosVisuais::efeitos'

Here is the code:

```<code>#include <iostream>
#include <queue>
#include "Efeito.h"
#include "Efeitos Visuais/EfeitoPedregulho.h"

class EfeitosVisuais {
public:
    static std::queue<Efeito*> efeitos;
    static void AddEfeito(double x, double y,char efeito){
        switch(efeito){
            case 'P':
                EfeitoPedregulho *pedregulho = new EfeitoPedregulho(x,y);
                efeitos.push(pedregulho);
                break;
        }
    }

    static void Atualizar(int tempodejogo) {
        if(!efeitos.empty()) {
            for (int i = 0; i < efeitos.size(); i++) {
                efeitos.front()->Atualiza(tempodejogo);
                efeitos.push(efeitos.front());
                efeitos.pop();
            }
        }
    }
};
</code>```

How to solve it?

答:
static data members needs to be defined separately. Just define your static variable outside the class in the .cpp file:

std::queue<Efeito*> EfeitosVisuais::efeitos;
```

<p><strong>Update</strong></p>

<p>As @Remy Lebeau said in the comments, The variable <em>must have</em> exactly one definition so that it doesn't violate ODR - One definition rule. This is why it is important that you define it in the <code>.cpp</code> file because if it's in the <code>.h</code> file, the header file may be included in multiple places which will result in an error. </p>

<p>As @WBuck said,
Since <strong>c++17</strong> you can use inline variables.:</p>

<pre class="lang-cpp prettyprint-override"><code>inline std::queue<Efeito*> efeitos;
</code>```

Also note that if you use constexpr, the variable is implicitly inline.

Title: I can't use a static std::queue?

Body:
I would like to use a static std::queue (static std::queue<Efeito*> efeitos;) to be called in my static functions in the same class, but I tried several ways and the one thing I got is a error:

undefined reference to EfeitosVisuais::efeitos'

Here is the code:

#include <iostream>
#include <queue>
#include "Efeito.h"
#include "Efeitos Visuais/EfeitoPedregulho.h"

class EfeitosVisuais {
public:
    static std::queue<Efeito*> efeitos;
    static void AddEfeito(double x, double y,char efeito){
        switch(efeito){
            case 'P':
                EfeitoPedregulho *pedregulho = new EfeitoPedregulho(x,y);
                efeitos.push(pedregulho);
                break;
        }
    }

    static void Atualizar(int tempodejogo) {
        if(!efeitos.empty()) {
            for (int i = 0; i < efeitos.size(); i++) {
                efeitos.front()->Atualiza(tempodejogo);
                efeitos.push(efeitos.front());
                efeitos.pop();
            }
        }
    }
};

How to solve it?

Body:
static data members needs to be defined separately. Just define your static variable outside the class in the .cpp file:

std::queue<Efeito*> EfeitosVisuais::efeitos;

Update

As @Remy Lebeau said in the comments, The variable must have exactly one definition so that it doesn't violate ODR - One definition rule. This is why it is important that you define it in the .cpp file because if it's in the .h file, the header file may be included in multiple places which will result in an error.

As @WBuck said,
Since c++17 you can use inline variables.:

inline std::queue<Efeito*> efeitos;

Also note that if you use constexpr, the variable is implicitly inline.


问:
How to identify an object and make a relationship among them [c#]
What is the best way to identify the objects and their Relationship between them ?
As i am new to Programming[c# windows application],I am finding difficult in making relationship between objects .
Can anyone suggest me the best way to start with?

Thanks,
Karthik

答:
I'll try and point you in the right direction with a contrived example:

Suppose we want to make a simple management application for supermarket staff. We are required to store some personal information and work-related information, so we'll need name, address, date started, department, and position.

So now we can try and summarise this specification and think about how to model each bit of data.

StaffMember

Name

Address

Date Started

Department

Department

Name

Position

Position

Title

Roles

Now we can map these ideas to c# classes and use properties to hold the bits of data we need:

```<code>class StaffMember
{
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DateStarted { get; set; }
    public Department Department { get; set; }    // class Department
}

class Department
{
    public string Name { get; set; }
    public Position Position { get; set; }    // class Position
}

class Position
{
    public string Title { get; set; }
    public string PrimaryRole { get; set; }
}
</code>```

Sample usage:

```<code>static void Main()
{
    StaffMember employee = new StaffMember();
    employee.Name = "Ali Gray";
    employee.Address = "123 Abc Street";
    employee.DateStarted = DateTime.Now;

    // Now add the employees department
    employee.Department = new Department();
    employee.Department.Name = "Checkout";

    // Now add the employees position
    employee.Department.Position = new Position();
    employee.Department.Position.Title = "Bag Packer";
    employee.Department.Position.PrimaryRole = "Pack bags";
}
</code>```

Obviously this is an extremely simplified example, but hopefully it'll help you on your way to understanding oo design.

Body:
I'll try and point you in the right direction with a contrived example:

Suppose we want to make a simple management application for supermarket staff. We are required to store some personal information and work-related information, so we'll need name, address, date started, department, and position.

So now we can try and summarise this specification and think about how to model each bit of data.

StaffMember

Name

Address

Date Started

Department

Department

Name

Position

Position

Title

Roles

Now we can map these ideas to c# classes and use properties to hold the bits of data we need:

class StaffMember
{
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DateStarted { get; set; }
    public Department Department { get; set; }    // class Department
}

class Department
{
    public string Name { get; set; }
    public Position Position { get; set; }    // class Position
}

class Position
{
    public string Title { get; set; }
    public string PrimaryRole { get; set; }
}

Sample usage:

static void Main()
{
    StaffMember employee = new StaffMember();
    employee.Name = "Ali Gray";
    employee.Address = "123 Abc Street";
    employee.DateStarted = DateTime.Now;

    // Now add the employees department
    employee.Department = new Department();
    employee.Department.Name = "Checkout";

    // Now add the employees position
    employee.Department.Position = new Position();
    employee.Department.Position.Title = "Bag Packer";
    employee.Department.Position.PrimaryRole = "Pack bags";
}

Obviously this is an extremely simplified example, but hopefully it'll help you on your way to understanding oo design.


问:
Replace an Object by another type of Object in a Main[JAVA]
i try to to change a Object to another type of Object in my main. Here is some code to see what i actually mean.

Main.java

```<code>public class Main {
    public static void main(String[] args) {
        Controller newcontroller = Controller.create();
        newcontroller.change();
    }
}
</code>```

Controler.java:

```<code>public class Controller{

    public static Controller create() {
        return new North(0,0);
    }

    public void change() {
    }

}
</code>```

North.java:

```<code>public class North extends Controller{
    int x;
    int y;

    public North(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void change() {
        super.change();
        //Now i have to replace the newcontroller North(x,y) by South(x,y)
        super.newcontroller = new South(this.x, this.y)
    }
}
</code>```

South.java is just like the North one but it changes to North again.
How can i do that? Or am i doing it completly on a false way?
its not allowed to use if, switch, for, while, ... Only linear programming

答:
You need a little modification.

```<code>public class Main {
public static void main(String[] args) {
    Controller ctl = Controller.create();
    ctl.change();
}
</code>```

}

```<code>public class Controller{

public static Controller create() {
    return new North(0,0);
}

public Controller change() {
    return null;
}
</code>```

}

```<code>public class North extends Controller{
int x;
int y;

public North(int x, int y) {
    this.x = x;
    this.y = y;
}

@Override
public Controller change() {
    return new South(this.x, this.y);
}
</code>```

}

```<code>public class South extends Controller {
int x;
int y;

public South(int x, int y) {
    this.x = x;
    this.y = y;
}

@Override
public Controller change() {
    return new North(this.x, this.y);
}
</code>```

}

Body:
i try to to change a Object to another type of Object in my main. Here is some code to see what i actually mean.

Main.java

public class Main {
    public static void main(String[] args) {
        Controller newcontroller = Controller.create();
        newcontroller.change();
    }
}

Controler.java:

public class Controller{

    public static Controller create() {
        return new North(0,0);
    }

    public void change() {
    }

}

North.java:

public class North extends Controller{
    int x;
    int y;

    public North(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void change() {
        super.change();
        //Now i have to replace the newcontroller North(x,y) by South(x,y)
        super.newcontroller = new South(this.x, this.y)
    }
}

South.java is just like the North one but it changes to North again.
How can i do that? Or am i doing it completly on a false way?
its not allowed to use if, switch, for, while, ... Only linear programming

Body:
You need a little modification.

public class Main {
public static void main(String[] args) {
    Controller ctl = Controller.create();
    ctl.change();
}

}

public class Controller{

public static Controller create() {
    return new North(0,0);
}

public Controller change() {
    return null;
}

}

public class North extends Controller{
int x;
int y;

public North(int x, int y) {
    this.x = x;
    this.y = y;
}

@Override
public Controller change() {
    return new South(this.x, this.y);
}

}

public class South extends Controller {
int x;
int y;

public South(int x, int y) {
    this.x = x;
    this.y = y;
}

@Override
public Controller change() {
    return new North(this.x, this.y);
}

}


问:
Numpy concatenate, using * or similar
I have a list of numpy arrays. Something like this (it won't be the same example, but similar)

```<code>lst = [np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1), np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1), np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1)]

</code>```

My lst in this case has 3 numpy arrays where their shape is (6,1), now I'd like to concatenate it, in something like this:

```<code># array([[1, 1, 1],
#        [2, 2, 2],
#        [3, 3, 3],
#        [4, 4, 4],
#        [5, 5, 5],
#        [6, 6, 6]])
</code>```

and this works perfectly doing this...

```<code>example = np.c_[lst[0], lst[1], lst[2]]

</code>```

but my lst is not always the same size, so I tried this.

```<code>example = np.c_[*lst]
</code>```

but it doesn't work. Is there any way to concatenete a whole list in this way?

Title: Numpy concatenate, using * or similar

Body:
I have a list of numpy arrays. Something like this (it won't be the same example, but similar)

lst = [np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1), np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1), np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1)]

My lst in this case has 3 numpy arrays where their shape is (6,1), now I'd like to concatenate it, in something like this:

# array([[1, 1, 1],
#        [2, 2, 2],
#        [3, 3, 3],
#        [4, 4, 4],
#        [5, 5, 5],
#        [6, 6, 6]])

and this works perfectly doing this...

example = np.c_[lst[0], lst[1], lst[2]]

but my lst is not always the same size, so I tried this.

example = np.c_[*lst]

but it doesn't work. Is there any way to concatenete a whole list in this way?

Body:
You can use column_stack function:

import numpy as np

lst = [np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1), np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1), np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1)]

example = np.column_stack(lst)
print(example)

[[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]
 [5 5 5]
 [6 6 6]]


问:
Program in C to count the frequency of a given word in a text file
Program in C to count the frequency of a given word in a text file

I made this program with the purpose of counting the frequency of a given word in a text file, but in count the characters.

Need help to fix it.

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

int main()
{
  FILE * fptr;
  char ch, * word, * a;
  int i=0, p=0;

  word =(char *) malloc(25 * sizeof(char));
  fptr = fopen("text.txt", "r");

  if (!fptr)
  {
    printf("File not found. \n");
  }
  else
  {
    printf("Word: ");
    scanf("%s", word);

    while(word[p]!='\0')
    {
      p++;
    }

    a=(char *) malloc(p * sizeof(char));

    while (*(ch+a) != EOF)
    {
      *(ch+a) = getc(fptr);

      if (*(ch+a) == * word)
      {
        i++;
      }
    }
  }
  if (i==0)
    printf("Word not found.\n");
  else
  {
    printf("Word found %d times.\n",i);
  }

  fclose(fptr);
  return 0;
}
</code>```

答:
The bug in your code is that getc() only get one character into memory. SO you must NOT make this *(ch+a) == * word since ch has a value not an address.
let ch='x' and let a=10 so *(ch+a)==*('x'+10) which would derefernce an address you didn't allocate.

This website implements countOccurancees function, which take a pointer to const char and a file pointer and return the number of word occurrences.

The strstr() helps finding a first occurrence of a word by returning a pointer to the beginning of the  located  sub‐string.

```<code>#define BUFFER_SIZE 100
int countOccurrences(FILE *fptr, const char *word)
{
  char str[BUFFER_SIZE];
  char *pos;

  int index, count;

  count = 0;

  // Read line from file till end of file.
  while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
    {
      index = 0;

      // Find next occurrence of word in str
      while ((pos = strstr(str + index, word)) != NULL)
        {
      // Index of word in str is
      // Memory address of pos - memory
      // address of str.
      index = (pos - str) + 1;

      count++;
        }
    }

  return count;
}
</code>```

So in main function just make i=countOccurrences(fptr, word);

main should be look like

```<code>int main()
{
  FILE * fptr;
  char  * word;
  int i=0;

  word = malloc(25 * sizeof(char));//Do NOT cast
  fptr = fopen("text.txt", "r");

  if (!fptr)
    printf("File not found. \n");

  else
  {
    printf("Word: ");
    scanf("%s", word);
    i=countOccurrences(fptr, word);
  }
  if (i==0)
    printf("Word not found.\n");
  else
    printf("Word found %d times.\n",i);

  fclose(fptr);
  return 0;
}
</code>```

Body:
Program in C to count the frequency of a given word in a text file

I made this program with the purpose of counting the frequency of a given word in a text file, but in count the characters.

Need help to fix it.

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

int main()
{
  FILE * fptr;
  char ch, * word, * a;
  int i=0, p=0;

  word =(char *) malloc(25 * sizeof(char));
  fptr = fopen("text.txt", "r");

  if (!fptr)
  {
    printf("File not found. \n");
  }
  else
  {
    printf("Word: ");
    scanf("%s", word);

    while(word[p]!='\0')
    {
      p++;
    }

    a=(char *) malloc(p * sizeof(char));

    while (*(ch+a) != EOF)
    {
      *(ch+a) = getc(fptr);

      if (*(ch+a) == * word)
      {
        i++;
      }
    }
  }
  if (i==0)
    printf("Word not found.\n");
  else
  {
    printf("Word found %d times.\n",i);
  }

  fclose(fptr);
  return 0;
}

Body:
The bug in your code is that getc() only get one character into memory. SO you must NOT make this *(ch+a) == * word since ch has a value not an address.
let ch='x' and let a=10 so *(ch+a)==*('x'+10) which would derefernce an address you didn't allocate.

This website implements countOccurancees function, which take a pointer to const char and a file pointer and return the number of word occurrences.

The strstr() helps finding a first occurrence of a word by returning a pointer to the beginning of the  located  sub‐string.

#define BUFFER_SIZE 100
int countOccurrences(FILE *fptr, const char *word)
{
  char str[BUFFER_SIZE];
  char *pos;

  int index, count;

  count = 0;

  // Read line from file till end of file.
  while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
    {
      index = 0;

      // Find next occurrence of word in str
      while ((pos = strstr(str + index, word)) != NULL)
        {
      // Index of word in str is
      // Memory address of pos - memory
      // address of str.
      index = (pos - str) + 1;

      count++;
        }
    }

  return count;
}

So in main function just make i=countOccurrences(fptr, word);

main should be look like

int main()
{
  FILE * fptr;
  char  * word;
  int i=0;

  word = malloc(25 * sizeof(char));//Do NOT cast
  fptr = fopen("text.txt", "r");

  if (!fptr)
    printf("File not found. \n");

  else
  {
    printf("Word: ");
    scanf("%s", word);
    i=countOccurrences(fptr, word);
  }
  if (i==0)
    printf("Word not found.\n");
  else
    printf("Word found %d times.\n",i);

  fclose(fptr);
  return 0;
}


问:
Default Locale Used by MSI
Which flavor of Spanish locale is supported by default when building MSI installers?
ES_MX?
ES_AR?
ES_LE?

Thanks!

答:
An MSI package uses the language you set, usually English. Some tools can also create multilingual installers which support multiple languages.

So MSI packages don't support Spanish by default unless you specifically configure them to use Spanish.

Title: Default Locale Used by MSI