问:
Android Studio ERROR: Executing external native build for ndkBuild when trying to run Gstreamer tutorial
I am trying to run the gstreamer android tutorial-5 in Android Sudio 3.5 (https://gitlab.freedesktop.org/gstreamer/gst-docs/tree/master/examples/tutorials/android)(https://gitlab.com/eduardoprado/gstreamer-tutorial5) but get the following error:

```<code>ERROR: Cause: executing external native build for ndkBuild C:\Users\Downloads\gst_docs_master_examples_tutorials_android\examples\tutorials\android\android-tutorial-1\jni\Android.mk.
</code>```

I have been following both the gstreamer android tutorials on the gstreamer website along with the stackoverflow thread Gstreamer examples in Android Studio.

The first goal is to get the gstreamer running on android studio.

There are some threads that error is related to white spaces in the path directory but I have checked and all folders have no white space. Below are some of the files that I have been working with and adapting to make the tutorial run.

I have also set my windows environment variable GSTREAMER_ROOT_ANDROID to the unpacked gstreamer binaries along with set it in the android.mk file.

local.properties file

```<code>## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Mon Sep 09 08:16:12 EDT 2019
sdk.dir=C\:\\Users\\AppData\\Local\\Android\\Sdk
ndk.dir=C\:\\Users\\AppData\\Local\\Android\\Sdk\\ndk\\20.0.5594570

</code>```

Android.mk

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := tutorial-5
LOCAL_SRC_FILES := tutorial-5.c
LOCAL_SHARED_LIBRARIES := gstreamer_android
LOCAL_LDLIBS := -llog -landroid
include $(BUILD_SHARED_LIBRARY)

GSTREAMER_ROOT_ANDROID := C\:\\gstreamer_android_binaries

ifndef GSTREAMER_ROOT_ANDROID
$(error GSTREAMER_ROOT_ANDROID is not defined!)
endif

ifeq ($(TARGET_ARCH_ABI),armeabi)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/arm
else ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/armv7
else ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/arm64
else ifeq ($(TARGET_ARCH_ABI),x86)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/x86
else ifeq ($(TARGET_ARCH_ABI),x86_64)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/x86_64
else
$(error Target arch ABI not supported: $(TARGET_ARCH_ABI))
endif

GSTREAMER_NDK_BUILD_PATH  := $(GSTREAMER_ROOT)/share/gst-android/ndk-build/
include $(GSTREAMER_NDK_BUILD_PATH)/plugins.mk
GSTREAMER_PLUGINS         := $(GSTREAMER_PLUGINS_CORE) $(GSTREAMER_PLUGINS_PLAYBACK) $(GSTREAMER_PLUGINS_CODECS) $(GSTREAMER_PLUGINS_NET) $(GSTREAMER_PLUGINS_SYS)
G_IO_MODULES              := gnutls
GSTREAMER_EXTRA_DEPS      := gstreamer-video-1.0
include $(GSTREAMER_NDK_BUILD_PATH)/gstreamer-1.0.mk

</code>```

build.gradle (app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "26.0.3"

    defaultConfig {
        applicationId "com.gst_sdk_tutorials.tutorial_5"
        minSdkVersion 14
        targetSdkVersion 29

        externalNativeBuild {
            ndkBuild {
                arguments "V=1"
            }
        }

        ndk {
            moduleName "tutorial-5"
            abiFilters 'x86', 'armeabi-v7a', 'arm64-v8a'
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
}
</code>```

build.gradle (project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

gradle-wrapper.properties

```<code>#Mon Sep 09 14:10:17 EDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
</code>```

UPDATE
Added the argument "V=1" to the ndkBuild section and received the same error:

```<code>ERROR: Cause: executing external native build for ndkBuild C:\Users\Downloads\gstreamer-tutorial5-master\app\src\main\jni\Android.mk
</code>```

答:
Please, just comment this from build.gradle (app):

```<code>externalNativeBuild {
         ndkBuild {
             path 'src/main/jni/Android.mk'
         }
     }
</code>```

Body:
I am trying to run the gstreamer android tutorial-5 in Android Sudio 3.5 (https://gitlab.freedesktop.org/gstreamer/gst-docs/tree/master/examples/tutorials/android)(https://gitlab.com/eduardoprado/gstreamer-tutorial5) but get the following error:

ERROR: Cause: executing external native build for ndkBuild C:\Users\Downloads\gst_docs_master_examples_tutorials_android\examples\tutorials\android\android-tutorial-1\jni\Android.mk.

I have been following both the gstreamer android tutorials on the gstreamer website along with the stackoverflow thread Gstreamer examples in Android Studio.

The first goal is to get the gstreamer running on android studio.

There are some threads that error is related to white spaces in the path directory but I have checked and all folders have no white space. Below are some of the files that I have been working with and adapting to make the tutorial run.

I have also set my windows environment variable GSTREAMER_ROOT_ANDROID to the unpacked gstreamer binaries along with set it in the android.mk file.

local.properties file

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Mon Sep 09 08:16:12 EDT 2019
sdk.dir=C\:\\Users\\AppData\\Local\\Android\\Sdk
ndk.dir=C\:\\Users\\AppData\\Local\\Android\\Sdk\\ndk\\20.0.5594570

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := tutorial-5
LOCAL_SRC_FILES := tutorial-5.c
LOCAL_SHARED_LIBRARIES := gstreamer_android
LOCAL_LDLIBS := -llog -landroid
include $(BUILD_SHARED_LIBRARY)

GSTREAMER_ROOT_ANDROID := C\:\\gstreamer_android_binaries

ifndef GSTREAMER_ROOT_ANDROID
$(error GSTREAMER_ROOT_ANDROID is not defined!)
endif

ifeq ($(TARGET_ARCH_ABI),armeabi)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/arm
else ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/armv7
else ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/arm64
else ifeq ($(TARGET_ARCH_ABI),x86)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/x86
else ifeq ($(TARGET_ARCH_ABI),x86_64)
GSTREAMER_ROOT        := $(GSTREAMER_ROOT_ANDROID)/x86_64
else
$(error Target arch ABI not supported: $(TARGET_ARCH_ABI))
endif

GSTREAMER_NDK_BUILD_PATH  := $(GSTREAMER_ROOT)/share/gst-android/ndk-build/
include $(GSTREAMER_NDK_BUILD_PATH)/plugins.mk
GSTREAMER_PLUGINS         := $(GSTREAMER_PLUGINS_CORE) $(GSTREAMER_PLUGINS_PLAYBACK) $(GSTREAMER_PLUGINS_CODECS) $(GSTREAMER_PLUGINS_NET) $(GSTREAMER_PLUGINS_SYS)
G_IO_MODULES              := gnutls
GSTREAMER_EXTRA_DEPS      := gstreamer-video-1.0
include $(GSTREAMER_NDK_BUILD_PATH)/gstreamer-1.0.mk

build.gradle (app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "26.0.3"

    defaultConfig {
        applicationId "com.gst_sdk_tutorials.tutorial_5"
        minSdkVersion 14
        targetSdkVersion 29

        externalNativeBuild {
            ndkBuild {
                arguments "V=1"
            }
        }

        ndk {
            moduleName "tutorial-5"
            abiFilters 'x86', 'armeabi-v7a', 'arm64-v8a'
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
}

build.gradle (project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

gradle-wrapper.properties

#Mon Sep 09 14:10:17 EDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

UPDATE
Added the argument "V=1" to the ndkBuild section and received the same error:

ERROR: Cause: executing external native build for ndkBuild C:\Users\Downloads\gstreamer-tutorial5-master\app\src\main\jni\Android.mk

Body:
Please, just comment this from build.gradle (app):

externalNativeBuild {
         ndkBuild {
             path 'src/main/jni/Android.mk'
         }
     }


来源: stackexchange

问:
How to fix 'GitHub.Services.OAuth.VssOAuthTokenRequestException' on a self-hosted runner for GitHub Actions
```# Authentication

√ Connected to GitHub

# Runner Registration

Enter the name of runner: [press Enter for sotzimorg]

This runner will have the following labels: 'self-hosted', 'Linux', 'X64'
Enter any additional labels (ex. label-1,label-2): [press Enter to skip]

A runner exists with the same name
Would you like to replace the existing runner? (Y/N) [press Enter for N] y
√ Successfully replaced the runner
Exception of type 'GitHub.Services.OAuth.VssOAuthTokenRequestException' was thrown.
```

答:
This exception can occur if the system time of your runner is too far part from the real time.

If this is the cause, then just setting the correct time fixes the problem.

ContentLicense: CC BY-SA 4.0


问:
checking if two dataframes have the same values at the same row and column in R
I have these two dataframes

```<code>x = c(2,4,2,4,4,6)
y = c("hi", "xyz" ,"xyz" ,"xyz" ,"xyz" ,"xyz")
z = c(2,4,5,5,5,5)
dfa = data.frame(X = x, Y = y, Z = z)
dfa

   X  Y      Z
1  2  "hi"   2
2  4  "xyz"  4
3  2  "xyz"  5
4  4  "xyz"  5
5  4  "xyz"  5
6  6  "xyz"  5
</code>```

And another one with same rows and columns

```<code>x = c(2,7,8,2,4,6)
y = c("hi", "234" ,"xyz" ,"25" ,"xyz" ,"dfs")
z = c(20,4,5,3,1,5)
dfb = data.frame(X = x, Y = y, Z = z)
dfb

   X  Y      Z
1  2  "hi"   20
2  7  "234"  4
3  8  "xyz"  5
4  2  "25"   3
5  4  "xyz"  1
6  6  "dfs"  5
</code>```

I want to get the number of times for each column that the value in dfa is the same as dfb

So for this example the output would be

```<code>    X   Y   Z
1   2   3   3
</code>```

Kindly let me know how to proceed with this.
Thank you very much

答:
You can use mapply/Map :

```<code>mapply(function(x, y) sum(x== y), dfa, dfb)
</code>```

Or similarly map2_dbl in purrr if you prefer tidyverse

```<code>purrr::map2_dbl(dfa, dfb, ~sum(.x == .y))
</code>```

This is assuming that the columns in both the dataframes are in the same order, if they are not rearrange one dataframe based on another.

```<code>dfa <- dfa[names(dfb)]
</code>```

Body:
I have these two dataframes

x = c(2,4,2,4,4,6)
y = c("hi", "xyz" ,"xyz" ,"xyz" ,"xyz" ,"xyz")
z = c(2,4,5,5,5,5)
dfa = data.frame(X = x, Y = y, Z = z)
dfa

   X  Y      Z
1  2  "hi"   2
2  4  "xyz"  4
3  2  "xyz"  5
4  4  "xyz"  5
5  4  "xyz"  5
6  6  "xyz"  5

And another one with same rows and columns

x = c(2,7,8,2,4,6)
y = c("hi", "234" ,"xyz" ,"25" ,"xyz" ,"dfs")
z = c(20,4,5,3,1,5)
dfb = data.frame(X = x, Y = y, Z = z)
dfb

   X  Y      Z
1  2  "hi"   20
2  7  "234"  4
3  8  "xyz"  5
4  2  "25"   3
5  4  "xyz"  1
6  6  "dfs"  5

I want to get the number of times for each column that the value in dfa is the same as dfb

So for this example the output would be

    X   Y   Z
1   2   3   3

Kindly let me know how to proceed with this.
Thank you very much

Body:
You can use mapply/Map :

mapply(function(x, y) sum(x== y), dfa, dfb)

Or similarly map2_dbl in purrr if you prefer tidyverse

purrr::map2_dbl(dfa, dfb, ~sum(.x == .y))

This is assuming that the columns in both the dataframes are in the same order, if they are not rearrange one dataframe based on another.

dfa <- dfa[names(dfb)]


问:
Best way to do tryMax and tryMin in F#?
Suppose I have a seq and I want to return the largest if there are any elements or None otherwise. F# does not appear to have this built-in.

Here is my attempt:

let tryMax xs =
  if Seq.isEmpty xs
  then
    None
  else
    Seq.max xs |> Some

let tryMin xs =
  if Seq.isEmpty xs
  then
    None
  else
    Seq.min xs |> Some
```

Are there any problems with this approach?

Is there a built-in solution for this?

答:
I think your approach is generally good. There was an answer that is now deleted that suggested to use try/with to prevent double-evaluation of the first item by catching the error for empty sequences, but that too can be expensive.

If you want to prevent double evaluation, you can use Seq.cache, or not use Seq at all (use List or Array instead). Or use fold, which iterates only once:

module Seq =
    let tryMin sq =
        sq
        |> Seq.fold(fun x y ->
            match x with None -> Some y | Some x -> Some(min x y)) None
```

<p>Usage:</p>

```> Seq.tryMin Seq.empty<int>;;
val it : int option = None

> Seq.tryMin (Seq.singleton 2L);;
val it : int64 option = Some 2L

> Seq.tryMin (seq { 2; 3});;
val it : int option = Some 2

> Seq.tryMin (seq { 2; -3});;
val it : int option = Some -3
```

<p>A potentially faster method (I didn't time it), is to prevent the creation of <code>option</code> on each min- or max-calculation result, and at the same time preventing multiple iterations of the first item.</p>

<p>This <em>should</em> have much less GC pressure too ;).</p>

<pre class="lang-ml prettyprint-override"><code>module Seq =
    let tryMin (sq: seq<_>) =
        use e = sq.GetEnumerator()

        // this returns false if there is no first item
        if e.MoveNext() then
            let mutable result = e.Current
            while e.MoveNext() do
                result <- min e.Current result

            Some result
        else
            None
</code>```

Usage:

> Seq.tryMin Seq.empty<int>;;
val it : int option = None

> Seq.tryMin (Seq.singleton 2L);;
val it : int64 option = Some 2L

> Seq.tryMin (seq { 2; 3});;
val it : int option = Some 2

> Seq.tryMin (seq { 2; -3});;
val it : int option = Some -3
```

Title: Best way to do tryMax and tryMin in F#?

Body:
Suppose I have a seq and I want to return the largest if there are any elements or None otherwise. F# does not appear to have this built-in.

Here is my attempt:

let tryMax xs =
  if Seq.isEmpty xs
  then
    None
  else
    Seq.max xs |> Some

let tryMin xs =
  if Seq.isEmpty xs
  then
    None
  else
    Seq.min xs |> Some

Are there any problems with this approach?

Is there a built-in solution for this?

Body:
I think your approach is generally good. There was an answer that is now deleted that suggested to use try/with to prevent double-evaluation of the first item by catching the error for empty sequences, but that too can be expensive.

If you want to prevent double evaluation, you can use Seq.cache, or not use Seq at all (use List or Array instead). Or use fold, which iterates only once:

module Seq =
    let tryMin sq =
        sq
        |> Seq.fold(fun x y ->
            match x with None -> Some y | Some x -> Some(min x y)) None

Usage:

> Seq.tryMin Seq.empty<int>;;
val it : int option = None

> Seq.tryMin (Seq.singleton 2L);;
val it : int64 option = Some 2L

> Seq.tryMin (seq { 2; 3});;
val it : int option = Some 2

> Seq.tryMin (seq { 2; -3});;
val it : int option = Some -3

A potentially faster method (I didn't time it), is to prevent the creation of option on each min- or max-calculation result, and at the same time preventing multiple iterations of the first item.

This should have much less GC pressure too ;).

module Seq =
    let tryMin (sq: seq<_>) =
        use e = sq.GetEnumerator()

        // this returns false if there is no first item
        if e.MoveNext() then
            let mutable result = e.Current
            while e.MoveNext() do
                result <- min e.Current result

            Some result
        else
            None

Usage:

> Seq.tryMin Seq.empty<int>;;
val it : int option = None

> Seq.tryMin (Seq.singleton 2L);;
val it : int64 option = Some 2L

> Seq.tryMin (seq { 2; 3});;
val it : int option = Some 2

> Seq.tryMin (seq { 2; -3});;
val it : int option = Some -3


问:
Unable to push to Heroku due to a package version being 0
I've created my heroku repository that uses python-3.6.9. On an attempt to push to the master branch, the push fails due to pkg-resources being version 0 in my requirements file.

error:

```<code>       ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12)) (from versions: none)
       ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12))
 !     Push rejected, failed to compile Python app.
 !     Push failed
</code>```

requirements (pip freeze > requirements.txt):

```<code>asgiref==3.2.7
astroid==2.4.1
beautifulsoup4==4.9.1
dj-database-url==0.5.0
Django==3.0.6
django-bootstrap4==1.1.1
django-heroku==0.3.1
gunicorn==20.0.4
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
pkg-resources==0.0.0
psycopg2==2.7.7
pylint==2.5.2
pytz==2020.1
six==1.14.0
soupsieve==2.0.1
sqlparse==0.3.1
toml==0.10.1
typed-ast==1.4.1
whitenoise==5.1.0
wrapt==1.12.1
</code>```

答: It`s a bug of pip frozen > requirements.txt command, you should remove string pkg-resources==0.0.0 manually from your file.

Body:
I've created my heroku repository that uses python-3.6.9. On an attempt to push to the master branch, the push fails due to pkg-resources being version 0 in my requirements file.

error:

       ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12)) (from versions: none)
       ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12))
 !     Push rejected, failed to compile Python app.
 !     Push failed

requirements (pip freeze > requirements.txt):

asgiref==3.2.7
astroid==2.4.1
beautifulsoup4==4.9.1
dj-database-url==0.5.0
Django==3.0.6
django-bootstrap4==1.1.1
django-heroku==0.3.1
gunicorn==20.0.4
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
pkg-resources==0.0.0
psycopg2==2.7.7
pylint==2.5.2
pytz==2020.1
six==1.14.0
soupsieve==2.0.1
sqlparse==0.3.1
toml==0.10.1
typed-ast==1.4.1
whitenoise==5.1.0
wrapt==1.12.1


问:
How can I render a button based on condition in html templates | Django
I am trying to render the button based on a condition.

Here I am checking if the combo is in cart, then I will render out the remove button, for that combo only.

But I am not able to do that.

Here in ComboCartItem class combo field is a ForeignKey of class Combo and in Cart class combo_item field is a ManyToManyField of class ComboCartItem

So in general if we want to display a list of all the combos that are present in the cart we can do that by {% for item in cart.combo_item.all %}{{item.combo}}{% endfor %}

But it doesn't work while going for a condition check.

Please help.

```<code>{% if combo in cart.combo_item.all %}
        <button type="submit" class="btn btn-success">Remove?</button>
    {% endif %}
</code>```

This doesn't work. Please help!

l.html

```<code><form method="POST" action="{% url 'carts:combo_add_to_cart' %}" class="form">
    {% csrf_token %}
    <input type="hidden" name="combo_id" value="{{ combo.id }}">
    <button type="submit" class="btn btn-success">Add to Cart</button>
    {% if combo in cart.combo_item.all %}
        <button type="submit" class="btn btn-success">Remove?</button>
    {% endif %}
</form>
</code>```

combo - models.py

```<code>class Combo(models.Model):
    title = models.CharField(max_length=120)
</code>```

cart - models.py

```<code>class ComboCartItem(models.Model):
    combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE)

class Cart(models.Model):
    combo_item = models.ManyToManyField(ComboCartItem, blank=True, null=True)
</code>```

答: You can do another way to solve this by: what you are checking here with a condition do it in your views, pass it by appending into your context data and get the boolean value here and do the operations in django template.</p>

Body:
I am trying to render the button based on a condition.

Here I am checking if the combo is in cart, then I will render out the remove button, for that combo only.

But I am not able to do that.

Here in ComboCartItem class combo field is a ForeignKey of class Combo and in Cart class combo_item field is a ManyToManyField of class ComboCartItem

So in general if we want to display a list of all the combos that are present in the cart we can do that by {% for item in cart.combo_item.all %}{{item.combo}}{% endfor %}

But it doesn't work while going for a condition check.

Please help.

{% if combo in cart.combo_item.all %}
        <button type="submit" class="btn btn-success">Remove?</button>
    {% endif %}

This doesn't work. Please help!

l.html

<form method="POST" action="{% url 'carts:combo_add_to_cart' %}" class="form">
    {% csrf_token %}
    <input type="hidden" name="combo_id" value="{{ combo.id }}">
    <button type="submit" class="btn btn-success">Add to Cart</button>
    {% if combo in cart.combo_item.all %}
        <button type="submit" class="btn btn-success">Remove?</button>
    {% endif %}
</form>

combo - models.py

class Combo(models.Model):
    title = models.CharField(max_length=120)

cart - models.py

class ComboCartItem(models.Model):
    combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE)

class Cart(models.Model):
    combo_item = models.ManyToManyField(ComboCartItem, blank=True, null=True)


问:
Named Arguments do not work in a string with conditional logic
I have a multiline string with an in-line if condition as follows:

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """
</code>```

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}
</code>```

Is there a specific reason why this won't work?

答:
The solution was to opt for a cleaner method as follows, shifting any logic to the named arguments rather than leaving them in-line.</p>

```<code>my_string=  """
    Hello my name is {name}

    {something_else}

    Good bye. """.format(
      name=("John" if client_code == "j" else "Mary"),
      something_else="Additional Message"
    )
</code>```

Body:
I have a multiline string with an in-line if condition as follows:

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}

Is there a specific reason why this won't work?

Body:
The solution was to opt for a cleaner method as follows, shifting any logic to the named arguments rather than leaving them in-line.

my_string=  """
    Hello my name is {name}

    {something_else}

    Good bye. """.format(
      name=("John" if client_code == "j" else "Mary"),
      something_else="Additional Message"
    )


问:
Cannot access data from api
I created function which returns me Object array, but I cant access data from it. Inside function it returns fine, but I need to reuse this function and access data it other components.
I got this:

Function

```<code>export function useFetch(url: string) {
    const [state, setState] = useState({data: null, loading: true})

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch(`${API_URL}${url}`, {
                method: 'GET',
                mode: 'cors',
            });
            if(!response.ok){
                const err = await response.json();
                throw(err);
            }
            const data = await response.json();
            setState({data: data.data, loading: false});
        }
        fetchData();
    }, [])

    return state;
}
</code>```

Inside my Project component a call it like this:

```<code>const { data, loading } = useFetch('/api/projects')
</code>```

this works fine, but when I want to access some data from this array

```<code>{data.map(i => {
    return (
       <p>{i.id}</p>
    )
})}
</code>```

I'm getting:

Projects.tsx?d6a4:27 Uncaught TypeError: Cannot read property 'map' of
  null

答:
Issue is because of initialization, initial value of data is null, and you are trying to loop through it

```<code>useState({data: null, loading: true})
</code>```

Solution :

Either use []

```<code>useState({data: [], loading: true})
</code>```

OR

If you want to keep it null , then check for data before looping it through :

```<code>{data && data.map(i => { // <---- HERE
    return (
       <p>{i.id}</p>
    )
})}
</code>```

Title: Cannot access data from api

Body:
I created function which returns me Object array, but I cant access data from it. Inside function it returns fine, but I need to reuse this function and access data it other components.
I got this:

Function

export function useFetch(url: string) {
    const [state, setState] = useState({data: null, loading: true})

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch(`${API_URL}${url}`, {
                method: 'GET',
                mode: 'cors',
            });
            if(!response.ok){
                const err = await response.json();
                throw(err);
            }
            const data = await response.json();
            setState({data: data.data, loading: false});
        }
        fetchData();
    }, [])

    return state;
}

Inside my Project component a call it like this:

const { data, loading } = useFetch('/api/projects')

this works fine, but when I want to access some data from this array

{data.map(i => {
    return (

{i.id}

    )
})}

I'm getting:

Projects.tsx?d6a4:27 Uncaught TypeError: Cannot read property 'map' of
  null

Body:
Issue is because of initialization, initial value of data is null, and you are trying to loop through it

useState({data: null, loading: true})

Solution :

Either use []

useState({data: [], loading: true})

OR

If you want to keep it null , then check for data before looping it through :

{data && data.map(i => { // <---- HERE
    return (
       <p>{i.id}</p>
    )
})}


问:
When I try to make a button show a different view controller using a segue it adds a black bar at the top
I am using the latest version on Xcode and am trying to connect a button to a new view controller using a segue. In my project I have other buttons that work and the view controller looks normal but when I attach it to this one by control clicking and dragging to another view controller it does this...

(There is a black space at the top rather than the usual full page)

I have also tried

```<code>presentedController.modalPresentationStyle = .fullScreen
</code>```

However this did not work for some reason.
I think a reason that it may not work is because the view controller is disconnected. I need to do this to connect 2 programmatically, how can I fix this?

答:
This is an expected behaviour of iOS 13 modal presentation. If you try with earlier versions than iOS 13 you will see the fullScreen presentation. But if you want to use fullScreen presentation in iOS 13 either you should set modalPresentationStyle of your presented view controller.

presentedController.modalPresentationStyle = .fullScreen
```

Body:
I am using the latest version on Xcode and am trying to connect a button to a new view controller using a segue. In my project I have other buttons that work and the view controller looks normal but when I attach it to this one by control clicking and dragging to another view controller it does this...

(There is a black space at the top rather than the usual full page)

I have also tried

presentedController.modalPresentationStyle = .fullScreen

However this did not work for some reason.
I think a reason that it may not work is because the view controller is disconnected. I need to do this to connect 2 programmatically, how can I fix this?


问:
Predicting from a trained LSTM model
I have trained a model using LSTM, on some data I have collected. I wanted to categorise as either Canine or Feline.

I am attempting to predict a string of text like so

```<code>json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("lstm.hd5")
print("Loaded model from disk")

text_to_predict = ['A 2‐year‐old male domestic shorthair cat was presented for a progressive history of abnormal posture, behavior, and mentation. Menace response was absent bilaterally, and generalized tremors were identified on neurological examination. A neuroanatomical diagnosis of diffuse brain dysfunction was made. A neurodegenerative disorder was suspected. Magnetic resonance imaging findings further supported the clinical suspicion. Whole‐genome sequencing of the affected cat with filtering of variants against a database of unaffected cats was performed. Candidate variants were confirmed by Sanger sequencing followed by genotyping of a control population. Two homozygous private (unique to individual or families and therefore absent from the breed‐matched controlled population) protein‐changing variants in the major facilitator superfamily domain 8 (MFSD8) gene, a known candidate gene for neuronal ceroid lipofuscinosis type 7 (CLN7), were identified. The affected cat was homozygous for the alternative allele at both variants. This is the first report of a pathogenic alteration of the MFSD8 gene in a cat strongly suspected to have CLN7.']

MAX_SEQUENCE_LENGTH = 352
MAX_NB_WORDS = 2000

tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ')
seq = tokenizer.texts_to_sequences(text_to_predict)
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = loaded_model.predict(padded)
labels = ['canine', 'feline']
print(pred, labels[np.argmax(pred)])
</code>```

However, the predictions all come back the same, irrespective of what the string I choose to classify.

[[0.5212073  0.47879276]] canine

I am also unsure as to why I have to set the MAX_SEQUENCE_LENGTH to 352, as it seems my model is expecting an array of that size. Setting it to any other value returns an error of

```<code>ValueError: Error when checking input: expected embedding_1_input to have shape (352,) but got array with shape (250,)
</code>```

My Model training, for reference, is done through this code.

```<code>data = pd.read_csv('data.csv')
data['Text'] = data['Text'].apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x)))

MAX_NB_WORDS = 2000
embed_dim = 128
lstm_out = 196

tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ')
tokenizer.fit_on_texts(data['Text'].values)
X = tokenizer.texts_to_sequences(data['Text'].values)
X = pad_sequences(X)

model = Sequential()
model.add(Embedding(max_fatures, embed_dim,input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(2,activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
print(model.summary())

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

print('model string has been saved')

Y =  data[['canine','feline']]
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 42)
print(X_train.shape,Y_train.shape)
print(X_test.shape,Y_test.shape)

batch_size = 32
model.fit(X_train, Y_train, epochs = 30, batch_size=batch_size, verbose = 2)

#save model for future use.
model.save('lstm.hd5')
</code>```

Any help would be greatly appreciated :D

答:
From your question, I understand that the Model is predicting correctly after Training but it is Training Same Class after Loading the Saved Model.

I recently faced the same issue and the solution to this problem is to Save the Tokenizer, with which the Model was Trained, in a Pickle File and Load the Pickle File when we want to perform Predictions after Loading the Saved Model.

Code for Saving the Tokenizer in a Pickle File:

```<code>import pickle

# saving
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
</code>```

Code for Loading the Pickle File:

```<code>with open('tokenizer.pickle', 'rb') as handle:
    tokenizer2 = pickle.load(handle)
</code>```

In addition to the above code, Some other observations from your code are:

It is recommended to use same Padding while Training the Model and while performing Predictions on the Loaded Model.

So, you can change the code from

X = pad_sequences(X)

to

```<code>X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)
</code>```

The Values of MAX_SEQUENCE_LENGTH and MAX_NB_WORDS should be the same before and after Loading the Model

It is recommended to perform same Data Preprocessing steps before and after Loading the Model. So, you can apply the function, (lambda x: re.sub('[^a-zA-z0-9\s]','',x)) after Loading the Model as well.

The Code, which should work fine is mentioned below:

```<code>data = pd.read_csv('data.csv')
data['Text'] = data['Text'].apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x)))

MAX_NB_WORDS = 2000
embed_dim = 128
lstm_out = 196

tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ')
tokenizer.fit_on_texts(data['Text'].values)

import pickle  # IMPORTANT STEP

# saving
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

X = tokenizer.texts_to_sequences(data['Text'].values)
X = pad_sequences(X, maxlen = MAX_SEQUENCE_LENGTH) # Change Number 2

model = Sequential()
model.add(Embedding(max_fatures, embed_dim,input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(2,activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
print(model.summary())

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

print('model string has been saved')

Y =  data[['canine','feline']]
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 42)
print(X_train.shape,Y_train.shape)
print(X_test.shape,Y_test.shape)

batch_size = 32
model.fit(X_train, Y_train, epochs = 30, batch_size=batch_size, verbose = 2)

#save model for future use.
model.save('lstm.hd5')
</code>```

Modified Code of the Loaded Model is shown below:

```<code>json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("lstm.hd5")
print("Loaded model from disk")

text_to_predict = ['A 2‐year‐old male domestic shorthair cat was presented for a progressive history of abnormal posture, behavior, and mentation. Menace response was absent bilaterally, and generalized tremors were identified on neurological examination. A neuroanatomical diagnosis of diffuse brain dysfunction was made. A neurodegenerative disorder was suspected. Magnetic resonance imaging findings further supported the clinical suspicion. Whole‐genome sequencing of the affected cat with filtering of variants against a database of unaffected cats was performed. Candidate variants were confirmed by Sanger sequencing followed by genotyping of a control population. Two homozygous private (unique to individual or families and therefore absent from the breed‐matched controlled population) protein‐changing variants in the major facilitator superfamily domain 8 (MFSD8) gene, a known candidate gene for neuronal ceroid lipofuscinosis type 7 (CLN7), were identified. The affected cat was homozygous for the alternative allele at both variants. This is the first report of a pathogenic alteration of the MFSD8 gene in a cat strongly suspected to have CLN7.']

text_to_predict = text_to_predict.apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x))) # CHANGE 3

MAX_SEQUENCE_LENGTH = 352
MAX_NB_WORDS = 2000

# Loading the Pickle File ==> IMPORTANT STEP
with open('tokenizer.pickle', 'rb') as handle:
    tokenizer2 = pickle.load(handle)

# tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ') # THIS IS NOT REQUIRED
seq = tokenizer2.texts_to_sequences(text_to_predict)
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = loaded_model.predict(padded)
labels = ['canine', 'feline']
print(pred, labels[np.argmax(pred)])
</code>```

Please reach out if these changes doesn't give you the desired output and I will Happy to help you.

Hope this helps. Happy Learning!

Title: Predicting from a trained LSTM model

Body:
I have trained a model using LSTM, on some data I have collected. I wanted to categorise as either Canine or Feline.

I am attempting to predict a string of text like so

json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("lstm.hd5")
print("Loaded model from disk")

text_to_predict = ['A 2‐year‐old male domestic shorthair cat was presented for a progressive history of abnormal posture, behavior, and mentation. Menace response was absent bilaterally, and generalized tremors were identified on neurological examination. A neuroanatomical diagnosis of diffuse brain dysfunction was made. A neurodegenerative disorder was suspected. Magnetic resonance imaging findings further supported the clinical suspicion. Whole‐genome sequencing of the affected cat with filtering of variants against a database of unaffected cats was performed. Candidate variants were confirmed by Sanger sequencing followed by genotyping of a control population. Two homozygous private (unique to individual or families and therefore absent from the breed‐matched controlled population) protein‐changing variants in the major facilitator superfamily domain 8 (MFSD8) gene, a known candidate gene for neuronal ceroid lipofuscinosis type 7 (CLN7), were identified. The affected cat was homozygous for the alternative allele at both variants. This is the first report of a pathogenic alteration of the MFSD8 gene in a cat strongly suspected to have CLN7.']

MAX_SEQUENCE_LENGTH = 352
MAX_NB_WORDS = 2000

tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ')
seq = tokenizer.texts_to_sequences(text_to_predict)
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = loaded_model.predict(padded)
labels = ['canine', 'feline']
print(pred, labels[np.argmax(pred)])

However, the predictions all come back the same, irrespective of what the string I choose to classify.

[[0.5212073  0.47879276]] canine

I am also unsure as to why I have to set the MAX_SEQUENCE_LENGTH to 352, as it seems my model is expecting an array of that size. Setting it to any other value returns an error of

ValueError: Error when checking input: expected embedding_1_input to have shape (352,) but got array with shape (250,)

My Model training, for reference, is done through this code.

data = pd.read_csv('data.csv')
data['Text'] = data['Text'].apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x)))

