问:
Curl Response is Empty after posting data via post php
I have a form where user puts his apiKey then that after checking for errors if everything is good the processing script post the key via curl to my server for verification. then my server should return success true | false and error code if false. but when I send the file the curl response is empty.

```<code>$post['apiKey'] = $apiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$res = curl_exec($ch);
if ($res === FALSE) {
    echo "Curl Error:" . curl_error($ch);
}

curl_close($ch);

print_r($res);
</code>```

Script we are submitting to:

```<code><?php

define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");

require("includes/initialize.php");

if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");

if (!isset($_POST['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");

$apiKey = escape($_POST['apiKey']);

if (isInputEmpty($apiKey)) {
    header(ERROR_HEADER_URL . "emptyFields");

} elseif (!$apiKey == 25) {
    header(ERROR_HEADER_URL . urlencode("invalidKey"));

} else {

    $response = [];

    if (getApiKeyUserDetails($apiKey, $connection)) {

        if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
            $response['success'] = false;
            $response['error'] = 'apiKeyUsed';
        } else {
            makeApiKeyUsed($apiKey, $connection);
            $response['success'] = true;
        }

    } else {
        $response['success'] = false;
        $response['error'] = 'invalidApiKey';
    }

    return json_encode($response);

}
</code>```

答:
You have to send as output the $response not return it:

instead of

```<code>return json_encode($response);
</code>```

use

```<code>echo json_encode($response);
</code>```

Also note that if eihter isInputEmpty($apiKey) or !$apiKey == 25 evaluate true then execution does not enther the last conditional block and you won't have any output in the body of the response.

The script logic is that for some kind of errors a specific header is set to notify the error.

The curl script that send the request should inspect headers too.

To do so you may use the following code to be placed before curl_exec

```<code>$response_headers = [];

curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
    function( $curl, $header ) use ( &$response_headers )
    {
        $len = strlen( $header );
        $header = explode(':', $header, 2);
        if( count( $header ) < 2 ) { return $len; } // ignore invalid headers
        $response_headers[ strtolower( trim( $header[0] ) ) ] = trim( $header[1] );
        return $len;
    }
);
</code>```

Body:
I have a form where user puts his apiKey then that after checking for errors if everything is good the processing script post the key via curl to my server for verification. then my server should return success true | false and error code if false. but when I send the file the curl response is empty.

$post['apiKey'] = $apiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$res = curl_exec($ch);
if ($res === FALSE) {
    echo "Curl Error:" . curl_error($ch);
}

curl_close($ch);

print_r($res);

Script we are submitting to:

<?php

define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");

require("includes/initialize.php");

if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");

if (!isset($_POST['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");

$apiKey = escape($_POST['apiKey']);

if (isInputEmpty($apiKey)) {
    header(ERROR_HEADER_URL . "emptyFields");

} elseif (!$apiKey == 25) {
    header(ERROR_HEADER_URL . urlencode("invalidKey"));

} else {

    $response = [];

    if (getApiKeyUserDetails($apiKey, $connection)) {

        if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
            $response['success'] = false;
            $response['error'] = 'apiKeyUsed';
        } else {
            makeApiKeyUsed($apiKey, $connection);
            $response['success'] = true;
        }

    } else {
        $response['success'] = false;
        $response['error'] = 'invalidApiKey';
    }

    return json_encode($response);

}

Body:
You have to send as output the $response not return it:

instead of

return json_encode($response);

use

echo json_encode($response);

Also note that if eihter isInputEmpty($apiKey) or !$apiKey == 25 evaluate true then execution does not enther the last conditional block and you won't have any output in the body of the response.

The script logic is that for some kind of errors a specific header is set to notify the error.

The curl script that send the request should inspect headers too.

To do so you may use the following code to be placed before curl_exec

$response_headers = [];

curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
    function( $curl, $header ) use ( &$response_headers )
    {
        $len = strlen( $header );
        $header = explode(':', $header, 2);
        if( count( $header ) < 2 ) { return $len; } // ignore invalid headers
        $response_headers[ strtolower( trim( $header[0] ) ) ] = trim( $header[1] );
        return $len;
    }
);


来源: stackexchange

问:
WebView with a collapsible Toolbar? (material design)
I'm developing an Android app with an Activity and two kind of fragments.

Type 1: a fragment with a collapsible toolbar and a RecyclerView as content. (It works).
Layout:

```<code><android.support.design.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/indicaciones"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_add"
        android:visibility="gone"
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Type 2: a fragment with a collapsible toolbar and a WebView as content. (Here is the problem). I've tried changing RecyclerView by "WebView" and it looks like this:

```<code><android.support.design.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/indicaciones"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <WebView
        android:id="@+id/scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_add"
        android:visibility="gone"
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>
</code>```

The problem is that the WebView doesn't appear. Any suggestions? Any idea to achieve this? Am I doing it ok?

Thanks in advance.

EDIT:

I load the webView this way:

```<code>String template = ... (a xml string, well formed).
webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.loadDataWithBaseURL("file:///android_asset/", template, "text/html", "UTF-8", "");
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
</code>```

I have also tried this:

```<code> WebSettings ws = webView.getSettings();
    ws.setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
</code>```

答:
You can listen to the scroll event to make a collapsing effect.

Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="146dp">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="@color/primary"
        app:expandedTitleGravity="bottom"
        app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />

    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_height="match_parent"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Code

```<code>webview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
  @Override
  public void onScrollChange(View view, int i, int i1, int i2, int i3) {
    // i1 last Y, i3 previous Y
    // Do you stuff here. A simple example: (not performant)
    AppBarLayout appBarLayout =
    CollapsingToolbarActivity.this.findViewById(R.id.appBarLayout);
    appBarLayout.setExpanded(i1 < i3, true);
  }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm developing an Android app with an Activity and two kind of fragments.

Type 1: a fragment with a collapsible toolbar and a RecyclerView as content. (It works).
Layout:

<android.support.design.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/indicaciones"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_add"
        android:visibility="gone"
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

Type 2: a fragment with a collapsible toolbar and a WebView as content. (Here is the problem). I've tried changing RecyclerView by "WebView" and it looks like this:

<android.support.design.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/indicaciones"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <WebView
        android:id="@+id/scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_add"
        android:visibility="gone"
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

The problem is that the WebView doesn't appear. Any suggestions? Any idea to achieve this? Am I doing it ok?

Thanks in advance.

EDIT:

I load the webView this way:

String template = ... (a xml string, well formed).
webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.loadDataWithBaseURL("file:///android_asset/", template, "text/html", "UTF-8", "");
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

I have also tried this:

 WebSettings ws = webView.getSettings();
    ws.setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

Body:
You can listen to the scroll event to make a collapsing effect.

Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="146dp">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="@color/primary"
        app:expandedTitleGravity="bottom"
        app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />

    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_height="match_parent"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Code

webview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
  @Override
  public void onScrollChange(View view, int i, int i1, int i2, int i3) {
    // i1 last Y, i3 previous Y
    // Do you stuff here. A simple example: (not performant)
    AppBarLayout appBarLayout =
    CollapsingToolbarActivity.this.findViewById(R.id.appBarLayout);
    appBarLayout.setExpanded(i1 < i3, true);
  }
});

ContentLicense: CC BY-SA 4.0


问:
Best way for Flutter Photo Management
I am creating an app where the user will select some photos for the avatars used in the app. Once selected, on the next launch I want to populate the avatars automatically.

Solution I am Thinking: I will keep a duplicate of the original photo in the app directory and next time I will use the photo to make the avatars.

Issue: Not efficient as the same copy of the image exists.

Question: Since many apps are doing this thing, I want to know the best way to do that, more specifically in Flutter?

答:
There are no best practices in this regard. It depends on your app.

1) Storing your avatars

Takes more storage space. But your app runs faster.

Best when the number of avatars displayed on a single screen is high, but the total number of avatars in your app is small. (E.g.: you show 15 avatars on a single screen, and there are 100 avatars in your database).

2) Generating your avatars

Takes less space. But your app runs slower.

Best when the number of avatars displayed on a single screen is low, but the total number of avatars in your app is large. (E.g.: you only show 3 avatars on a single screen, but there are 100.000 avatars in your database).

Conclusion

Speed is usually more important than storage space, therefor I'd lean towards storing the avatars. But the only true way to get an answer is to test it and see what works best for your specific app.