MAX_NB_WORDS = 2000
embed_dim = 128
lstm_out = 196

tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ')
tokenizer.fit_on_texts(data['Text'].values)
X = tokenizer.texts_to_sequences(data['Text'].values)
X = pad_sequences(X)

model = Sequential()
model.add(Embedding(max_fatures, embed_dim,input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(2,activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
print(model.summary())

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

print('model string has been saved')

Y =  data[['canine','feline']]
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 42)
print(X_train.shape,Y_train.shape)
print(X_test.shape,Y_test.shape)

batch_size = 32
model.fit(X_train, Y_train, epochs = 30, batch_size=batch_size, verbose = 2)

#save model for future use.
model.save('lstm.hd5')

Any help would be greatly appreciated :D

Body:
From your question, I understand that the Model is predicting correctly after Training but it is Training Same Class after Loading the Saved Model.

I recently faced the same issue and the solution to this problem is to Save the Tokenizer, with which the Model was Trained, in a Pickle File and Load the Pickle File when we want to perform Predictions after Loading the Saved Model.

Code for Saving the Tokenizer in a Pickle File:

import pickle

# saving
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

Code for Loading the Pickle File:

with open('tokenizer.pickle', 'rb') as handle:
    tokenizer2 = pickle.load(handle)

In addition to the above code, Some other observations from your code are:

It is recommended to use same Padding while Training the Model and while performing Predictions on the Loaded Model.

So, you can change the code from

X = pad_sequences(X)

to

X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)

The Values of MAX_SEQUENCE_LENGTH and MAX_NB_WORDS should be the same before and after Loading the Model

It is recommended to perform same Data Preprocessing steps before and after Loading the Model. So, you can apply the function, (lambda x: re.sub('[^a-zA-z0-9\s]','',x)) after Loading the Model as well.

The Code, which should work fine is mentioned below:

data = pd.read_csv('data.csv')
data['Text'] = data['Text'].apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x)))