Title: Best way for Flutter Photo Management


问:
Can't free linked list in objective-C iPhone dev
I'm writing an application for iPhone, that uses a linked list to keep track of a set of points. I've used linked lists time and time again successfully in other C programs, but I've never used a linked list on iPhone, and my 'freeList' function is crashing.

```<code>pointNode * temp;

pointTrain = lPoints->next;
while (pointTrain) {
    temp = pointTrain->next;
    free(pointTrain);
    pointTrain = temp;
}
</code>```

This is how I'm freeing my list, 'lPoints' is the head, and is always allocated during runtime. This code is executed before any more nodes are added, but it seems to still execute even though "pointTrain" is NULL, which SHOULD make it skip the while loop. Unfortunately, the loop is still executed, and the program crashes on free(pointTrain)

Is there something I'm just not seeing?

Points are added like so within a loop:

```<code>pointTrain->x = onPx / trueWidth;
pointTrain->y = onPx % trueWidth;
pointTrain->next = (pointNode*)malloc(sizeof(pointNode));
pointTrain = pointTrain->next;
</code>```

答:
Are you explicitly initializing next to NULL or nil?

If not, its likely to already be set to some non zero value, and therefore while (pointTrain) will still evaluate to true.

Body:
I'm writing an application for iPhone, that uses a linked list to keep track of a set of points. I've used linked lists time and time again successfully in other C programs, but I've never used a linked list on iPhone, and my 'freeList' function is crashing.

pointNode * temp;

pointTrain = lPoints->next;
while (pointTrain) {
    temp = pointTrain->next;
    free(pointTrain);
    pointTrain = temp;
}

This is how I'm freeing my list, 'lPoints' is the head, and is always allocated during runtime. This code is executed before any more nodes are added, but it seems to still execute even though "pointTrain" is NULL, which SHOULD make it skip the while loop. Unfortunately, the loop is still executed, and the program crashes on free(pointTrain)

Is there something I'm just not seeing?

Points are added like so within a loop:

pointTrain->x = onPx / trueWidth;
pointTrain->y = onPx % trueWidth;
pointTrain->next = (pointNode*)malloc(sizeof(pointNode));
pointTrain = pointTrain->next;


问:
How to keep a bash script running in the background
I write a simple bash script:

```<code>while :
do
sleep 2;

//my code

done
</code>```

Now I want this bash script always be running.

```<code>bash mybash.sh > /dev/null &
</code>```

When I run above command my bash works fine. but when I close my terminal I think my bash is killed. because it doesn't work as my script make some files when it running.

答: Run the script "bash script.sh"  in terminal and press ctrl+z and then use 'bg' command to put the script in background</p>

Body:
I write a simple bash script:

while :
do
sleep 2;

//my code

done

Now I want this bash script always be running.

bash mybash.sh > /dev/null &

When I run above command my bash works fine. but when I close my terminal I think my bash is killed. because it doesn't work as my script make some files when it running.


问:
Can I pipe the pathname expansion to a command?
Using bash I want to accomplish what the following command does without using the ls command and instead using pure pathname expansion. Is this possible?

```<code>ls * | tail -1
</code>```

I'm looking for something like

```<code>* | tail -1
</code>```

答:
Yes you can use do that, but * doesn't do what you think it does. It expands to a list of the directory contents and tries to execute itself as a binary. This can be dangerous when your directory contents contain actual executables that are not meant to be run.

You can use a shell built-in without forking a separate process, to do something with the pathname expansion result. For e.g. using printf()

```<code>printf '%s\n' *
</code>```

See what happens when you just try to execute * in the commandline

```<code>mkdir -p foobar
cd foobar
touch zeezee
*
bash: zeezee: command not found
</code>```

You can tail the result of this output and filter the results as you seem convenient.

Body:
Using bash I want to accomplish what the following command does without using the ls command and instead using pure pathname expansion. Is this possible?

ls * | tail -1

I'm looking for something like

* | tail -1

Body:
Yes you can use do that, but * doesn't do what you think it does. It expands to a list of the directory contents and tries to execute itself as a binary. This can be dangerous when your directory contents contain actual executables that are not meant to be run.

You can use a shell built-in without forking a separate process, to do something with the pathname expansion result. For e.g. using printf()

printf '%s\n' *

See what happens when you just try to execute * in the commandline

mkdir -p foobar
cd foobar
touch zeezee
*
bash: zeezee: command not found

You can tail the result of this output and filter the results as you seem convenient.


问:
CSV import looping duplicate times
Rather new to the Python world. I wrote the following script to convert my csv file and overwrite the existing JSON file, ready to upload to Firebase. Problem is, the script is reading each row 4 times which is odd. My code is below, would be great to know where I'm going wrong.

```<code>import csv
import json
from collections import OrderedDict

fieldnames = ("Code", "Currency", "Rate", "Last Updated")
entries = []

with open('rates.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    for row in reader:
        entry = OrderedDict()
        for field in fieldnames:
            entry[field] = row[field]
            entries.append(entry)

output = {
    "rates": entries
    }

with open('rates2.json', 'w') as jsonfile:
    json.dump(output, jsonfile, indent=2, ensure_ascii=False)
    jsonfile.write('\n')
</code>```

Example of the CSV
CSV IMAGE

Example Output

```<code>{
  "rates": [
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    }
  ]
}

</code>```

答:
Just un-indent entries.append(...):

```<code>with open('rates.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    for row in reader:
        entry = OrderedDict()
        for field in fieldnames:
            entry[field] = row[field]
        entries.append(entry)
</code>```

otherwise you are appending a new row for every field, when you in fact only want to do this once per row, not once per field.

Title: CSV import looping duplicate times

Body:
Rather new to the Python world. I wrote the following script to convert my csv file and overwrite the existing JSON file, ready to upload to Firebase. Problem is, the script is reading each row 4 times which is odd. My code is below, would be great to know where I'm going wrong.

import csv
import json
from collections import OrderedDict

fieldnames = ("Code", "Currency", "Rate", "Last Updated")
entries = []

with open('rates.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    for row in reader:
        entry = OrderedDict()
        for field in fieldnames:
            entry[field] = row[field]
            entries.append(entry)

output = {
    "rates": entries
    }

with open('rates2.json', 'w') as jsonfile:
    json.dump(output, jsonfile, indent=2, ensure_ascii=False)
    jsonfile.write('\n')

Example of the CSV
CSV IMAGE

Example Output

{
  "rates": [
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    }
  ]
}

Body:
Just un-indent entries.append(...):