MAX_NB_WORDS = 2000
embed_dim = 128
lstm_out = 196

tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ')
tokenizer.fit_on_texts(data['Text'].values)

import pickle  # IMPORTANT STEP

# saving
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

X = tokenizer.texts_to_sequences(data['Text'].values)
X = pad_sequences(X, maxlen = MAX_SEQUENCE_LENGTH) # Change Number 2

model = Sequential()
model.add(Embedding(max_fatures, embed_dim,input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(2,activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
print(model.summary())

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

print('model string has been saved')

Y =  data[['canine','feline']]
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 42)
print(X_train.shape,Y_train.shape)
print(X_test.shape,Y_test.shape)

batch_size = 32
model.fit(X_train, Y_train, epochs = 30, batch_size=batch_size, verbose = 2)

#save model for future use.
model.save('lstm.hd5')

Modified Code of the Loaded Model is shown below:

json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("lstm.hd5")
print("Loaded model from disk")

text_to_predict = ['A 2‐year‐old male domestic shorthair cat was presented for a progressive history of abnormal posture, behavior, and mentation. Menace response was absent bilaterally, and generalized tremors were identified on neurological examination. A neuroanatomical diagnosis of diffuse brain dysfunction was made. A neurodegenerative disorder was suspected. Magnetic resonance imaging findings further supported the clinical suspicion. Whole‐genome sequencing of the affected cat with filtering of variants against a database of unaffected cats was performed. Candidate variants were confirmed by Sanger sequencing followed by genotyping of a control population. Two homozygous private (unique to individual or families and therefore absent from the breed‐matched controlled population) protein‐changing variants in the major facilitator superfamily domain 8 (MFSD8) gene, a known candidate gene for neuronal ceroid lipofuscinosis type 7 (CLN7), were identified. The affected cat was homozygous for the alternative allele at both variants. This is the first report of a pathogenic alteration of the MFSD8 gene in a cat strongly suspected to have CLN7.']

text_to_predict = text_to_predict.apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x))) # CHANGE 3

MAX_SEQUENCE_LENGTH = 352
MAX_NB_WORDS = 2000

# Loading the Pickle File ==> IMPORTANT STEP
with open('tokenizer.pickle', 'rb') as handle:
    tokenizer2 = pickle.load(handle)

# tokenizer = Tokenizer(num_words=MAX_NB_WORDS, split=' ') # THIS IS NOT REQUIRED
seq = tokenizer2.texts_to_sequences(text_to_predict)
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = loaded_model.predict(padded)
labels = ['canine', 'feline']
print(pred, labels[np.argmax(pred)])

Please reach out if these changes doesn't give you the desired output and I will Happy to help you.

Hope this helps. Happy Learning!


问:
Core Plot - Histogram
How could I realize a Histogram with corePlot.
Actually I am trying that by using a Bar Chart.

Is in the Bar-Chart any option to group my values.
For example:
so i can print just 3 bars.
So that the values should group like this:

```
  X<br>
 0...5: Barline 1<br>
 6...10:Barline 2 <br>
11...15:Barline 3<br>
```

Is in CorePlot-Bar any property to do that?

thnx

答: No, you'll have to pre-process your data and do the grouping yourself before passing the data to Core Plot.</p>

ContentLicense: CC BY-SA 3.0

Title: Core Plot - Histogram