with open('rates.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    for row in reader:
        entry = OrderedDict()
        for field in fieldnames:
            entry[field] = row[field]
        entries.append(entry)

otherwise you are appending a new row for every field, when you in fact only want to do this once per row, not once per field.


问:
Update column value that has one or more same values of other column
I have this statement:

```<code>UPDATE `tblAllocatedLeads`
SET tblAllocatedLeads.fldAllocatedStatus = CASE
WHEN tblAllocatedLeads.fldAllocatedStatus = 'Allocated'
AND
(SELECT COUNT(*) FROM (SELECT * FROM `tblAllocatedLeads`) AS tblallocate WHERE AND tblallocate.fldAllocatedLeadId = tblAllocatedLeads.fldAllocatedLeadId) > 1
THEN 'Outstanding'
END

</code>```

What I wanted is that update all rows where fldAllocatedStatus = 'Allocated' to 'Outstanding' that has one or more same value of column fldAllocatedLeadId to other rows.

my data

```<code>ID   fldAllocatedStatus   fldAllocatedLeadId
1    Accepted             123
2    Rejected             123
3    Allocated            123
4    Allocated            321

</code>```

In this case ID = 3 should update fldAllocatedStatus to 'Outstanding' as it has one or more same fldAllocatedLeadId from ID = 1,2

and ID = 4 should stay 'Allocated' as it doesn't have match of fldAllocatedLeadId with other rows.

right now what it does it updates even the "Accepted,Rejected" which is supposedly to update only rows with "Allocated"

答:
Assuming MySQL, I think you want:

```<code>UPDATE tblAllocatedLeads al JOIN
       (SELECT al2.fldAllocatedLeadId
        FROM tblAllocatedLeads al2
        WHERE al.fldAllocatedStatus <> 'Allocated'
        GROUP BY al2.tblAllocatedLeads
       ) al2
       ON al2.tblAllocatedLeads = al.tblAllocatedLeads
    SET al.fldAllocatedStatus = 'Outstanding'
    WHERE al.fldAllocatedStatus = 'Allocated' ;
</code>```

The subquery gets leads that have some value that is  not allocated.  The outer WHERE only updates the allocated row (if there is one).

Body:
I have this statement:

UPDATE `tblAllocatedLeads`
SET tblAllocatedLeads.fldAllocatedStatus = CASE
WHEN tblAllocatedLeads.fldAllocatedStatus = 'Allocated'
AND
(SELECT COUNT(*) FROM (SELECT * FROM `tblAllocatedLeads`) AS tblallocate WHERE AND tblallocate.fldAllocatedLeadId = tblAllocatedLeads.fldAllocatedLeadId) > 1
THEN 'Outstanding'
END

What I wanted is that update all rows where fldAllocatedStatus = 'Allocated' to 'Outstanding' that has one or more same value of column fldAllocatedLeadId to other rows.

my data

ID   fldAllocatedStatus   fldAllocatedLeadId
1    Accepted             123
2    Rejected             123
3    Allocated            123
4    Allocated            321

In this case ID = 3 should update fldAllocatedStatus to 'Outstanding' as it has one or more same fldAllocatedLeadId from ID = 1,2

and ID = 4 should stay 'Allocated' as it doesn't have match of fldAllocatedLeadId with other rows.

right now what it does it updates even the "Accepted,Rejected" which is supposedly to update only rows with "Allocated"

Body:
Assuming MySQL, I think you want:

UPDATE tblAllocatedLeads al JOIN
       (SELECT al2.fldAllocatedLeadId
        FROM tblAllocatedLeads al2
        WHERE al.fldAllocatedStatus <> 'Allocated'
        GROUP BY al2.tblAllocatedLeads
       ) al2
       ON al2.tblAllocatedLeads = al.tblAllocatedLeads
    SET al.fldAllocatedStatus = 'Outstanding'
    WHERE al.fldAllocatedStatus = 'Allocated' ;

The subquery gets leads that have some value that is  not allocated.  The outer WHERE only updates the allocated row (if there is one).


问:
How to disable an extension for VS2017 but enable for VS2019
I have created a ".vsix" package . I have updated the manifest file with
"InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[15.0,)"

The command used to install the ".vsix" file is
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\VSIXInstaller.exe" /a /q "C:\ccrc.vsix"

But still the extension gets installed for vs2017.

Any way to disable the extension for vs2017, but keep it enabled for vs2019

答:
You explicitly enabled VS 2017 which is version 15. VS 2019 is version 16. Change your manifest to:</p>

```<code>"InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[16.0,)"
</code>```

Body:
You explicitly enabled VS 2017 which is version 15. VS 2019 is version 16. Change your manifest to:

"InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[16.0,)"


问:
Function to get a value from table if not empry else generate new value
```<code>create sequence number_generator as int;

create table my_numbers (
    num int primary key;
);
</code>```

How to implement a function with the following logic:

if my_numbers is not empty then
    delete one row and return the deleted number
else
    return next value from the sequence.

答:
You can do something like this:

```<code>with deleted as (
  delete from my_numbers
  where num in (select min(num) from my_numbers)
  returning num
)
select num
from deleted
union all
select nextval('number_generator')
where not exists (select * from deleted);
</code>```

First the row with the lowest num is deleted, and the deleted number is returned. The final select returns either that number or calls nextval() but only if no row was returned from the delete statement.

To put that into a function use:

create or replace function delete_or_get()
  returns bigint
as
$$
with deleted as (
  delete from my_numbers
  where num in (select min(num) from my_numbers)
  returning num
)
select num
from deleted
union all
select nextval('number_generator')
where not exists (select * from deleted);
$$
language sql;
```

Body:
create sequence number_generator as int;

create table my_numbers (
    num int primary key;
);

How to implement a function with the following logic:

if my_numbers is not empty then
    delete one row and return the deleted number
else
    return next value from the sequence.

Body:
You can do something like this:

with deleted as (
  delete from my_numbers
  where num in (select min(num) from my_numbers)
  returning num
)
select num
from deleted
union all
select nextval('number_generator')
where not exists (select * from deleted);

First the row with the lowest num is deleted, and the deleted number is returned. The final select returns either that number or calls nextval() but only if no row was returned from the delete statement.

To put that into a function use:

create or replace function delete_or_get()
  returns bigint
as
$$
with deleted as (
  delete from my_numbers
  where num in (select min(num) from my_numbers)
  returning num
)
select num
from deleted
union all
select nextval('number_generator')
where not exists (select * from deleted);
$$
language sql;


问:
does an MVC Action have to return an actionResult?
Can a so called action in my controller just be a regular function that returns anything I want or does the return of an ActionResult declare whether its an "action" or not?

I was wondering if i could call functions in my ActionLink in the "actionname" that didn't return actionresults.

答: All public methods of a controller are actions by default, regardless of return type. So, yes, you can call them. Use [NonActionAttribute] to override this default.</p>

OwnerDisplayName: Dacrocky

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Craig Stuntz

ContentLicense: CC BY-SA 2.5


问:
WCF erratically timing out despite binding timeout settings
My system is composed of a bunch of WCF services that can be used by various clients.

The first thing I do is to run the services in interactive mode (I have a console popping and letting me know the service is started).

I can then run a given client that excercises any of my WCF services. When instantiated the client create a channel and associated timeouts in the following way:

```<code>var ctx = new InstanceContext(TestCallbackProxy.Instance);

string baseAddress = Constants.ServiceBaseAddress;

var binding = new NetNamedPipeBinding();
binding.MaxConnections = 10;
binding.OpenTimeout = System.TimeSpan.FromMinutes(1);
binding.CloseTimeout = System.TimeSpan.FromMinutes(1);
binding.ReceiveTimeout = System.TimeSpan.FromMinutes(5);
binding.SendTimeout = System.TimeSpan.FromMinutes(5);

var channelFactory = new DuplexChannelFactory<ITestService>(ctx, binding, new EndpointAddress(baseAddress + serviceName));

 // Create channel to a specified endpoint
 _channel = channelFactory.CreateChannel() as ITestService;
</code>```

Now, the service eventually times out when left unused for a while, which from my understanding is expected. ie. The channel will simply vanish/be discarded by the system if unused - Something to do with reusablility and optimisation I believe.

However, when trying to prove this theory and reducing all the timeouts, I cannot get the service to break. ie. Should the service not timeout/break when trying to use it when left alone for more than 30sec? Used timeouts are:

```<code>binding.OpenTimeout = System.TimeSpan.FromMinutes(0.5);
binding.CloseTimeout = System.TimeSpan.FromMinutes(0.5);
binding.ReceiveTimeout = System.TimeSpan.FromMinutes(0.5);
binding.SendTimeout = System.TimeSpan.FromMinutes(0.5);
</code>```

答:
I think the reason is that you should be setting your timeouts on the service side, where you are setting up your hosts and defining endpoints, not on the client side. Here is an example:

```<code>var binding = new NetNamedPipeBinding();
binding.MaxConnections = 10;
binding.OpenTimeout = TimeSpan.FromMinutes(0.5);
binding.CloseTimeout = TimeSpan.FromMinutes(0.5);
binding.ReceiveTimeout = TimeSpan.FromMinutes(0.5);
binding.SendTimeout = TimeSpan.FromMinutes(0.5);

// Compose URIs
Uri uriBase = new Uri(baseAddress);
Uri uri = new Uri(baseAddress + something);
Uri uriMex = new Uri(baseAddress + something + "/mex");

// Create End Points
SomeHost = new CustomServiceHost(typeof(TestService), uriBase);
SomeHost.AddServiceEndpoint(typeof(ITestService), binding, uri);
SomeHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, uriMex);

// Open the ServiceHost
SomeHost.Open();
</code>```

Now you should see you service dying after 30sec.

Body:
My system is composed of a bunch of WCF services that can be used by various clients.

The first thing I do is to run the services in interactive mode (I have a console popping and letting me know the service is started).

I can then run a given client that excercises any of my WCF services. When instantiated the client create a channel and associated timeouts in the following way:

var ctx = new InstanceContext(TestCallbackProxy.Instance);

string baseAddress = Constants.ServiceBaseAddress;

var binding = new NetNamedPipeBinding();
binding.MaxConnections = 10;
binding.OpenTimeout = System.TimeSpan.FromMinutes(1);
binding.CloseTimeout = System.TimeSpan.FromMinutes(1);
binding.ReceiveTimeout = System.TimeSpan.FromMinutes(5);
binding.SendTimeout = System.TimeSpan.FromMinutes(5);

var channelFactory = new DuplexChannelFactory<ITestService>(ctx, binding, new EndpointAddress(baseAddress + serviceName));

 // Create channel to a specified endpoint
 _channel = channelFactory.CreateChannel() as ITestService;

Now, the service eventually times out when left unused for a while, which from my understanding is expected. ie. The channel will simply vanish/be discarded by the system if unused - Something to do with reusablility and optimisation I believe.

However, when trying to prove this theory and reducing all the timeouts, I cannot get the service to break. ie. Should the service not timeout/break when trying to use it when left alone for more than 30sec? Used timeouts are:

binding.OpenTimeout = System.TimeSpan.FromMinutes(0.5);
binding.CloseTimeout = System.TimeSpan.FromMinutes(0.5);
binding.ReceiveTimeout = System.TimeSpan.FromMinutes(0.5);
binding.SendTimeout = System.TimeSpan.FromMinutes(0.5);

Body:
I think the reason is that you should be setting your timeouts on the service side, where you are setting up your hosts and defining endpoints, not on the client side. Here is an example:

var binding = new NetNamedPipeBinding();
binding.MaxConnections = 10;
binding.OpenTimeout = TimeSpan.FromMinutes(0.5);
binding.CloseTimeout = TimeSpan.FromMinutes(0.5);
binding.ReceiveTimeout = TimeSpan.FromMinutes(0.5);
binding.SendTimeout = TimeSpan.FromMinutes(0.5);

// Compose URIs
Uri uriBase = new Uri(baseAddress);
Uri uri = new Uri(baseAddress + something);
Uri uriMex = new Uri(baseAddress + something + "/mex");

// Create End Points
SomeHost = new CustomServiceHost(typeof(TestService), uriBase);
SomeHost.AddServiceEndpoint(typeof(ITestService), binding, uri);
SomeHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, uriMex);

// Open the ServiceHost
SomeHost.Open();

Now you should see you service dying after 30sec.


问:
Spring Boot & reactor-netty https multiple domains
I'm trying to configure a spring cloud gateway, (on top of project Reactor) to serve HTTPS across two domains.

However it appears that it is unable to use SNI to choose the correct certificate to show to the client.

My configuration is as follows:
I've generated two different private key/ certs and both of those are stored in keystore.jks
both of them have different CommonNames and they also have Subject Alternative Names that match the expected domains.
I've entered the common name into my hosts files. To fool browser/curl into thinking that its two seperate domains.

I've configured application.yml as follows

```<code>server:
  ssl:
    enabled: true
    # The entire purpose of this project is so that client authentication is needed
    client-auth: need

---

spring:
  profiles: development

server:
  ssl:
    key-store: config/keystore.jks
    trust-store: config/truststore.jks
</code>```

The purpose of this is to enable 2 way ssl authentication with two different clients both of whom issue us with their own certificates.

I know netty which is the foundation for spring cloud gateway supports SNI. Is there any way to configure SNI for spring cloud gateway?

答:
It looks like there is an outstanding issue to Support SNI.

https://github.com/spring-cloud/spring-cloud-gateway/issues/1525 which though closed is closed by the issue creator. Not by the framework creators.

This issue links to another issue in reactor.
https://github.com/reactor/reactor-netty/issues/573

Which at the time of writing is not closed.

Body:
I'm trying to configure a spring cloud gateway, (on top of project Reactor) to serve HTTPS across two domains.

However it appears that it is unable to use SNI to choose the correct certificate to show to the client.

My configuration is as follows:
I've generated two different private key/ certs and both of those are stored in keystore.jks
both of them have different CommonNames and they also have Subject Alternative Names that match the expected domains.
I've entered the common name into my hosts files. To fool browser/curl into thinking that its two seperate domains.

I've configured application.yml as follows

server:
  ssl:
    enabled: true
    # The entire purpose of this project is so that client authentication is needed
    client-auth: need

---

spring:
  profiles: development

server:
  ssl:
    key-store: config/keystore.jks
    trust-store: config/truststore.jks

The purpose of this is to enable 2 way ssl authentication with two different clients both of whom issue us with their own certificates.

I know netty which is the foundation for spring cloud gateway supports SNI. Is there any way to configure SNI for spring cloud gateway?


问:
Case in Where Clause SQL (Oracle)
I want to filter a query in the Where Statement. I want to compare IDs with 'IN' but only if an input has value.
If this text comes empty I don't want to compare. Prevent the error query

EXAMPLE:

```<code>StringProductIDs = ''

WHERE
    ({Issue}.[ServiceRequestId] IN (@StringServiceRequestIDs))
    AND ({ServiceRequest}.[Id] IN (@StringServiceRequestIDs))
    AND ({Product}.[Id] IN (@StringProductIDs) OR @StringProductIDs = '')   /* Is this one that i want to prevent*/
    AND EXTRACT(MONTH FROM {Sprint}.[CompleteDate]) = @Month
    AND EXTRACT(YEAR FROM {Sprint}.[CompleteDate]) = @Year
</code>```

In this case, I just want to filter things.id if the value passed as a parameter has value. If it comes empty I don't want to compare and avoid the 'AND' line

Or try another approach:). There is a way to run a query only if this input has value? If it has no value, it returns nothing. If the input has value run normally –

Many thanks

答:
You need OR :

```<code>WHERE  (things.active = 1 AND things.state = 2) AND
       (things.id IN (@INPUT) OR @INPUT IS NULL);