Body:
How could I realize a Histogram with corePlot.
Actually I am trying that by using a Bar Chart.

Is in the Bar-Chart any option to group my values.
For example:
so i can print just 3 bars.
So that the values should group like this:

  X

 0...5: Barline 1

 6...10:Barline 2

11...15:Barline 3

Is in CorePlot-Bar any property to do that?

thnx


问:
My code problem is that when i run the code then list1st elements is automatically copy to the ll node
My code problem is that when i run the code then list1st elements is automatically copy to the ll node

one class for implementation of linked list:

```<code>public class node {

    static public class Node{
        Node next;
        int data;
        Node(int d)
        {
            this.data=d;
            this.next=null;
        }
        static Node head=null;
        public void add(int data)
        {
             Node new_node = new Node(data);
                new_node.next = head;
                head = new_node;

        }
public void printlist(Node list) {

             Node currNode = list.head;

                System.out.print("Linked List: ");

                // Traverse through the Linked List
                while (currNode != null) {
                    // Print the data at current node
                    System.out.print(currNode.data + " ");

                    // Go to next node
                    currNode = currNode.next;
                }
                System.out.println(" ");
        }
}
}
</code>```

Second class for working on linked list:

```<code>    public class Linked_list {
        public static void main(String args[])
        {
            Node list1=new Node(0);*// 1st linked list*
            list1.add(10);
            list1.add(1);
            list1.add(15);
            list1.add(3);
            list1.add(88);
            list1.printlist(list1);
            Node ll=new Node(0);   **//second linked list**
            ll.add(55);
            ll.add(44);
            ll.printlist(ll);
        }

 }
</code>```

My code problem is that when i run the code then list1st elements is automatically copy to the ll node.

答:
There are a number of things wrong with your code. The main bug is here in your class Node:

```<code>static Node head=null;
</code>```

The field head must not be static. Change it to this:

```<code>private Node head = null;
</code>```

You'll also need to modify the rest of the code to set the head variable appropriately: the add method should return the newly created Node instead of void, and in the main method you need to use the return value.

Why is it wrong to make it static: because static makes it a class-level variable, shared by all instances of the class, and that's not what you want.

More info: Understanding Class Members

Also, the printlist method does not need to take a Node as an argument. Just make it work on the Node you call it on.

Body:
My code problem is that when i run the code then list1st elements is automatically copy to the ll node

one class for implementation of linked list:

public class node {

    static public class Node{
        Node next;
        int data;
        Node(int d)
        {
            this.data=d;
            this.next=null;
        }
        static Node head=null;
        public void add(int data)
        {
             Node new_node = new Node(data);
                new_node.next = head;
                head = new_node;

        }
public void printlist(Node list) {

             Node currNode = list.head;

                System.out.print("Linked List: ");

                // Traverse through the Linked List
                while (currNode != null) {
                    // Print the data at current node
                    System.out.print(currNode.data + " ");

                    // Go to next node
                    currNode = currNode.next;
                }
                System.out.println(" ");
        }
}
}

Second class for working on linked list:

    public class Linked_list {
        public static void main(String args[])
        {
            Node list1=new Node(0);*// 1st linked list*
            list1.add(10);
            list1.add(1);
            list1.add(15);
            list1.add(3);
            list1.add(88);
            list1.printlist(list1);
            Node ll=new Node(0);   **//second linked list**
            ll.add(55);
            ll.add(44);
            ll.printlist(ll);
        }

 }

My code problem is that when i run the code then list1st elements is automatically copy to the ll node.

Body:
There are a number of things wrong with your code. The main bug is here in your class Node:

static Node head=null;

The field head must not be static. Change it to this:

private Node head = null;

You'll also need to modify the rest of the code to set the head variable appropriately: the add method should return the newly created Node instead of void, and in the main method you need to use the return value.

Why is it wrong to make it static: because static makes it a class-level variable, shared by all instances of the class, and that's not what you want.

More info: Understanding Class Members

Also, the printlist method does not need to take a Node as an argument. Just make it work on the Node you call it on.


问:
Android paytm integration - Unable to show Payment Page
I'm trying to integrate paytm payment in my android application. Transaction Initialisation and CHECKSUM verification and also I'm able to get transaction token but I'm not able to get paytm UI on my mobile.

Below mentioned are the logs I get. I don't see any error message in logs.

```<code>I/Timeline: Timeline: Activity_launch_request time:611492681 intent:Intent {
cmp=com.hago.lucky.seven/com.paytm.pgsdk.PaytmPGActivity (has extras) }
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@f9c15c4
I/WebViewFactory: Loading com.google.android.webview version 81.0.4044.138 (code 404413803)
I/cr_LibraryLoader: Loaded native library version number "81.0.4044.138"
W/ago.lucky.seve: Accessing hidden method Landroid/content/Context;-    >bindServiceAsUser(Landroid/content/Intent;Landroid/content/ServiceConnection;ILandroid/os/Handl    er;Landroid/os/UserHandle;)Z (light greylist, reflection)
D/EgretLoader: EgretLoader(Context context)
D/EgretLoader: The context is not activity
W/ContentCatcher: Failed to notify a WebView
I/ago.lucky.seve: ProcessProfilingInfo new_methods=0 is saved saved_to_disk=0     resolve_classes_delay=8000
D/ViewRootImpl[PaytmPGActivity]: changeCanvasOpacity: opaque=false
D/ViewRootImpl[PaytmPGActivity]: changeCanvasOpacity: opaque=true
W/ContentCatcher: Failed to notify a WebView
</code>```

I added implementation 'com.paytm:pgplussdk:1.4.4' in build.gradle
I added maven {
            url "https://artifactory.paytm.in/libs-release-local"
        } in my app level build.gradle.

What would we be wrong in my code ? Thanks in advance.

答:
I have shared the logic I implemented with Paytm suppor.

Found that issue is, I have Paytm app which is downloaded from play store and trying staging integration. Once I uninstalled Paytm app, it worked successfully.

I got this information from Paytm Support

Body:
I'm trying to integrate paytm payment in my android application. Transaction Initialisation and CHECKSUM verification and also I'm able to get transaction token but I'm not able to get paytm UI on my mobile.

Below mentioned are the logs I get. I don't see any error message in logs.

I/Timeline: Timeline: Activity_launch_request time:611492681 intent:Intent {
cmp=com.hago.lucky.seven/com.paytm.pgsdk.PaytmPGActivity (has extras) }
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@f9c15c4
I/WebViewFactory: Loading com.google.android.webview version 81.0.4044.138 (code 404413803)
I/cr_LibraryLoader: Loaded native library version number "81.0.4044.138"
W/ago.lucky.seve: Accessing hidden method Landroid/content/Context;-    >bindServiceAsUser(Landroid/content/Intent;Landroid/content/ServiceConnection;ILandroid/os/Handl    er;Landroid/os/UserHandle;)Z (light greylist, reflection)
D/EgretLoader: EgretLoader(Context context)
D/EgretLoader: The context is not activity
W/ContentCatcher: Failed to notify a WebView
I/ago.lucky.seve: ProcessProfilingInfo new_methods=0 is saved saved_to_disk=0     resolve_classes_delay=8000
D/ViewRootImpl[PaytmPGActivity]: changeCanvasOpacity: opaque=false
D/ViewRootImpl[PaytmPGActivity]: changeCanvasOpacity: opaque=true
W/ContentCatcher: Failed to notify a WebView

I added implementation 'com.paytm:pgplussdk:1.4.4' in build.gradle
I added maven {
            url "https://artifactory.paytm.in/libs-release-local"
        } in my app level build.gradle.

What would we be wrong in my code ? Thanks in advance.


问:
Create dynamic component (ComponentFactoryResolver) with dynamic template
I want to dynamically create a component with a dynamic template, so that interpolations of this template will resolve in the context of the dynamic component.

I know that I can use this code to create a dynamic component (which must be mentioned in entryComponents on the module):

My static component:

@Component({
  selector: 'html-type',
  template: `<ng-template #htmlcontrolcomponent></ng-template>`
})
export class HtmlTypeComponent implements AfterViewInit{

  @ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) {
    super();
   }

  ngAfterViewInit() {
    this.createComponent("
{{contextvar}}
");
  }

  createComponent(template) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.template = template;       // this doesn't work, is there a way to do it?
  }