</code>```

Title: Case in Where Clause SQL (Oracle)

Body:
I want to filter a query in the Where Statement. I want to compare IDs with 'IN' but only if an input has value.
If this text comes empty I don't want to compare. Prevent the error query

EXAMPLE:

StringProductIDs = ''

WHERE
    ({Issue}.[ServiceRequestId] IN (@StringServiceRequestIDs))
    AND ({ServiceRequest}.[Id] IN (@StringServiceRequestIDs))
    AND ({Product}.[Id] IN (@StringProductIDs) OR @StringProductIDs = '')   /* Is this one that i want to prevent*/
    AND EXTRACT(MONTH FROM {Sprint}.[CompleteDate]) = @Month
    AND EXTRACT(YEAR FROM {Sprint}.[CompleteDate]) = @Year

In this case, I just want to filter things.id if the value passed as a parameter has value. If it comes empty I don't want to compare and avoid the 'AND' line

Or try another approach:). There is a way to run a query only if this input has value? If it has no value, it returns nothing. If the input has value run normally –

Many thanks

Body:
You need OR :

WHERE  (things.active = 1 AND things.state = 2) AND
       (things.id IN (@INPUT) OR @INPUT IS NULL);


问:
Why the regular expression of the URL rule for the Vutify form validation with port number get error?
The following URL rule without port number is working well.

```<code>export default {
  data: () => ({
    valid: true,
    url: '',
    urlRules: [
      v => !!v || 'URL is required',
      v => (v && v.length <= 256) || 'URL must be less than 256 characters',
      v => /https?:\/\/[\w!?/\+\-_~=;\.,*&@#$%\(\)\'\[\]]+/.test(v) || 'URL must be valid',
    ],
  }),
  components: {
  },
}
</code>```

Then, I've put [0-9]* rule for port number part of the URL as follows.

```<code>export default {
  data: () => ({
    valid: true,
    url: '',
    urlRules: [
      v => !!v || 'URL is required',
      v => (v && v.length <= 256) || 'URL must be less than 256 characters',
      v => /https?:[0-9]*\/\/[\w!?/\+\-_~=;\.,*&@#$%\(\)\'\[\]]+/.test(v) || 'URL must be valid',
    ],
  }),
  components: {
  },
}
</code>```

But this occurs following error:

```<code>  34:36  error  Unnecessary escape character: \+  no-useless-escape
  34:44  error  Unnecessary escape character: \.  no-useless-escape
  34:53  error  Unnecessary escape character: \(  no-useless-escape
  34:55  error  Unnecessary escape character: \)  no-useless-escape
  34:57  error  Unnecessary escape character: \'  no-useless-escape
  34:59  error  Unnecessary escape character: \[  no-useless-escape

✖ 6 problems (6 errors, 0 warnings)
</code>```

I have no idea why the additional port number part breaks the regular expression. Thank you for your suggestion!

答:
The problem is not related to vuetify rules or regular expressions. You should take a look to your ESLint config. This error said that your code failed "no-useless-escape" ESLint rule.

As a quick workaround, you could disable ESLint rule for some lines.
This code should work:

```<code>export default {
  data: () => ({
    valid: true,
    url: '',
    urlRules: [
      v => !!v || 'URL is required',
      v => (v && v.length <= 256) || 'URL must be less than 256 characters', /* eslint-disable-next-line no-useless-escape*/
      v => /https?:[0-9]*\/\/[\w!?/\+\-_~=;\.,*&@#$%\(\)\'\[\]]+/.test(v) || 'URL must be valid',
    ],
  }),
  components: {
  },
}
</code>```

Body:
The following URL rule without port number is working well.

export default {
  data: () => ({
    valid: true,
    url: '',
    urlRules: [
      v => !!v || 'URL is required',
      v => (v && v.length <= 256) || 'URL must be less than 256 characters',
      v => /https?:\/\/[\w!?/\+\-_~=;\.,*&@#$%\(\)\'\[\]]+/.test(v) || 'URL must be valid',
    ],
  }),
  components: {
  },
}

Then, I've put [0-9]* rule for port number part of the URL as follows.

export default {
  data: () => ({
    valid: true,
    url: '',
    urlRules: [
      v => !!v || 'URL is required',
      v => (v && v.length <= 256) || 'URL must be less than 256 characters',
      v => /https?:[0-9]*\/\/[\w!?/\+\-_~=;\.,*&@#$%\(\)\'\[\]]+/.test(v) || 'URL must be valid',
    ],
  }),
  components: {
  },
}

But this occurs following error:

  34:36  error  Unnecessary escape character: \+  no-useless-escape
  34:44  error  Unnecessary escape character: \.  no-useless-escape
  34:53  error  Unnecessary escape character: \(  no-useless-escape
  34:55  error  Unnecessary escape character: \)  no-useless-escape
  34:57  error  Unnecessary escape character: \'  no-useless-escape
  34:59  error  Unnecessary escape character: \[  no-useless-escape

✖ 6 problems (6 errors, 0 warnings)

I have no idea why the additional port number part breaks the regular expression. Thank you for your suggestion!

Body:
The problem is not related to vuetify rules or regular expressions. You should take a look to your ESLint config. This error said that your code failed "no-useless-escape" ESLint rule.

As a quick workaround, you could disable ESLint rule for some lines.
This code should work:

export default {
  data: () => ({
    valid: true,
    url: '',
    urlRules: [
      v => !!v || 'URL is required',
      v => (v && v.length <= 256) || 'URL must be less than 256 characters', /* eslint-disable-next-line no-useless-escape*/
      v => /https?:[0-9]*\/\/[\w!?/\+\-_~=;\.,*&@#$%\(\)\'\[\]]+/.test(v) || 'URL must be valid',
    ],
  }),
  components: {
  },
}


问:
React Native - StackActions.reset does nothing
I have this function which gets executed when a <TouchableWithoutFeedback> area is pressed:

```<code>navigateToRentable = () => {
    console.log('in navigateToRentable');

    this.props
     .navigation
     .dispatch(StackActions.reset({
       index: 0,
       actions: [
         NavigationActions.navigate({
           routeName: 'Rent',
           actions: [
              NavigationActions.navigate({
               routeName: 'Rentable',
             }),
           ]
         }),
       ],
     }))
}
</code>```

I see in navigateToRentable in my console so I know the method is firing, but nothing else happens - there is no other output in the console.

Here is the structure of my Navigation:

CameraNavigator.js

```<code>import React from 'react';
import { StyleSheet, Text, View, Alert, Permissions, Linking, TouchableOpacity, Platform, ImageStore, Dimensions } from 'react-native';
import { createStackNavigator } from 'react-navigation';

import RentScreenNavigator from './RentScreenNavigator';
import RentScreen from '../pages/RentScreen';
import CameraScreen from '../pages/CameraScreen';
import RentableScreen from '../pages/RentableScreen';

export default CameraNavigator = createStackNavigator(
  {
    OpenCamera: {
      screen: CameraScreen,
      navigationOptions: ({ navigation }) => ({
        header: null
      }),
    },
    RentDetails: {
      screen: RentScreen,
      navigationOptions: ({ navigation }) => ({
        header: null
      }),
    },
    Rentable: {
      screen: RentableScreen,
      navigationOptions: ({ navigation }) => ({
        header: null
      }),
    }
  },
  {
    initialRouteName: 'Rent',
  },
);
</code>```

CameraScreenNavigator.js

```<code>import React from 'react';
import { StyleSheet, Text, View, Alert, Permissions, Linking, TouchableOpacity, Platform, ImageStore, Dimensions } from 'react-native';
import { createStackNavigator } from 'react-navigation';

import CameraNavigator from './CameraNavigator';

export default class CameraScreenNavigator extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <CameraNavigator/>
    )
  }
};
</code>```

App.js

```<code>import React from 'react';
import { StyleSheet, Platform, Image, Text, View, ScrollView } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Icon } from 'react-native-elements';
import { createBottomTabNavigator } from 'react-navigation';
import firebase from 'react-native-firebase';
import { YellowBox } from 'react-native';

import HomeScreen from './pages/HomeScreen';
import ProfileScreen from './pages/ProfileScreen';
//import CameraScreen from './pages/CameraScreen';
import CameraScreenNavigator from './components/CameraScreenNavigator';
//import RentScreenNavigator from './components/RentScreenNavigator';

YellowBox.ignoreWarnings(['Class RCTCxxModule']);
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
YellowBox.ignoreWarnings(['You should only render one navigator explicitly in your app, and other navigators should by rendered by including them in that navigator.']);

const AppNavigator = createBottomTabNavigator(
  {
    Home: HomeScreen,
    Profile: ProfileScreen,
    Rent: CameraScreenNavigator,
  },
  {
    navigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === 'Home') {
          iconName = 'home';
        } else if (routeName === 'Profile') {
          iconName = 'user';
        } else if (routeName === 'Rent') {
          iconName = 'plus-square';
        }

        // You can return any component that you like here! We usually use an
        // icon component from react-native-vector-icons
        return (
          <Icon
            name={iconName}
            color={tintColor}
            type='feather'
          />
        )
      }
    }),
    tabBarOptions: {
      activeTintColor: '#fff',
      inactiveTintColor: '#c9fffd',
      activeBackgroundColor: '#6de3dc',
      inactiveBackgroundColor: '#6de3dc'
    },
  },
);

export default class App extends React.Component {
  render() {
    return (
      <AppNavigator/>
    )
  }
}
</code>```

As you can probably tell from the the StackActions.reset, I am trying to navigate to the Rentable route that is part of CameraNavigator, which is a child navigator the main App navigator. I am trying to execute the StackActions.reset from the Home route, which is part of the root App navigator.

In summary, nothing happens when I press the area that should navigate me to the Rentable route.

UPDATE

I have tried:

```<code>this.props
     .navigation
     .dispatch(
         NavigationActions.navigate({
           routeName: 'Rent',
           actions: [
              NavigationActions.navigate({
               routeName: 'Rentable',
             }),
           ]
         }),
     )
</code>```

The first Navigation.navigate works, but the sub-action navigation to Rentable does not.

UPDATE

I am still seeking an answer as to why StackActions.reset isn't working - but for what I was trying to do (navigate to the page of a child navigator from the parent navigator)...I found a workaround/method proposed by @kashishgrover here: https://github.com/react-navigation/react-navigation/issues/2398

However it isn't a perfect workaround - it forces the app to go to an intermediary page, and then listen for a parameter, so for a split second - the intermediary page loads, and then it loads the intended page.

答:
To navigate between stacks I use:

    const navigateToScreen = routeName => {
        navigation.dispatch(StackActions.reset(StackActions.popToTop()))
        navigation.dispatch(NavigationActions.navigate({ routeName }))
    }
```