```

<p>Component that should be dynamically added:</p>

<pre class="lang-js prettyprint-override"><code>import { Component} from '@angular/core';

@Component({
  selector: 'html-control',
  template: '',
})
export class HtmlControlComponent {
   contextvar: string = "This is my current context";
}

</code>```

Is there a way to reassign the template of a dynamically created component?

What I wanted to achieve: The template of the dynamic component should be dynamic (entered by user and sanitized)

答:
You could try to use <ng-content> with projectableNodes parameter of the createComponent() function. Try the following

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

@Component({
  selector: 'html-control',
  template: `<ng-content></ng-content>`,      // <-- add `<ng-content>` here
})
export class HtmlControlComponent {
   contextvar: string = "This is my current context";
}
```

<p>static component</p>

<pre class="lang-js prettyprint-override"><code>createComponent(template) {
  this.entry.clear();
  const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
  const componentRef = this.entry.createComponent(factory, 0, undefined, [[template]]);    // <-- add `template` here
}
</code>```

Here [[template]] argument is sent to projectableNodes parameter of type any[][]

Untested code. Might need to iron out some kinks.

Body:
I want to dynamically create a component with a dynamic template, so that interpolations of this template will resolve in the context of the dynamic component.

I know that I can use this code to create a dynamic component (which must be mentioned in entryComponents on the module):

My static component:

@Component({
  selector: 'html-type',
  template: `<ng-template #htmlcontrolcomponent></ng-template>`
})
export class HtmlTypeComponent implements AfterViewInit{

  @ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) {
    super();
   }

  ngAfterViewInit() {
    this.createComponent("
{{contextvar}}
");
  }

  createComponent(template) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.template = template;       // this doesn't work, is there a way to do it?
  }

Component that should be dynamically added:

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

@Component({
  selector: 'html-control',
  template: '',
})
export class HtmlControlComponent {
   contextvar: string = "This is my current context";
}

Is there a way to reassign the template of a dynamically created component?

What I wanted to achieve: The template of the dynamic component should be dynamic (entered by user and sanitized)

Body:
You could try to use <ng-content> with projectableNodes parameter of the createComponent() function. Try the following

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

@Component({
  selector: 'html-control',
  template: `<ng-content></ng-content>`,      // <-- add `<ng-content>` here
})
export class HtmlControlComponent {
   contextvar: string = "This is my current context";
}

static component

createComponent(template) {
  this.entry.clear();
  const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
  const componentRef = this.entry.createComponent(factory, 0, undefined, [[template]]);    // <-- add `template` here
}

Here [[template]] argument is sent to projectableNodes parameter of type any[][]

Untested code. Might need to iron out some kinks.


问:
Is it possible to change the height on a jquery ui progressbar
I have a progress bar in a html table cell.  It seems to expand to the width of the table cell but i want to explicitly specify the height of the progress bar.

Is it possible to specify the height of a jQuery progress bar?

```<code>    $(this).progressbar({
        value: parseInt($(this).attr("rel"))
    });
</code>```

答:
Of course it is. There's even a resizable progress bar demo.

Too fancy for you? Just use .height():

```<code>$('#progressbar').height(400);
</code>```

Demo: http://jsfiddle.net/mattball/N5AVv/

Body:
I have a progress bar in a html table cell.  It seems to expand to the width of the table cell but i want to explicitly specify the height of the progress bar.

Is it possible to specify the height of a jQuery progress bar?

    $(this).progressbar({
        value: parseInt($(this).attr("rel"))
    });

Body:
Of course it is. There's even a resizable progress bar demo.

Too fancy for you? Just use .height():

$('#progressbar').height(400);

Demo: http://jsfiddle.net/mattball/N5AVv/


问:
How to simplify the process of evaluating cells with respect to the average value of a column
I want to review each cell of my dataframe to check if each value is lower than 50% of the columns mean. I tried with the following code, but it is super inefficient and it get stuck.

```<code>for col, value in data.items():
    mean = data[col].mean()
    for i in value:
        for day in data.index:
            if i < 0.5 * mean:
                data.loc[day, col] = 0
</code>```

How could I simplify or do it better?

The dataframe is the following one:

```<code>                  Log  1233.de  asdad.w.1  fff.op

Tagname

01/06/2008 00:00    0   343.04      73.75   79.03

02/06/2008 00:00    0   332.31      73.71   79.21

03/06/2008 00:00    0   339.25      75.77   80.11

04/06/2008 00:00    0   353.25      76.47   79.75

05/06/2008 00:00    0   353.44      77.35   82.48
</code>```

Which is uploaded as:

```<code>dat =  pd.read_csv('data.csv', header = 0, index_col = "Tagname")

data = pd.DataFrame(dat)
</code>```

答:
Idea is compare mean of all columns by mean, multiple by 0.5 and the compare by DataFrame.lt with set 0 values by DataFrame.mask:

```<code>data = data.mask(data.lt(data.mean() * 0.5), 0)
</code>```

Body:
I want to review each cell of my dataframe to check if each value is lower than 50% of the columns mean. I tried with the following code, but it is super inefficient and it get stuck.

for col, value in data.items():
    mean = data[col].mean()
    for i in value:
        for day in data.index:
            if i < 0.5 * mean:
                data.loc[day, col] = 0

How could I simplify or do it better?

The dataframe is the following one:

                  Log  1233.de  asdad.w.1  fff.op

Tagname

01/06/2008 00:00    0   343.04      73.75   79.03

02/06/2008 00:00    0   332.31      73.71   79.21

03/06/2008 00:00    0   339.25      75.77   80.11

04/06/2008 00:00    0   353.25      76.47   79.75

05/06/2008 00:00    0   353.44      77.35   82.48

Which is uploaded as:

dat =  pd.read_csv('data.csv', header = 0, index_col = "Tagname")

data = pd.DataFrame(dat)

Body:
Idea is compare mean of all columns by mean, multiple by 0.5 and the compare by DataFrame.lt with set 0 values by DataFrame.mask:

data = data.mask(data.lt(data.mean() * 0.5), 0)


问:
React-Admin How to change the "Dashboard" name in the menu
How can I change the "dashoboard" menu name in the react-admin?

By default it's name is always "Dashboard" even in the Demo

the name is Dashboard. Someone knows a way to change the name or if it is even possible to change?

答:
So more detailed answer is:

Override layout

// in src/Admin.js
  <Admin
        layout={MyLayout}
        title="SuperCoolProject"
        theme={myTheme}
        dataProvider={dataProvider}
        authProvider={authProvider}
      >
```

<ol start="2">
<li>Use custom menu in layout. (it's not sidebar)</li>
</ol>

<pre class="lang-js prettyprint-override"><code>// in src/MyLayout.js
import React from "react";
import { Layout } from "react-admin";
import MyMenu from "./MyMenu";

const MyLayout = (props) => <Layout {...props} menu={MyMenu} />;

export default MyLayout;
</code>```

Change menu so it still renders resources and add custom MenuItemLinks you need (vs. one hardcoded "dashboard")

// in src/Menu.js
import React from "react";
import { useSelector } from "react-redux";
import { useMediaQuery } from "@material-ui/core";
import { MenuItemLink, getResources } from "react-admin";
import DefaultIcon from "@material-ui/icons/ViewList";
import SettingsIcon from "@material-ui/icons/Settings";
import HomeIcon from "@material-ui/icons/Home";
import HelpIcon from "@material-ui/icons/Help";

const Menu = ({ onMenuClick, logout }) => {
  const isXSmall = useMediaQuery((theme) => theme.breakpoints.down("xs"));
  const open = useSelector((state) => state.admin.ui.sidebarOpen);
  const resources = useSelector(getResources);
  return (

      <MenuItemLink
        to="/home"
        primaryText="Home"
        leftIcon={<HomeIcon />}
        onClick={onMenuClick}
        sidebarIsOpen={open}
      />
      {resources.map((resource) => (
        <MenuItemLink
          key={resource.name}
          to={`/${resource.name}`}
          primaryText={
            (resource.options && resource.options.label) || resource.name
          }
          leftIcon={resource.icon ? <resource.icon /> : <DefaultIcon />}
          onClick={onMenuClick}
          sidebarIsOpen={open}
        />
      ))}
      <MenuItemLink
        to="/custom-route"
        primaryText="Settings"
        leftIcon={<SettingsIcon />}
        onClick={onMenuClick}
        sidebarIsOpen={open}
      />
      <MenuItemLink
        to="/help-center"
        primaryText="Help Center"
        leftIcon={<HelpIcon />}
        onClick={onMenuClick}
        sidebarIsOpen={open}
      />
      {isXSmall && logout}

  );
};

export default Menu;