Body:
I have this function which gets executed when a <TouchableWithoutFeedback> area is pressed:

navigateToRentable = () => {
    console.log('in navigateToRentable');

    this.props
     .navigation
     .dispatch(StackActions.reset({
       index: 0,
       actions: [
         NavigationActions.navigate({
           routeName: 'Rent',
           actions: [
              NavigationActions.navigate({
               routeName: 'Rentable',
             }),
           ]
         }),
       ],
     }))
}

I see in navigateToRentable in my console so I know the method is firing, but nothing else happens - there is no other output in the console.

Here is the structure of my Navigation:

CameraNavigator.js

import React from 'react';
import { StyleSheet, Text, View, Alert, Permissions, Linking, TouchableOpacity, Platform, ImageStore, Dimensions } from 'react-native';
import { createStackNavigator } from 'react-navigation';

import RentScreenNavigator from './RentScreenNavigator';
import RentScreen from '../pages/RentScreen';
import CameraScreen from '../pages/CameraScreen';
import RentableScreen from '../pages/RentableScreen';

export default CameraNavigator = createStackNavigator(
  {
    OpenCamera: {
      screen: CameraScreen,
      navigationOptions: ({ navigation }) => ({
        header: null
      }),
    },
    RentDetails: {
      screen: RentScreen,
      navigationOptions: ({ navigation }) => ({
        header: null
      }),
    },
    Rentable: {
      screen: RentableScreen,
      navigationOptions: ({ navigation }) => ({
        header: null
      }),
    }
  },
  {
    initialRouteName: 'Rent',
  },
);

CameraScreenNavigator.js

import React from 'react';
import { StyleSheet, Text, View, Alert, Permissions, Linking, TouchableOpacity, Platform, ImageStore, Dimensions } from 'react-native';
import { createStackNavigator } from 'react-navigation';

import CameraNavigator from './CameraNavigator';

export default class CameraScreenNavigator extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <CameraNavigator/>
    )
  }
};

App.js

import React from 'react';
import { StyleSheet, Platform, Image, Text, View, ScrollView } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Icon } from 'react-native-elements';
import { createBottomTabNavigator } from 'react-navigation';
import firebase from 'react-native-firebase';
import { YellowBox } from 'react-native';

import HomeScreen from './pages/HomeScreen';
import ProfileScreen from './pages/ProfileScreen';
//import CameraScreen from './pages/CameraScreen';
import CameraScreenNavigator from './components/CameraScreenNavigator';
//import RentScreenNavigator from './components/RentScreenNavigator';

YellowBox.ignoreWarnings(['Class RCTCxxModule']);
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
YellowBox.ignoreWarnings(['You should only render one navigator explicitly in your app, and other navigators should by rendered by including them in that navigator.']);

const AppNavigator = createBottomTabNavigator(
  {
    Home: HomeScreen,
    Profile: ProfileScreen,
    Rent: CameraScreenNavigator,
  },
  {
    navigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === 'Home') {
          iconName = 'home';
        } else if (routeName === 'Profile') {
          iconName = 'user';
        } else if (routeName === 'Rent') {
          iconName = 'plus-square';
        }

        // You can return any component that you like here! We usually use an
        // icon component from react-native-vector-icons
        return (
          <Icon
            name={iconName}
            color={tintColor}
            type='feather'
          />
        )
      }
    }),
    tabBarOptions: {
      activeTintColor: '#fff',
      inactiveTintColor: '#c9fffd',
      activeBackgroundColor: '#6de3dc',
      inactiveBackgroundColor: '#6de3dc'
    },
  },
);

export default class App extends React.Component {
  render() {
    return (
      <AppNavigator/>
    )
  }
}

As you can probably tell from the the StackActions.reset, I am trying to navigate to the Rentable route that is part of CameraNavigator, which is a child navigator the main App navigator. I am trying to execute the StackActions.reset from the Home route, which is part of the root App navigator.

In summary, nothing happens when I press the area that should navigate me to the Rentable route.

UPDATE

I have tried:

this.props
     .navigation
     .dispatch(
         NavigationActions.navigate({
           routeName: 'Rent',
           actions: [
              NavigationActions.navigate({
               routeName: 'Rentable',
             }),
           ]
         }),
     )

The first Navigation.navigate works, but the sub-action navigation to Rentable does not.

UPDATE

I am still seeking an answer as to why StackActions.reset isn't working - but for what I was trying to do (navigate to the page of a child navigator from the parent navigator)...I found a workaround/method proposed by @kashishgrover here: https://github.com/react-navigation/react-navigation/issues/2398

However it isn't a perfect workaround - it forces the app to go to an intermediary page, and then listen for a parameter, so for a split second - the intermediary page loads, and then it loads the intended page.


问:
Excel vba - Format isn't copied to other cell
I got an excel file with an autoincrement on 1 cell, where the numberformat is "000".

```<code>Worksheets("TEST").Range("M17").Value = Worksheets("TEST").Range("M17").Value + 1
Worksheets("TEST").Range("M17").NumberFormat = "000"
</code>```

This works fine, so my first number is: 001 instead of 1.

Now I need to merge this cell to another cell M16 (which displays an input for example: 2020)

```<code>=M16&"/"&M17
</code>```

But for some reason it is losing his NumberFormat, and excel is showing: 2020/1 instead of 2020/001.

I have tried several things, like formatting my cell M18

```<code>Worksheets("TEST").Range("M18").NumberFormat = "0000/000"
</code>```

Or by trying to solve this directly in vba

```<code>Worksheets("TEST").Range("M18").Value = Worksheets("FACTUUR").Range("M16").Value & Worksheets("TEST").Range("M17").Value
Worksheets("TEST").Range("M18").NumberFormat = "0000/000"
</code>```

Or even by changing the format from within Excel itself, but then I get an error message directly (don't know why...)

Any idea on how to solve this?

答:
The first part of your code only changes the way the number is displayed to the user. If you click into cell M17 after running your code, you will see that the actual value is simply 1 and not 001. You need to use format$ as BigBen suggested earlier and then concatenate as per the code below:</p>

```<code>    Worksheets("test").range("M17").value = Worksheets("test").range("M17").value + 1
    Worksheets("test").range("M17").NumberFormat = "000"

    Dim firstValue As String: firstValue = Worksheets("test").range("M16").value
    Dim secondValue As String: secondValue =
    Format$(Worksheets("test").range("M17").value, "000")
    Worksheets("test").range("M18").value = firstValue & "/" & secondValue
</code>```

Body:
I got an excel file with an autoincrement on 1 cell, where the numberformat is "000".

Worksheets("TEST").Range("M17").Value = Worksheets("TEST").Range("M17").Value + 1
Worksheets("TEST").Range("M17").NumberFormat = "000"

This works fine, so my first number is: 001 instead of 1.

Now I need to merge this cell to another cell M16 (which displays an input for example: 2020)

=M16&"/"&M17

But for some reason it is losing his NumberFormat, and excel is showing: 2020/1 instead of 2020/001.

I have tried several things, like formatting my cell M18

Worksheets("TEST").Range("M18").NumberFormat = "0000/000"

Or by trying to solve this directly in vba

Worksheets("TEST").Range("M18").Value = Worksheets("FACTUUR").Range("M16").Value & Worksheets("TEST").Range("M17").Value
Worksheets("TEST").Range("M18").NumberFormat = "0000/000"

Or even by changing the format from within Excel itself, but then I get an error message directly (don't know why...)

Any idea on how to solve this?

Body:
The first part of your code only changes the way the number is displayed to the user. If you click into cell M17 after running your code, you will see that the actual value is simply 1 and not 001. You need to use format$ as BigBen suggested earlier and then concatenate as per the code below:

    Worksheets("test").range("M17").value = Worksheets("test").range("M17").value + 1
    Worksheets("test").range("M17").NumberFormat = "000"

    Dim firstValue As String: firstValue = Worksheets("test").range("M16").value
    Dim secondValue As String: secondValue =
    Format$(Worksheets("test").range("M17").value, "000")
    Worksheets("test").range("M18").value = firstValue & "/" & secondValue


问:
Change global variable from event function
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<table>
    <tr>
        <td class="b1-1"></td>
        <td class="b1-2"></td>
        <td class="b1-3"></td>
    </tr>
    <tr>
        <td class="b2-1"></td>
        <td class="b2-2"></td>
        <td class="b2-3"></td>
    </tr>
    <tr>
        <td class="b3-1"></td>
        <td class="b3-2"></td>
        <td class="b3-3"></td>
    </tr>
</table>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
</code>```

CSS

```<code>.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}
</code>```

Javascript

```<code>var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};
</code>```

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

答:
In your first loop : for (var i = 0; i <= action.length - 1; i++) { ... } you are adding events listeners to each cells. Since the variable gameState is initialized to 0, the condition if (gameState === 0) { ... } will always be true within that loop.

Instead of checking the status of the game during the initialization, just add an event listener as you did, to each cells.

To make sure you pass the correct parameter to the event, you need to wrap the callback within function() { chasvi(param); }, and the whole body of the loop inside another anonymous function, setting another variable to the coordinate i :

```<code>for (var i = 0; i <= action.length - 1; i++) {
    (function(){
          let coor = i;
          let getClassName = "." + action[i].classList.value;
          document.querySelector(getClassName).addEventListener("click", function() { chasvi(coor); });
    }());
}
</code>```

Note that I changed the name of the function to chasvi because you can manage the case X or O in that function.

In each of the functions chasviX and chasviO you are again adding an event listener. This is not good, because on each clicks, you'll add one more event.

Before clicking, there's already an event.

After clicking once, there are 2 events. Another click, and there's 3 events, and so on...

I suggest you to change thoses functions to 1 function that handles both cases :

```<code>function chasvi(cord)
{
    let TextToDisplay;

    if (gameState === 0)
    {
        TextToDisplay = "X";
        gameState = 1;
    }
    else
    {
        TextToDisplay = "O";
        gameState = 0;
    }
    document.querySelector("." + action[cord].classList.value).textContent = TextToDisplay;
}
</code>```

Since there's only 2 states for gameState, you can use a boolean value. You can initialize it to var gameState = false; I randomly choose false for the X.

And then, the function can be simplified to :

```<code>function chasvi(cord)
{
    let TextToDisplay;

    if (gameState === false)
    {
        TextToDisplay = "X";
    }
    else
    {
        TextToDisplay = "O";
    }
    gameState = !gameState; // This swaps the state true/false
    document.querySelector("." + action[cord].classList.value).textContent = TextToDisplay;
}
</code>```

This kind of notation :

```<code>let TextToDisplay;

if (gameState === false)
{
    TextToDisplay = "X";
}
else
{
    TextToDisplay = "O";
}
</code>```

Can be simplified using ternary expressions :

```<code>let TextToDisplay = gameState ? "O" : "X"; // This means if gameState is true, then "O" is returned, else "X"
</code>```

Final code can looks like this :

var action = document.querySelectorAll('td');
    var gameState = false;
    for (var i = 0; i <= action.length - 1; i++) {
        (function(){
          let coor = i;
          getClassName = "." + action[i].classList.value;
          document.querySelector(getClassName).addEventListener("click", function() { chasvi(coor); });
         }());
    }

    function chasvi(cord) {
        let TextToDisplay = gameState ? "O" : "X";
        gameState = !gameState;
        document.querySelector("." + action[cord].classList.value).textContent = TextToDisplay;
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
        padding: 100px 0;
        width: 360px;
        margin: 0 auto;
    }

    table, tbody {
        margin: 0;
        padding: 0;
        width: 360px;
        height: 360px;
    }

    tr {
        width:360px;
        height: 120px;
        margin: 0;
        padding: 0;
    }

    td {
        text-align: center;
        width:120px;
        height: 120px;
        border: 1px solid #333;
        margin: 0;
        padding: 0;
        font-size: 50px;
    }</code>```

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="style.css">

    ```

Body:
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

CSS

.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}

Javascript

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

Body:
In your first loop : for (var i = 0; i <= action.length - 1; i++) { ... } you are adding events listeners to each cells. Since the variable gameState is initialized to 0, the condition if (gameState === 0) { ... } will always be true within that loop.

Instead of checking the status of the game during the initialization, just add an event listener as you did, to each cells.

To make sure you pass the correct parameter to the event, you need to wrap the callback within function() { chasvi(param); }, and the whole body of the loop inside another anonymous function, setting another variable to the coordinate i :

for (var i = 0; i <= action.length - 1; i++) {
    (function(){
          let coor = i;
          let getClassName = "." + action[i].classList.value;
          document.querySelector(getClassName).addEventListener("click", function() { chasvi(coor); });
    }());
}

Note that I changed the name of the function to chasvi because you can manage the case X or O in that function.

In each of the functions chasviX and chasviO you are again adding an event listener. This is not good, because on each clicks, you'll add one more event.

Before clicking, there's already an event.

After clicking once, there are 2 events. Another click, and there's 3 events, and so on...

I suggest you to change thoses functions to 1 function that handles both cases :

function chasvi(cord)
{
    let TextToDisplay;

    if (gameState === 0)
    {
        TextToDisplay = "X";
        gameState = 1;
    }
    else
    {
        TextToDisplay = "O";
        gameState = 0;
    }
    document.querySelector("." + action[cord].classList.value).textContent = TextToDisplay;
}

Since there's only 2 states for gameState, you can use a boolean value. You can initialize it to var gameState = false; I randomly choose false for the X.

And then, the function can be simplified to :

function chasvi(cord)
{
    let TextToDisplay;

    if (gameState === false)
    {
        TextToDisplay = "X";
    }
    else
    {
        TextToDisplay = "O";
    }
    gameState = !gameState; // This swaps the state true/false
    document.querySelector("." + action[cord].classList.value).textContent = TextToDisplay;
}

This kind of notation :

let TextToDisplay;

if (gameState === false)
{
    TextToDisplay = "X";
}
else
{
    TextToDisplay = "O";
}

Can be simplified using ternary expressions :

let TextToDisplay = gameState ? "O" : "X"; // This means if gameState is true, then "O" is returned, else "X"

Final code can looks like this :

var action = document.querySelectorAll('td');
    var gameState = false;
    for (var i = 0; i <= action.length - 1; i++) {
        (function(){
          let coor = i;
          getClassName = "." + action[i].classList.value;
          document.querySelector(getClassName).addEventListener("click", function() { chasvi(coor); });
         }());
    }

    function chasvi(cord) {
        let TextToDisplay = gameState ? "O" : "X";
        gameState = !gameState;
        document.querySelector("." + action[cord].classList.value).textContent = TextToDisplay;
    }

.main {
        padding: 100px 0;
        width: 360px;
        margin: 0 auto;
    }

    table, tbody {
        margin: 0;
        padding: 0;
        width: 360px;
        height: 360px;
    }

    tr {
        width:360px;
        height: 120px;
        margin: 0;
        padding: 0;
    }

    td {
        text-align: center;
        width:120px;
        height: 120px;
        border: 1px solid #333;
        margin: 0;
        padding: 0;
        font-size: 50px;
    }

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
    <div class="main">
    <table>
        <tr>
            <td class="b1-1"></td>
            <td class="b1-2"></td>
            <td class="b1-3"></td>
        </tr>
        <tr>
            <td class="b2-1"></td>
            <td class="b2-2"></td>
            <td class="b2-3"></td>
        </tr>
        <tr>
            <td class="b3-1"></td>
            <td class="b3-2"></td>
            <td class="b3-3"></td>
        </tr>
    </table>
    </div>
    <script src="script.js" type="text/javascript"></script>
    </body>
    </html>


问:
WPF - Change UI culture in callback of asynchrone task
In my application, the user can switch the language. Before the change is apply, a check is done.
In full synchronous this work fine.

Now, the check is asynchronous and a callback on the UI thread set CultureInfo.CurrentUICulture.
But at the end of callback, the CultureInfo.CurrentUICulture is rollback. See this example :

MainWindow.xaml :

<StackPanel>
    <ComboBox SelectionChanged="ComboBox_Selected">
        <ComboBoxItem>en-US</ComboBoxItem>
        <ComboBoxItem>en-GB</ComboBoxItem>
        <ComboBoxItem>fr-FR</ComboBoxItem>
    </ComboBox>
    <Button Click="Button_Click">Display</Button>
</StackPanel>
```