```

Body:
So more detailed answer is:

Override layout

// in src/Admin.js
  <Admin
        layout={MyLayout}
        title="SuperCoolProject"
        theme={myTheme}
        dataProvider={dataProvider}
        authProvider={authProvider}
      >

Use custom menu in layout. (it's not sidebar)

// in src/MyLayout.js
import React from "react";
import { Layout } from "react-admin";
import MyMenu from "./MyMenu";

const MyLayout = (props) => <Layout {...props} menu={MyMenu} />;

export default MyLayout;

Change menu so it still renders resources and add custom MenuItemLinks you need (vs. one hardcoded "dashboard")

// in src/Menu.js
import React from "react";
import { useSelector } from "react-redux";
import { useMediaQuery } from "@material-ui/core";
import { MenuItemLink, getResources } from "react-admin";
import DefaultIcon from "@material-ui/icons/ViewList";
import SettingsIcon from "@material-ui/icons/Settings";
import HomeIcon from "@material-ui/icons/Home";
import HelpIcon from "@material-ui/icons/Help";

const Menu = ({ onMenuClick, logout }) => {
  const isXSmall = useMediaQuery((theme) => theme.breakpoints.down("xs"));
  const open = useSelector((state) => state.admin.ui.sidebarOpen);
  const resources = useSelector(getResources);
  return (
    <div>
      <MenuItemLink
        to="/home"
        primaryText="Home"
        leftIcon={<HomeIcon />}
        onClick={onMenuClick}
        sidebarIsOpen={open}
      />
      {resources.map((resource) => (
        <MenuItemLink
          key={resource.name}
          to={`/${resource.name}`}
          primaryText={
            (resource.options && resource.options.label) || resource.name
          }
          leftIcon={resource.icon ? <resource.icon /> : <DefaultIcon />}
          onClick={onMenuClick}
          sidebarIsOpen={open}
        />
      ))}
      <MenuItemLink
        to="/custom-route"
        primaryText="Settings"
        leftIcon={<SettingsIcon />}
        onClick={onMenuClick}
        sidebarIsOpen={open}
      />
      <MenuItemLink
        to="/help-center"
        primaryText="Help Center"
        leftIcon={<HelpIcon />}
        onClick={onMenuClick}
        sidebarIsOpen={open}
      />
      {isXSmall && logout}
    </div>
  );
};

export default Menu;


问:
Replace \r from json in shell
I have below JSON in a variable name TASK_DEFINTIION
It has a \r character at the end of "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r" under containerDefinitions

I am using TASK_DEFINITION_AFTER= 'echo $TASK_DEFINTIION | sed "s/\\r//g"' to remove the \r but seems it is removing all the hidden carriage return but not removing the one which is visible as regular character.

Any help would be highly appriciated.

```<code>{
      "memory": "1024",
      "networkMode": "awsvpc",
      "family": "ecs-php-demo",
      "placementConstraints": [],
      "cpu": "512",
      "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "volumes": [],
      "requiresCompatibilities": [
        "FARGATE"
      ],
      "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "containerDefinitions": [
        {
          "memoryReservation": 256,
          "environment": [],
          "name": "ecs-php-demo",
          "mountPoints": [],
          "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r",
          "cpu": 0,
          "portMappings": [
            {
              "protocol": "tcp",
              "containerPort": 8080,
              "hostPort": 8080
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs",
              "awslogs-group": "/ecs/ecs-php-demo"
            }
          },
          "essential": true,
          "volumesFrom": []
        }
      ]
    }
</code>```

答:
Using jq rtrimstr to stay conform with the JSON syntax:

#!/usr/bin/bash

TASK_DEFINTIION="$(
  jq '.containerDefinitions[].image|=rtrimstr("\r")' <<<"$TASK_DEFINTIION"
)"

echo "$TASK_DEFINTIION"
```

<p><code>man jq</code>:</p>

<blockquote>
  <p><strong><code>rtrimstr(str)</code></strong>
        Outputs its input with the given suffix string removed, if it ends with it.</p>

```      jq ´[.[]|rtrimstr("foo")]´
         ["fo", "foo", "barfoo", "foobar", "foob"]
      => ["fo","","bar","foobar","foob"]
```

Title: Replace \r from json in shell

Body:
I have below JSON in a variable name TASK_DEFINTIION
It has a \r character at the end of "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r" under containerDefinitions

I am using TASK_DEFINITION_AFTER= 'echo $TASK_DEFINTIION | sed "s/\\r//g"' to remove the \r but seems it is removing all the hidden carriage return but not removing the one which is visible as regular character.

Any help would be highly appriciated.

{
      "memory": "1024",
      "networkMode": "awsvpc",
      "family": "ecs-php-demo",
      "placementConstraints": [],
      "cpu": "512",
      "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "volumes": [],
      "requiresCompatibilities": [
        "FARGATE"
      ],
      "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "containerDefinitions": [
        {
          "memoryReservation": 256,
          "environment": [],
          "name": "ecs-php-demo",
          "mountPoints": [],
          "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r",
          "cpu": 0,
          "portMappings": [
            {
              "protocol": "tcp",
              "containerPort": 8080,
              "hostPort": 8080
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs",
              "awslogs-group": "/ecs/ecs-php-demo"
            }
          },
          "essential": true,
          "volumesFrom": []
        }
      ]
    }

Body:
Using jq rtrimstr to stay conform with the JSON syntax:

#!/usr/bin/bash

TASK_DEFINTIION="$(
  jq '.containerDefinitions[].image|=rtrimstr("\r")' <<<"$TASK_DEFINTIION"
)"

echo "$TASK_DEFINTIION"

man jq:

rtrimstr(str)
        Outputs its input with the given suffix string removed, if it ends with it.

      jq ´[.[]|rtrimstr("foo")]´
         ["fo", "foo", "barfoo", "foobar", "foob"]
      => ["fo","","bar","foobar","foob"]


问:
Why do I get unexpected behavior in Python isinstance after pickling?
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:

```<code>from __future__ import with_statement
import pickle

# Simple class definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Create an instance of the class
x = myclass(100)

# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
    pickle.dump(x, f)

# Replace class with exact same definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
    x2 = pickle.load(f)

# The class names appear to match
print x.__class__
print x2.__class__

# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
</code>```

Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.

答:
Change your code to print the id of x.__class__ and x2.__class__ and you'll see that they are different:

```<code>$ python foo4.py
199876736
200015248
</code>```

OwnerDisplayName: Ben Hoffstein

ContentLicense: CC BY-SA 2.5

Body:
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:

from __future__ import with_statement
import pickle

# Simple class definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Create an instance of the class
x = myclass(100)

# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
    pickle.dump(x, f)

# Replace class with exact same definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
    x2 = pickle.load(f)

# The class names appear to match
print x.__class__
print x2.__class__

# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)

Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.

LastEditorDisplayName: Rich B

Body:
Change your code to print the id of x.__class__ and x2.__class__ and you'll see that they are different:

$ python foo4.py
199876736
200015248

OwnerDisplayName: Jacob Gabrielson


问:
IE : Unable to download * from *. Unable to open this Internet site. The requested site is either unavailable or cannot be found
I have an issue with my website and IE. I have a file Document.ashx that becomes a document from my database depending on the parameter passed in the query string.

The file works if:

You're on my website and click a download link.

You access anything on my site and paste the URL into the address bar and access it.

You've already access the document link once before, even if it did error.

It doesn't work if:

You've not accessed my site with the current IE open and paste the link in the address bar. It displays the following error:

Windows Internet Explorer

Unable to download Document.ashx from MyHostName.

Unable to open this Internet site.

The requested site is either unavailable or cannot be found.

Please try again later.

Does anyone have a clue what would cause this. Naturally it works fine in Firefox.

I've gotten several people in my office to try it with IE and they all get the same issue. They all say it works in Firefox.

答:
It sounds like I problem I came accross with IE 8 only. When I was tracking down a solution I came across 2 solutions. One of them should correct this issue.

Just to let you know it is a fix on the client machine as it is how IE coded that causes the issue.

Fixes:
http://support.microsoft.com/kb/815313
http://support.microsoft.com/kb/323308


问:
Which .ssh/known_hosts file is used by npm in Azure?
Running a npm install git+ssh://<git repo url> from the Kudu's console in an Azure App Service instance fails with following error:

```<code>npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.
</code>```

People often solve this error by adding the host's key to the .ssh/known_hosts file. The problem is that the correct key is already there. If it wasn't there, git clone <git repo url> would fail with the same error, but it does not. It successfully clones the repository.

In order to debug the issue, I tried to set the SSH's log level to DEBUG3 via the ~/.ssh/config file but the output did not change (while with git clone, it prints the debug info).

So, because of that I suspect that the problem is that the SSH client used by npm in Azure does not take the ~/.ssh directory into account.

My question is, is this documented somewhere or is it bug? Do you have any idea in which component the bug is?

FTR, the full output is:

```<code>npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: Cloning into bare repository 'D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85'...
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85:
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: Host key verification failed.
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: fatal: Could not read from remote repository.
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85:
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: Please make sure you have the correct access rights
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: and the repository exists.
npm ERR! Windows_NT 6.2.9200
npm ERR! argv "D:\\Program Files (x86)\\nodejs\\4.2.3\\node.exe" "D:\\Program Files (x86)\\npm\\3.5.1\\node_modules\\npm\\bin\\npm-cli.js" "install" "git+ssh://<git repo url>"
npm ERR! node v4.2.3
npm ERR! npm  v3.5.1
npm ERR! code 128

npm ERR! Command failed: git -c core.longpaths=true clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85
npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     D:\home\site\foo\npm-debug.log
</code>```

答:
So for me the problem was that my app service was deployed through Github and hence had a deployment key associated with it's repo on Github.

To be able to access my other private repos I needed to do the following.

Remove the deployment key.

Get the public key from https://[your-web-app].scm.azurewebsites.net/api/sshkey?ensurePublicKey=1

Add the key to my SSH keys in github.

After this npm would happily install my private repos.

Body:
Running a npm install git+ssh://<git repo url> from the Kudu's console in an Azure App Service instance fails with following error:

npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.

People often solve this error by adding the host's key to the .ssh/known_hosts file. The problem is that the correct key is already there. If it wasn't there, git clone <git repo url> would fail with the same error, but it does not. It successfully clones the repository.

In order to debug the issue, I tried to set the SSH's log level to DEBUG3 via the ~/.ssh/config file but the output did not change (while with git clone, it prints the debug info).