<p>MainWindow.xaml.cs :</p>

<pre class="lang-cs prettyprint-override"><code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ComboBox_Selected(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine($"A - {Thread.CurrentThread.ManagedThreadId} - {Thread.CurrentThread.IsBackground}");
        var to = ((ComboBoxItem)((ComboBox)sender).SelectedItem).Content as string;
        Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith(
            t => SetCurrentCulture(to),
            TaskScheduler.FromCurrentSynchronizationContext()
        );
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(CultureInfo.CurrentCulture.Name);
    }

    private static void SetCurrentCulture(string to)
    {
        Debug.WriteLine($"B - {Thread.CurrentThread.ManagedThreadId} - {Thread.CurrentThread.IsBackground}");
        var culture = new CultureInfo(to);
        CultureInfo.DefaultThreadCurrentCulture = culture;
        CultureInfo.DefaultThreadCurrentUICulture = culture;
        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
    }
}
</code>```

Can you explain why?
How can resolve this?

答:
Can you explain why?

From the docs:

For apps that target the .NET Framework 4.6 or later versions, culture is part of an asynchronous operation's context. In other words, starting with apps that target the .NET Framework 4.6, asynchronous operations by default inherit the values of the CurrentCulture and CurrentUICulture properties of the thread from which they are launched.

How can resolve this?

Add the following switch to your App.config file to switch back to the behaviour seen in .NET Framework 4.5.2:

```<code><runtime>
    <AppContextSwitchOverrides value="Switch.System.Globalization.NoAsyncCurrentCulture=true" />
</runtime>
</code>```

Body:
In my application, the user can switch the language. Before the change is apply, a check is done.
In full synchronous this work fine.

Now, the check is asynchronous and a callback on the UI thread set CultureInfo.CurrentUICulture.
But at the end of callback, the CultureInfo.CurrentUICulture is rollback. See this example :

MainWindow.xaml :

<StackPanel>
    <ComboBox SelectionChanged="ComboBox_Selected">
        <ComboBoxItem>en-US</ComboBoxItem>
        <ComboBoxItem>en-GB</ComboBoxItem>
        <ComboBoxItem>fr-FR</ComboBoxItem>
    </ComboBox>
    <Button Click="Button_Click">Display</Button>
</StackPanel>

MainWindow.xaml.cs :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ComboBox_Selected(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine($"A - {Thread.CurrentThread.ManagedThreadId} - {Thread.CurrentThread.IsBackground}");
        var to = ((ComboBoxItem)((ComboBox)sender).SelectedItem).Content as string;
        Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith(
            t => SetCurrentCulture(to),
            TaskScheduler.FromCurrentSynchronizationContext()
        );
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(CultureInfo.CurrentCulture.Name);
    }

    private static void SetCurrentCulture(string to)
    {
        Debug.WriteLine($"B - {Thread.CurrentThread.ManagedThreadId} - {Thread.CurrentThread.IsBackground}");
        var culture = new CultureInfo(to);
        CultureInfo.DefaultThreadCurrentCulture = culture;
        CultureInfo.DefaultThreadCurrentUICulture = culture;
        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
    }
}

Can you explain why?
How can resolve this?

Body:
Can you explain why?

From the docs:

For apps that target the .NET Framework 4.6 or later versions, culture is part of an asynchronous operation's context. In other words, starting with apps that target the .NET Framework 4.6, asynchronous operations by default inherit the values of the CurrentCulture and CurrentUICulture properties of the thread from which they are launched.

How can resolve this?

Add the following switch to your App.config file to switch back to the behaviour seen in .NET Framework 4.5.2:

<runtime>
    <AppContextSwitchOverrides value="Switch.System.Globalization.NoAsyncCurrentCulture=true" />
</runtime>


答:
You could pass the * expanded list to a function and output the last argument:

```<code>f() { printf "%s\n" "${@: -1}"; }; f *
</code>```

Title: Can I pipe the pathname expansion to a command?

Body:
Using bash I want to accomplish what the following command does without using the ls command and instead using pure pathname expansion. Is this possible?

ls * | tail -1

I'm looking for something like

* | tail -1

Body:
You could pass the * expanded list to a function and output the last argument:

f() { printf "%s\n" "${@: -1}"; }; f *


问:
move files to s3 in EC2
I have S3 bucket in EC2 . I want to remove multiple files between s3 folders . however it showing deleted files but files are still there

command:

aws s3  rm s3://mybucket/path1/publish/test/dummyfile_*.dat

got below message

delete: s3://mybucket/path1/publish/test/dummyfile_*.dat,. But file is still present

can anyone please help

答:
"Amazon S3 offers eventual consistency for overwrite PUTS and DELETES in all Regions."
from https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#CoreConcepts

If you make a copy of a S3 object to an EC2 instance, you simply made a copy of it.
You can use aws s3 sync to synchronize S3 objects (files) between S3 and your EC2 instance, see https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

Title: move files to s3 in EC2


问:
Separate URL and Data for an excel style =HYPERLINK field
I have a csv file which contains a filed which is intended to provide a backing link when inported to Excel. Example content is:

"=HYPERLINK(""https://app.redflagalert.net/search/company/00975699/"",""CHILTERN HILLS MINERAL WATER LIMITED"")"

Is there a way, within CsvHelper to separate this into field into the two separate values?

答:
This should at least give you a good idea of how you could do it.

public class Program
{
    public static void Main(string[] args)
    {
        using (MemoryStream stream = new MemoryStream())
        using (StreamWriter writer = new StreamWriter(stream))
        using (StreamReader reader = new StreamReader(stream))
        using (CsvReader csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            writer.WriteLine("Id,Company");
            writer.WriteLine("1,\"=HYPERLINK(\"\"https://app.redflagalert.net/search/company/00975699/\"\",\"\"CHILTERN HILLS MINERAL WATER LIMITED\"\")\"");
            writer.Flush();
            stream.Position = 0;

            csv.Configuration.RegisterClassMap<FooClassMap>();

            var records = csv.GetRecords<Foo>().ToList();
        }

        Console.ReadKey();
    }
}

public class FooClassMap : ClassMap<Foo>
{
    public FooClassMap()
    {
        Map(m => m.Id);
        Map(m => m.CompanyLink).ConvertUsing(row => row[1].Split(',')[0]);
        Map(m => m.Company).ConvertUsing(row => row[1].Split(',')[1]);
    }
}

public class Foo
{
    public int Id { get; set; }
    public string CompanyLink { get; set; }
    public string Company { get; set; }
}
```


问:
Could not find a version that satisfies the requirement tensorflow
I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing Tensorflow it didn't install, and I got the error message:

Could not find a version that satisfies the requirement TensorFlow (from versions: )
      No matching distribution found for TensorFlow.

Then I tried installing TensorFlow from the command prompt and I got the same error message.
I did however successfully install tflearn.

I also installed Python 2.7, but I got the same error message again. I googled the error and tried some of the things which were suggested to other people, but nothing worked (this included installing Flask).

How can I install Tensorflow? Thanks.

答: use python version 3.6 or 3.7 but the important thing is you should install the python version of 64-bit.</p>


问:
LINQ - Order By and Distinct by different fields. Skip & Take distinct values
I'm trying to ORDER BY some fields but SELECT DISTINCT by another field, and after that apply a Skip & Take

Code:

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

But I'm getting this exception:

System.NotSupportedException: 'The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.'

I understand the reason (the set is being changed between the ordering and the skipping) but can I work around this issue without querying the database more than once (edit: and not fetching more entities than its supposed to)?

EDIT:
I don't think there's an optimal solution for that, so what I did was fetch the values and then paginated them. *sigh*

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

答:
You can take from Distinct values from database and then work in memory like this:

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

You will be querying once as you wanted

Body:
I'm trying to ORDER BY some fields but SELECT DISTINCT by another field, and after that apply a Skip & Take

Code:

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

But I'm getting this exception:

System.NotSupportedException: 'The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.'

I understand the reason (the set is being changed between the ordering and the skipping) but can I work around this issue without querying the database more than once (edit: and not fetching more entities than its supposed to)?

EDIT:
I don't think there's an optimal solution for that, so what I did was fetch the values and then paginated them. *sigh*

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

Body:
You can take from Distinct values from database and then work in memory like this:

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

You will be querying once as you wanted