So, because of that I suspect that the problem is that the SSH client used by npm in Azure does not take the ~/.ssh directory into account.

My question is, is this documented somewhere or is it bug? Do you have any idea in which component the bug is?

FTR, the full output is:

npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: Cloning into bare repository 'D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85'...
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85:
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: Host key verification failed.
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: fatal: Could not read from remote repository.
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85:
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: Please make sure you have the correct access rights
npm ERR! git clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85: and the repository exists.
npm ERR! Windows_NT 6.2.9200
npm ERR! argv "D:\\Program Files (x86)\\nodejs\\4.2.3\\node.exe" "D:\\Program Files (x86)\\npm\\3.5.1\\node_modules\\npm\\bin\\npm-cli.js" "install" "git+ssh://<git repo url>"
npm ERR! node v4.2.3
npm ERR! npm  v3.5.1
npm ERR! code 128

npm ERR! Command failed: git -c core.longpaths=true clone --template=D:\local\AppData\npm-cache\_git-remotes\_templates --mirror <git repo url> D:\local\AppData\npm-cache\_git-remotes\git-ssh-<git repo url>-dc8c35134031285cb7109c3e32618e85
npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     D:\home\site\foo\npm-debug.log


问:
How do I create a shortcut via command-line in Windows?
I want my .bat script (test.bat) to create a shortcut to itself so that I can copy it to my windows 8 Startup folder.

I have written this line of code to copy the file but I haven't yet found a way to create the said shortcut, as you can see it only copies the script.

```<code>xcopy "C:\Users\Gabriel\Desktop\test.bat" "C:\Users\Gabriel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
</code>```

Can you help me out?

答:
I created a VB script and run it either from command line or from a Java process.
I also tried to catch errors when creating the shortcut so I can have a better error handling.

```<code>Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)

'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number

'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number

'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number

'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number
</code>```

I run the script with the following commmand:

```<code>cscript /b script.vbs shortcutFuturePath targetPath startInProperty
</code>```

It is possible to have it working even without setting the 'Start in' property in some cases.

Body:
I want my .bat script (test.bat) to create a shortcut to itself so that I can copy it to my windows 8 Startup folder.

I have written this line of code to copy the file but I haven't yet found a way to create the said shortcut, as you can see it only copies the script.

xcopy "C:\Users\Gabriel\Desktop\test.bat" "C:\Users\Gabriel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

Can you help me out?

Body:
I created a VB script and run it either from command line or from a Java process.
I also tried to catch errors when creating the shortcut so I can have a better error handling.

Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)

'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number

'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number

'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number

'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number

I run the script with the following commmand:

cscript /b script.vbs shortcutFuturePath targetPath startInProperty

It is possible to have it working even without setting the 'Start in' property in some cases.


问:
Filtering out data based effective and Term Data
I have query contains both start and end date, i would like to filter out data based on two dates. I need only 2019 and higher data either based on start or end date, if you can have a look examples. i need ID 1,2,3,6,7 and 4,5 is not required. We can do based on extract year for both start and end date. but looking for better approach Thanks!</p>

```<code>CREATE TABLE TEMP
(
ID INT,
SDate DATE,
EDate DATE
)

INSERT INTO TEMP
SELECT 1,'01/01/2014', '01/01/2019' FROM DUAL
UNION ALL
SELECT 2,'01/01/2015', '01/01/2020' FROM DUAL
UNION ALL
SELECT 3,'01/01/2019', '12/31/2019' FROM DUAL
UNION ALL
SELECT 4,'01/01/2012', '12/31/2018' FROM DUAL
UNION ALL
SELECT 5,'01/01/2010', '10/01/2016' FROM DUAL
 UNION ALL
SELECT 6,'06/01/2020', '10/01/2020' FROM DUAL
UNION ALL
SELECT 7,'01/01/2021', '03/01/2021' FROM DUAL
</code>```

答:
You can simply use the condition on edate as follows:

```<code>select * from emp
where edate >= date '2019-01-01';
</code>```

This will use the index on edate, if any.

Body:
I have query contains both start and end date, i would like to filter out data based on two dates. I need only 2019 and higher data either based on start or end date, if you can have a look examples. i need ID 1,2,3,6,7 and 4,5 is not required. We can do based on extract year for both start and end date. but looking for better approach Thanks!

CREATE TABLE TEMP
(
ID INT,
SDate DATE,
EDate DATE
)

INSERT INTO TEMP
SELECT 1,'01/01/2014', '01/01/2019' FROM DUAL
UNION ALL
SELECT 2,'01/01/2015', '01/01/2020' FROM DUAL
UNION ALL
SELECT 3,'01/01/2019', '12/31/2019' FROM DUAL
UNION ALL
SELECT 4,'01/01/2012', '12/31/2018' FROM DUAL
UNION ALL
SELECT 5,'01/01/2010', '10/01/2016' FROM DUAL
 UNION ALL
SELECT 6,'06/01/2020', '10/01/2020' FROM DUAL
UNION ALL
SELECT 7,'01/01/2021', '03/01/2021' FROM DUAL

Body:
You can simply use the condition on edate as follows:

select * from emp
where edate >= date '2019-01-01';

This will use the index on edate, if any.


问:
test the existence of property in a deep object structure
In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a property may be undefined (so mediaGroup may not be set).

What is a simple way to say:

```<code>if( entry.mediaGroup[0].contents[0].url ){
   console.log( entry.mediaGroup[0].contents[0].url )
}
</code>```

without generating an error? This way will generate an undefined error if any point along the way is undefined.

My solution

```<code>if(entry) && (entry.mediaGroup) && (entry.MediaGroup[0]) ...snip...){
   console.log(entry.mediaGroup[0].contents[0].url)
}
</code>```

which is pretty lengthy. I am guessing there must be something more elegant.

答:
This is a very lazy way to do it, but it meets the criteria for many similar situations:

```<code>try {
  console.log(entry.mediaGroup[0].contents[0].url);
} catch (e) {}
</code>```

This should not be done on long code blocks where other errors may potentially be ignored, but should be suitable for a simple situation like this.

Body:
In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a property may be undefined (so mediaGroup may not be set).

What is a simple way to say:

if( entry.mediaGroup[0].contents[0].url ){
   console.log( entry.mediaGroup[0].contents[0].url )
}

without generating an error? This way will generate an undefined error if any point along the way is undefined.

My solution

if(entry) && (entry.mediaGroup) && (entry.MediaGroup[0]) ...snip...){
   console.log(entry.mediaGroup[0].contents[0].url)
}

which is pretty lengthy. I am guessing there must be something more elegant.

Body:
This is a very lazy way to do it, but it meets the criteria for many similar situations:

try {
  console.log(entry.mediaGroup[0].contents[0].url);
} catch (e) {}

This should not be done on long code blocks where other errors may potentially be ignored, but should be suitable for a simple situation like this.


问:
How to repeat values in case of null values on left join
I have a table with a calendar, and a table with rates. In the table with the rates, there are no values existing for days in the weekend. I'm trying to join the two, in order to have a table where there is a rate for all days, and I need the rates in the weekend to be the latest available rate. Instad of it showing NULL values, as it would when you make a left join and the record doesn't exist, it should just take the latest available, repeating the previous value.

I have the below code, which works, but it takes 2 min to do on 7,397 rows, which is way too long.

Does anyone know a faster way to get the same results?

```<code>SELECT
c.CalendarID,
MAX(r.RateID)

FROM Dim_Calendar c

LEFT JOIN Dim_Rates r ON r.RateDate <= c.CalendarID
</code>```

What I get without <= and just an = is the following

```<code>CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | NULL
20131006   | NULL
20131007   | 6
</code>```

And this is the desired table:

```<code>CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | 5
20131006   | 5
20131007   | 6
</code>```

答:
You could use a correlated subquery to fill the gaps:

```<code>SELECT
    c.CalendarID,
    (SELECT TOP 1 r.RateID FROM Dim_Rates r
     WHERE r.RateDate <= c.CalendarID AND r.RateID IS NOT NULL
     ORDER BY r.RateDate DESC) AS RateID
FROM Dim_Calendar c
ORDER BY c.CalendarID;
</code>```

This query can be improved by using the following index:

```<code>CREATE INDEX idx ON Dim_Rates (RateDate, RateID);
</code>```

Body:
I have a table with a calendar, and a table with rates. In the table with the rates, there are no values existing for days in the weekend. I'm trying to join the two, in order to have a table where there is a rate for all days, and I need the rates in the weekend to be the latest available rate. Instad of it showing NULL values, as it would when you make a left join and the record doesn't exist, it should just take the latest available, repeating the previous value.

I have the below code, which works, but it takes 2 min to do on 7,397 rows, which is way too long.

Does anyone know a faster way to get the same results?

SELECT
c.CalendarID,
MAX(r.RateID)

FROM Dim_Calendar c

LEFT JOIN Dim_Rates r ON r.RateDate <= c.CalendarID

What I get without <= and just an = is the following

CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | NULL
20131006   | NULL
20131007   | 6

And this is the desired table:

CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | 5
20131006   | 5
20131007   | 6

Body:
You could use a correlated subquery to fill the gaps:

SELECT
    c.CalendarID,
    (SELECT TOP 1 r.RateID FROM Dim_Rates r
     WHERE r.RateDate <= c.CalendarID AND r.RateID IS NOT NULL
     ORDER BY r.RateDate DESC) AS RateID
FROM Dim_Calendar c
ORDER BY c.CalendarID;

This query can be improved by using the following index:

CREATE INDEX idx ON Dim_Rates (RateDate, RateID);