问:
Android SplashScreen API crashes on Android <=9
I'm in the process of migrating my splash screen to the new API. It works well on my device (S21 running Android 13).

I began testing it on an Android 9 emulator and it just keeps crashing without opening, I managed to get a log. It looks like this is the main cause. I've

Tried changing the image to something simpler like an icon and it works on the emulator

I won't be able to source the splash logo with shorter paths in the SVG. Is there anything that can be done about this for Android 9 and lower?

```<code>Caused by: java.lang.IllegalArgumentException: R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE
</code>```
```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iku.test/com.iku.intro.splash.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.iku.test:drawable/compat_splash_screen_no_icon_background with resource ID #0x7f0800a1
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.content.res.Resources$NotFoundException: Drawable com.iku.test:drawable/compat_splash_screen_no_icon_background with resource ID #0x7f0800a1
Caused by: android.content.res.Resources$NotFoundException: Drawable com.iku.test:drawable/iku_new_splash with resource ID #0x7f080215
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/iku_new_splash.xml from drawable resource ID #0x7f080215
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:847)
    at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:631)
    at android.content.res.Resources.loadDrawable(Resources.java:897)
    at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:955)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:930)
    at android.graphics.drawable.LayerDrawable.updateLayerFromTypedArray(LayerDrawable.java:382)
    at android.graphics.drawable.LayerDrawable.applyTheme(LayerDrawable.java:224)
    at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:646)
    at android.content.res.Resources.getDrawableForDensity(Resources.java:888)
    at android.content.res.Resources.getDrawable(Resources.java:827)
    at android.content.Context.getDrawable(Context.java:626)
    at androidx.core.content.ContextCompat$Api21Impl.getDrawable(ContextCompat.java:1012)
    at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:522)
    at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:149)
    at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:480)
    at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:94)
    at androidx.appcompat.app.AppCompatDelegateImpl.attachToWindow(AppCompatDelegateImpl.java:807)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureWindow(AppCompatDelegateImpl.java:783)
    at androidx.appcompat.app.AppCompatDelegateImpl.onCreate(AppCompatDelegateImpl.java:506)
    at androidx.appcompat.app.AppCompatActivity$2.onContextAvailable(AppCompatActivity.java:131)
    at androidx.activity.contextaware.ContextAwareHelper.dispatchOnContextAvailable(ContextAwareHelper.java:99)
    at androidx.activity.ComponentActivity.onCreate(ComponentActivity.java:352)
    at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:217)
    at com.iku.intro.splash.SplashActivity.onCreate(SplashActivity.kt:24)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IllegalArgumentException: R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE
    at android.util.PathParser.nCreatePathDataFromString(Native Method)
    at android.util.PathParser.access$200(PathParser.java:24)
    at android.util.PathParser$PathData.<init>(PathParser.java:76)
    at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:2016)
    at android.graphics.drawable.VectorDrawable$VFullPath.inflate(VectorDrawable.java:1967)
    at android.graphics.drawable.VectorDrawable.inflateChildElements(VectorDrawable.java:819)
    at android.graphics.drawable.VectorDrawable.inflate(VectorDrawable.java:717)
    at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
    at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
    at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1291)
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:833)
    ... 38 more
</code>```

Body:
I'm in the process of migrating my splash screen to the new API. It works well on my device (S21 running Android 13).

I began testing it on an Android 9 emulator and it just keeps crashing without opening, I managed to get a log. It looks like this is the main cause. I've

Tried changing the image to something simpler like an icon and it works on the emulator

I won't be able to source the splash logo with shorter paths in the SVG. Is there anything that can be done about this for Android 9 and lower?

Caused by: java.lang.IllegalArgumentException: R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iku.test/com.iku.intro.splash.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.iku.test:drawable/compat_splash_screen_no_icon_background with resource ID #0x7f0800a1
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.content.res.Resources$NotFoundException: Drawable com.iku.test:drawable/compat_splash_screen_no_icon_background with resource ID #0x7f0800a1
Caused by: android.content.res.Resources$NotFoundException: Drawable com.iku.test:drawable/iku_new_splash with resource ID #0x7f080215
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/iku_new_splash.xml from drawable resource ID #0x7f080215
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:847)
    at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:631)
    at android.content.res.Resources.loadDrawable(Resources.java:897)
    at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:955)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:930)
    at android.graphics.drawable.LayerDrawable.updateLayerFromTypedArray(LayerDrawable.java:382)
    at android.graphics.drawable.LayerDrawable.applyTheme(LayerDrawable.java:224)
    at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:646)
    at android.content.res.Resources.getDrawableForDensity(Resources.java:888)
    at android.content.res.Resources.getDrawable(Resources.java:827)
    at android.content.Context.getDrawable(Context.java:626)
    at androidx.core.content.ContextCompat$Api21Impl.getDrawable(ContextCompat.java:1012)
    at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:522)
    at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:149)
    at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:480)
    at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:94)
    at androidx.appcompat.app.AppCompatDelegateImpl.attachToWindow(AppCompatDelegateImpl.java:807)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureWindow(AppCompatDelegateImpl.java:783)
    at androidx.appcompat.app.AppCompatDelegateImpl.onCreate(AppCompatDelegateImpl.java:506)
    at androidx.appcompat.app.AppCompatActivity$2.onContextAvailable(AppCompatActivity.java:131)
    at androidx.activity.contextaware.ContextAwareHelper.dispatchOnContextAvailable(ContextAwareHelper.java:99)
    at androidx.activity.ComponentActivity.onCreate(ComponentActivity.java:352)
    at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:217)
    at com.iku.intro.splash.SplashActivity.onCreate(SplashActivity.kt:24)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IllegalArgumentException: R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE
    at android.util.PathParser.nCreatePathDataFromString(Native Method)
    at android.util.PathParser.access$200(PathParser.java:24)
    at android.util.PathParser$PathData.<init>(PathParser.java:76)
    at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:2016)
    at android.graphics.drawable.VectorDrawable$VFullPath.inflate(VectorDrawable.java:1967)
    at android.graphics.drawable.VectorDrawable.inflateChildElements(VectorDrawable.java:819)
    at android.graphics.drawable.VectorDrawable.inflate(VectorDrawable.java:717)
    at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
    at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
    at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1291)
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:833)
    ... 38 more


来源: stackexchange

问:
Check if user input number is float with MARS system-calls
I'm doing a program in MIPS Assembly (using MARS 4_5) that has to be able to only read positive integers for my computer architecture class. My program should display a error message if the user's input is negative or has decimal places but I don't know how to do it. I mean, I know how to display the error message, I have done it already to negative (and 0) numbers, just not how to tell the program "If the input is a float number, then...".

Could anyone help me? Thank you so much.

For negative numbers I did this (among the rest of the program, of course):

```<code>blez $t0, error
</code>```
```<code>error:
    li $v0, 4
    la $a0, str9 #error message
    syscall

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm doing a program in MIPS Assembly (using MARS 4_5) that has to be able to only read positive integers for my computer architecture class. My program should display a error message if the user's input is negative or has decimal places but I don't know how to do it. I mean, I know how to display the error message, I have done it already to negative (and 0) numbers, just not how to tell the program "If the input is a float number, then...".

Could anyone help me? Thank you so much.

For negative numbers I did this (among the rest of the program, of course):

blez $t0, error

error:
    li $v0, 4
    la $a0, str9 #error message
    syscall


问:
Sharing Websocket connection between multiple tabs?
I'm having difficulty figuring out the best method of sharing a WebSocket connection between multiple tabs. It seems like BroadcastEvent and SharedWorker are two modern APIs that can be used for this task. BroadcastEvent and SharedWorker seem like the solve the same problem, but I've seen solutions that use both together, something like this:

// worker.js

const socket = new WebSocket('url')
const broadcastChannel = new BroadcastChannel('example-broadcast')

socket.onmessage = ({ data }) => {
  broadcastChannel.postMessage(data)
}
```
<pre class="lang-js prettyprint-override"><code>// connection.js

const sharedWorker = new SharedWorker(new URL('worker.js', import.meta.url), {
  type: 'module',
  name: 'example-worker',
})
sharedWorker.port.start()
sharedWorker.port.onmessage = ({ data }) => {
  switch (data.type) {
    case 'message':
      console.log(data)
      break
  }
}

const broadcastChannel = new BroadcastChannel('example-broadcast')
broadcastChannel.addEventListener('message', ({ data }) => {
  switch (data.type) {
    case 'message':
      console.log(data)
      break
  }
})
</code>```

Is this a reasonable approach? Is it necessary to have both BroadcastChannel and SharedWorker here or can it be accomplished in a simpler manner? It's difficult to find answers about this situation that aren't from 2012 and use localhost and other outdated solutions.

Body:
I'm having difficulty figuring out the best method of sharing a WebSocket connection between multiple tabs. It seems like BroadcastEvent and SharedWorker are two modern APIs that can be used for this task. BroadcastEvent and SharedWorker seem like the solve the same problem, but I've seen solutions that use both together, something like this:

// worker.js

const socket = new WebSocket('url')
const broadcastChannel = new BroadcastChannel('example-broadcast')

socket.onmessage = ({ data }) => {
  broadcastChannel.postMessage(data)
}

// connection.js

const sharedWorker = new SharedWorker(new URL('worker.js', import.meta.url), {
  type: 'module',
  name: 'example-worker',
})
sharedWorker.port.start()
sharedWorker.port.onmessage = ({ data }) => {
  switch (data.type) {
    case 'message':
      console.log(data)
      break
  }
}

const broadcastChannel = new BroadcastChannel('example-broadcast')
broadcastChannel.addEventListener('message', ({ data }) => {
  switch (data.type) {
    case 'message':
      console.log(data)
      break
  }
})

Is this a reasonable approach? Is it necessary to have both BroadcastChannel and SharedWorker here or can it be accomplished in a simpler manner? It's difficult to find answers about this situation that aren't from 2012 and use localhost and other outdated solutions.


问:
Efficiently index into a Multi-index dataframe (with default handling)
I've been charged with optimizing an API and when I run my profiler I see that 70% of the cumulative run time is taken by the functionality described below. It would be great if you could point me toward resources that could help me make this faster.
It would be amazing if I could make this a vector operation but I'm drawing blanks

Due to product requirements, I have to query lm_df twice per API call. Optimizing this would be amazing.

I have a multi-index df as follows:

lm_df

value

X
Y
Z

x1
y1
z1
1.2

x1
not_available
z1
1.3

x1
not_available
not_available
1.36

not_available
y1
z2
1.31

not_available
y2
z2
1.32

not_available
not_available
z2
1.33

not_available
y1
not_available
1.34

not_available
y2
not_available
1.5

not_available
not_available
not_available
1.37

x3
y3
z1
1.9

x3
y3
not_available
3.4

x3
not_available
not_available
5.7

note: X, Y and Z are in a multi-index and are categorical values. In real word data, I have 6 features, and the last feature contains more than 200 unique values.
As you go deeper every level, it will contain a "not_available" feature. This feature is to be used if your category is not supported for the current index.
For example: X1 does not support y2, if the client request for (X1, Y2, Z1), we should use (X1, not_available, Z1) to index into lm_df and return 1.3

I need to index into lm_df based on the client's request:

This is the code I'm currently using that is slow:

```<code>def assign_prediction_feature(feat, model, row):
    current_feat = getattr(row, feat)
    return (
        current_feat
        if current_feat in model.index.get_level_values(feat)
        else "not_available"
    )

def problem_function(row, model):
    x_index = assign_prediction_feature("X", model, row)
    x_model =  model.loc[x_index]

    y_index = assign_prediction_feature("Y", x_model, row)
    y_model =  x_model.loc[y_index]

    z_index = assign_prediction_feature("Z", y_model, row)
    value =  y_model.loc[z_index].value
    return value

df["value"] = df.apply(
            problem_function,
            models=lm_df,
            axis=1,
        )
</code>```

According to the profiler, a large portion of the time is taken by indexing.
note: This is for two calls to problem_function

Body:
I've been charged with optimizing an API and when I run my profiler I see that 70% of the cumulative run time is taken by the functionality described below. It would be great if you could point me toward resources that could help me make this faster.
It would be amazing if I could make this a vector operation but I'm drawing blanks

Due to product requirements, I have to query lm_df twice per API call. Optimizing this would be amazing.

I have a multi-index df as follows:

lm_df

value

X
Y
Z

x1
y1
z1
1.2

x1
not_available
z1
1.3

x1
not_available
not_available
1.36

not_available
y1
z2
1.31

not_available
y2
z2
1.32

not_available
not_available
z2
1.33

not_available
y1
not_available
1.34

not_available
y2
not_available
1.5

not_available
not_available
not_available
1.37

x3
y3
z1
1.9

x3
y3
not_available
3.4

x3
not_available
not_available
5.7

note: X, Y and Z are in a multi-index and are categorical values. In real word data, I have 6 features, and the last feature contains more than 200 unique values.
As you go deeper every level, it will contain a "not_available" feature. This feature is to be used if your category is not supported for the current index.
For example: X1 does not support y2, if the client request for (X1, Y2, Z1), we should use (X1, not_available, Z1) to index into lm_df and return 1.3

I need to index into lm_df based on the client's request:

This is the code I'm currently using that is slow:

def assign_prediction_feature(feat, model, row):
    current_feat = getattr(row, feat)
    return (
        current_feat
        if current_feat in model.index.get_level_values(feat)
        else "not_available"
    )

def problem_function(row, model):
    x_index = assign_prediction_feature("X", model, row)
    x_model =  model.loc[x_index]

    y_index = assign_prediction_feature("Y", x_model, row)
    y_model =  x_model.loc[y_index]

    z_index = assign_prediction_feature("Z", y_model, row)
    value =  y_model.loc[z_index].value
    return value

df["value"] = df.apply(
            problem_function,
            models=lm_df,
            axis=1,
        )

According to the profiler, a large portion of the time is taken by indexing.
note: This is for two calls to problem_function


问:
Geckodriver 0.32 x64 stuck on "listening"
Here is my code that I'm trying to run. I'm not using driver = webdriver.Firefox(executable_path=... because of the DeprecationWarning. The .exe file and the .py file are in the same folder. I'm using selenium 4.5.0 and geckodriver 0.32.0 (64-bit)

```<code>from selenium import webdriver
from selenium.webdriver.firefox.service import Service

gecko  = "C:\\Users\\example\\example\\example\\geckodriver.exe"
print("1")
serv   = Service(gecko)
print("2")

driver = webdriver.Firefox(service = serv)
print("3")
driver.get("https://www.google.com")
print("4")
</code>```

Here is what I found in the geckodriver.log files :-

```<code>1672249526524   geckodriver INFO    Listening on 127.0.0.1:52433
</code>```

Upon running the script, only these happen :-

```<code>C:\example\example>C:\example\example\example\example\script.py
1
2
</code>```

No firefox window is opened. I'm using firefox version 108.0.1 (64 bit) and it also isn't set as my default browser. I'm also using python 3.9.6 (64 bit).

I tried going through the official documentations and guides but to no avail

Body:
Here is my code that I'm trying to run. I'm not using driver = webdriver.Firefox(executable_path=... because of the DeprecationWarning. The .exe file and the .py file are in the same folder. I'm using selenium 4.5.0 and geckodriver 0.32.0 (64-bit)

from selenium import webdriver
from selenium.webdriver.firefox.service import Service

gecko  = "C:\\Users\\example\\example\\example\\geckodriver.exe"
print("1")
serv   = Service(gecko)
print("2")

driver = webdriver.Firefox(service = serv)
print("3")
driver.get("https://www.google.com")
print("4")

Here is what I found in the geckodriver.log files :-

1672249526524   geckodriver INFO    Listening on 127.0.0.1:52433

Upon running the script, only these happen :-

C:\example\example>C:\example\example\example\example\script.py
1
2

No firefox window is opened. I'm using firefox version 108.0.1 (64 bit) and it also isn't set as my default browser. I'm also using python 3.9.6 (64 bit).

I tried going through the official documentations and guides but to no avail


问:
Problem with conda environment 'r-reticulate' when using keras
I have installed tensorflow and keras for my R environment but I always get an error when using keras functions.

Always get this error

Error: Error creating conda environment 'r-reticulate' [exit code 1]

I successfully loaded the libraries

```<code>library(tensorflow)
library(keras)
</code>```

and when I run

k_clear_session() or model <- keras_model_sequential()

I get the error mentioned above.
I have no idea what is causing this issue.
I also tried loading the library reticulate, but it didn't fix the problem.

And then I tried to create that environment with conda_create("r-reticulate") but the error popped up again.

Of course I get an error when I use use_condaenv("r-reticulate")

Error in use_condaenv("r-reticulate"): Unable to locate conda environment 'r-reticulate'.

Body:
I have installed tensorflow and keras for my R environment but I always get an error when using keras functions.

Always get this error

Error: Error creating conda environment 'r-reticulate' [exit code 1]

I successfully loaded the libraries

library(tensorflow)
library(keras)

and when I run

k_clear_session() or model <- keras_model_sequential()

I get the error mentioned above.
I have no idea what is causing this issue.
I also tried loading the library reticulate, but it didn't fix the problem.

And then I tried to create that environment with conda_create("r-reticulate") but the error popped up again.

Of course I get an error when I use use_condaenv("r-reticulate")

Error in use_condaenv("r-reticulate"): Unable to locate conda environment 'r-reticulate'.


问:
Does RISE accept greyscale images?
I am trying to implement RISE (https://github.com/eclique/RISE) for greyscale images. The base achtitecture is trained with 1 channel. However, in easystart.ipynb with def load_img (see below), the input size is automatically converted from greyscale into RGB images.

```<code> def load_img(path):
  img = image.load_img(path, target_size=model.input_size)
</code>```

I tried setting

```<code>   img = image.load_img(path, target_size=model.input_size, color_mode="grayscale")

</code>```
```<code>img, x = load_img('greyscale_image')
</code>```

provides this error

error_code 1/2
error_code 2/2

So, do you know if RISE is only usable with RGB images? Or how to solve this?

Best regards,
Daan

Title: Does RISE accept greyscale images?

Body:
I am trying to implement RISE (https://github.com/eclique/RISE) for greyscale images. The base achtitecture is trained with 1 channel. However, in easystart.ipynb with def load_img (see below), the input size is automatically converted from greyscale into RGB images.

 def load_img(path):
  img = image.load_img(path, target_size=model.input_size)

I tried setting

   img = image.load_img(path, target_size=model.input_size, color_mode="grayscale")

img, x = load_img('greyscale_image')

provides this error

error_code 1/2
error_code 2/2

So, do you know if RISE is only usable with RGB images? Or how to solve this?

Best regards,
Daan


问:
Flutter : BottomNavigationbar get passed along with other variables while doing Navigation.push
I am trying to include Bottomnavigationbar to my app .This the list of pages that I navigate through :

```<code>List<Widget> pageList = [home(), draft(), Profile()];

</code>```

I only want to show the bottomnavigationbar in these 3 pages .Inside the home screen I navigate to a comment screen through Navigation.push and I pass certain values into it like this:

```<code> Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => comment(
                                          body: document['body'],
                                          title: document['title'],
                                          date: document['date'],
                                        )),
                              );
</code>```

However my bottomnavigationbar is shown in comment screen also .I think it is because I am passing values inside push() method from home() to comment().How can I hide the navigationbar in comment screen ?

The comment box already have a navigationbar.

This is my bottomnavigationbar code

```<code>
class _mainscreenState extends State<mainscreen> {
  int _selectedIndex = 0;
  List<Widget> pageList = [home(), draft(), Profile()];
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageList.elementAt(_selectedIndex),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.add_circle_outline_sharp),
            label: 'Create',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

</code>```

Body:
I am trying to include Bottomnavigationbar to my app .This the list of pages that I navigate through :

List<Widget> pageList = [home(), draft(), Profile()];

I only want to show the bottomnavigationbar in these 3 pages .Inside the home screen I navigate to a comment screen through Navigation.push and I pass certain values into it like this:

 Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => comment(
                                          body: document['body'],
                                          title: document['title'],
                                          date: document['date'],
                                        )),
                              );

However my bottomnavigationbar is shown in comment screen also .I think it is because I am passing values inside push() method from home() to comment().How can I hide the navigationbar in comment screen ?

The comment box already have a navigationbar.

This is my bottomnavigationbar code

class _mainscreenState extends State<mainscreen> {
  int _selectedIndex = 0;
  List<Widget> pageList = [home(), draft(), Profile()];
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageList.elementAt(_selectedIndex),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.add_circle_outline_sharp),
            label: 'Create',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}


问:
GLFW window not showing anything
My code is as follows, mostly following http://www.opengl-tutorial.org/beginners-tutorials.

#define GL_SILENCE_DEPRECATION

#include <GL/glew.h>
#include <GLFW/glfw3.h>

GLFWwindow* window;

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;

#include <cstdio>

int main(int argc, char *argv[]) {
    if (!glfwInit()) {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(1024, 768, "Test", NULL, NULL);
    if (window == NULL) {
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible.\n" );
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        glfwTerminate();
        return -1;
    }

    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glClearColor(255.0f, 255.0f, 255.0f, 0.0f);

    glViewport(0, 0, 1024, 768);
    glMatrixMode(GL_PROJECTION);
    glOrtho(0, 1024, 0, 768, -1, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glEnable(GL_DEPTH_TEST);

    do {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glPointSize(20);
        glBegin(GL_POINTS);
        for (int i = 0; i < 1; i++) {
            glColor4f(0.0f, 0.0f, 0.4f, 0.0f);
            glVertex3f(0,0,0);
            glVertex3f(1,1,1);
        }
        glEnd();

        glLineWidth(5);
        glBegin(GL_LINES);
        for (int i = 0; i < 1; i++) {
            glColor4f(0.0f, 0.0f, 0.4f, 0.0f);
            glVertex3f(0,0,0);
            glVertex3f(1,1,1);
        }
        glEnd();

        glfwSwapBuffers(window);
        glfwPollEvents();
    } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);

    glfwTerminate();

    return 0;
}

```

Only a white window shows and no lines or points are drawn. What's more, when I follow the tutorial on http://www.opengl-tutorial.org/beginners-tutorials and try to set the line width of the triangles I also failed. Thanks.

Title: GLFW window not showing anything

Body:
My code is as follows, mostly following http://www.opengl-tutorial.org/beginners-tutorials.

#define GL_SILENCE_DEPRECATION

#include <GL/glew.h>
#include <GLFW/glfw3.h>

GLFWwindow* window;

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;

#include <cstdio>

int main(int argc, char *argv[]) {
    if (!glfwInit()) {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(1024, 768, "Test", NULL, NULL);
    if (window == NULL) {
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible.\n" );
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        glfwTerminate();
        return -1;
    }

    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glClearColor(255.0f, 255.0f, 255.0f, 0.0f);

    glViewport(0, 0, 1024, 768);
    glMatrixMode(GL_PROJECTION);
    glOrtho(0, 1024, 0, 768, -1, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glEnable(GL_DEPTH_TEST);

    do {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glPointSize(20);
        glBegin(GL_POINTS);
        for (int i = 0; i < 1; i++) {
            glColor4f(0.0f, 0.0f, 0.4f, 0.0f);
            glVertex3f(0,0,0);
            glVertex3f(1,1,1);
        }
        glEnd();

        glLineWidth(5);
        glBegin(GL_LINES);
        for (int i = 0; i < 1; i++) {
            glColor4f(0.0f, 0.0f, 0.4f, 0.0f);
            glVertex3f(0,0,0);
            glVertex3f(1,1,1);
        }
        glEnd();

        glfwSwapBuffers(window);
        glfwPollEvents();
    } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);

    glfwTerminate();

    return 0;
}

Only a white window shows and no lines or points are drawn. What's more, when I follow the tutorial on http://www.opengl-tutorial.org/beginners-tutorials and try to set the line width of the triangles I also failed. Thanks.


问:
Equivalent for predict_proba in statsmodels Logistic Regression in Python?
I created Logisitc Regression Model in statsmodels in Python like below:

```<code>model = sm.Logit(y_train, X_train[selected_features]).fit(disp = 0)
</code>```

and then I need to calculate probabilities, (NOT prediction model.predict) but probabilities, same like predict_proba in sklearn. But whne I try to use predict_proba in statsmodels like below:

```<code>y_proba_1 = model.predict_proba(X_test)[:,1]
</code>```

I have error: AttributeError: 'LogitResults' object has no attribute 'predict_proba'

Is there some equivalent for predict_proba from sklearn in statsmodels in Python ?

I need to hae equivalent for below lines which works in sklearn but does not wokrs in statsmodels:

```<code>y_proba_0 = model.predict_proba(X_test)[:,0]
y_proba_1 = model.predict_proba(X_test)[:,1]
</code>```

Body:
I created Logisitc Regression Model in statsmodels in Python like below:

model = sm.Logit(y_train, X_train[selected_features]).fit(disp = 0)

and then I need to calculate probabilities, (NOT prediction model.predict) but probabilities, same like predict_proba in sklearn. But whne I try to use predict_proba in statsmodels like below:

y_proba_1 = model.predict_proba(X_test)[:,1]

I have error: AttributeError: 'LogitResults' object has no attribute 'predict_proba'

Is there some equivalent for predict_proba from sklearn in statsmodels in Python ?

I need to hae equivalent for below lines which works in sklearn but does not wokrs in statsmodels:

y_proba_0 = model.predict_proba(X_test)[:,0]
y_proba_1 = model.predict_proba(X_test)[:,1]


问:
Push TabBarView upward when keyboard appears on the screen
Hi Developers, I am new to Flutter and developing an app that contains Authentication. I have added tabs for Login as shown below

Login Screen with Tabs.

Now the issue I'm facing is that When the keyboard opens up for entering username or password, texFields hides behind the keyboard like this (Sorry for the image: iPhone does not show the keyboard when taking screenshots).

Textfields hides behind the keyboard.

I have tried the suggested solutions by adding

resizeToAvoidBottomInset: true,

padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom)

but nothing works out. When I tried this on individual screens without tabs, it worked. So, is there any Option to move tabBarView upwards when the keyboard appears.

Here is the source code:

Login

```<code>import 'dart:async';
import 'package:first_app/mvvm/repo/dataholder.dart';
import 'package:first_app/mvvm/viewmodels/app_viewmodel.dart';
import 'package:first_app/screens/login_tabs_screen.dart';
import 'package:first_app/utils/colors.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../mvvm/models/exchange_stats_feed_model.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  static const routeName = 'login';

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  late List<IndiceObj> _exchangeStatsList = [];
  late List<IndiceObj> _dropDownList = [];
  late int _selected;
  Timer? _timer;

  @override
  void initState() {
    _exchangeStatsList = DataHolder.indicesList;
    _dropDownList = DataHolder.indicesList;
    _selected = 0;
    keepUpdating();

    super.initState();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                buildIconButtons(Icons.whatsapp, _launchWhatsapp),
                buildIconButtons(Icons.call, () {})
              ],
            ),
            Image.asset(
              'assets/icons/js-logo.png',
              width: 100,
              height: 100,
              alignment: Alignment.center,
            ),

            _buildRateExchangeWidget(),
            const LoginTabsScreen(),
            // Padding(
            //   padding: EdgeInsets.only(
            //       bottom: MediaQuery.of(context).viewInsets.bottom),
            // )
          ],
        ),
      ),
    );
  }

  Widget _buildRateExchangeWidget() {
    IndiceObj indiceObj = _exchangeStatsList[_selected];
    double mainIndexChangePercentage = indiceObj.indexChange /
        double.parse(indiceObj.index.replaceAll(',', ''));
    mainIndexChangePercentage *= 100;
    return  Padding(
      padding: const EdgeInsets.only(left: 5, right: 5),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.5,
                child: DropdownButton<IndiceObj>(
                  underline: const SizedBox(),
                  value: indiceObj,
                  iconSize: 24,
                  elevation: 16,
                  isExpanded: true,
                  onChanged: (val) {
                    setState(() {
                      _selected = _dropDownList.indexWhere(
                          (element) => element.indexName == val!.indexName);
                    });
                  },
                  alignment: Alignment.center,
                  items: _dropDownList.map((IndiceObj exchangeStats) {
                    return DropdownMenuItem<IndiceObj>(
                        value: exchangeStats,
                        child: Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Text(
                            exchangeStats.indexName,
                            style: Theme.of(context).textTheme.titleMedium,
                            textAlign: TextAlign.start,
                          ),
                        ));
                  }).toList(),
                ),
              ),
              Text(
                indiceObj.index,
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              RichText(
                text: TextSpan(children: [
                  TextSpan(
                      text: 'M.Vol: ${indiceObj.marketVolume}| ',
                      style: Theme.of(context).textTheme.titleMedium),
                  indiceObj.marketStatus == 'Close'
                      ? const TextSpan(
                          text: 'Close',
                          style: TextStyle(
                              fontSize: 16,
                              fontFamily: 'assets/icons/Bahnscript',
                              color: maroon,
                              fontWeight: FontWeight.bold))
                      : TextSpan(
                          text: indiceObj.marketStatus,
                          style: TextStyle(
                              fontSize: 18,
                              color: Theme.of(context).primaryColor))
                ]),
              ),
              indiceObj.indexChange >= 0
                  ? indiceObj.indexChange == 0
                      ? Text(
                          '${indiceObj.indexChange} (0.0%)',
                          style:
                              TextStyle(color: Colors.blue[900], fontSize: 18),
                        )
                      : Text(
                          '+ ${indiceObj.indexChange} (${mainIndexChangePercentage.toStringAsFixed(2)}%)',
                          textAlign: TextAlign.end,
                          style: TextStyle(
                              fontSize: 18,
                              color: Theme.of(context).primaryColor),
                        )
                  : Expanded(
                      child: Text(
                        '${indiceObj.indexChange} (${mainIndexChangePercentage.toStringAsFixed(2)}%)',
                        textAlign: TextAlign.end,
                        style: TextStyle(
                          fontSize: 18,
                          color: Colors.red[700],
                        ),
                      ),
                    ),
            ],
          ),

        ],
      ),
    );
  }

  void _launchWhatsapp() async {
    var whatsapp = "+923443028878";
    var message = 'Hi, there';
    var whatsappSendMsg =
        Uri.parse("whatsapp://send?phone=$whatsapp&text=$message");
    if (await canLaunchUrl(whatsappSendMsg)) {
      await launchUrl(whatsappSendMsg);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("WhatsApp is not installed on the device"),
        ),
      );
    }
  }

  updateStatsExchangeList() async {
    String date = DateFormat("MMddyyyy").format(DateTime.now());
    await Provider.of<AppViewModel>(context, listen: false)
        .getExchangeStatsFeed(date);

    _exchangeStatsList = DataHolder.indicesList;
    setState(() {});
  }

  void keepUpdating() {
    int counter = 1;
    _timer = Timer.periodic(
        const Duration(seconds: 5), (Timer t) => updateStatsExchangeList());
    debugPrint("Invoked: $counter");
    counter++;
    // setState(() {});
  }

  buildIconButtons(IconData icon, VoidCallback callback) {
    return IconButton(
        onPressed: callback,
        icon: Icon(
          icon,
          color: Theme.of(context).primaryColor,
        ));
  }
}
</code>```

Tabs Screen

```<code>import 'package:first_app/screens/global_lite.dart';
import 'package:first_app/screens/global_pro_login.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class LoginTabsScreen extends StatelessWidget {
  const LoginTabsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.only(top: 20),
        padding: const EdgeInsets.all(5),
        child: DefaultTabController(
          length: 2,
          child: SizedBox(
            height: 100.0,
            child: Column(
              children: <Widget>[
                 TabBar(
                   labelStyle: Theme.of(context).textTheme.titleMedium,
                   unselectedLabelColor: Colors.grey,
                  labelColor: Theme.of(context).primaryColor,
                  tabs: const <Widget>[
                     Tab(
                      text: "JS Global Pro",
                    ),
                    Tab(
                      text: "JS Global Lite",
                    )
                  ],
                ),
                const SizedBox(height: 10,),
                const Expanded(
                  child: TabBarView(
                    children: <Widget>[
                      GlobalProLogin(),
                      GlobalLightLogin()
                    ],
                  ),
                ),
              ],

            ),
          ),
        ),
      ),
    );
  }
}
</code>```

I have tried to move upward the tabBarView and I am expecting this result.

Body:
Hi Developers, I am new to Flutter and developing an app that contains Authentication. I have added tabs for Login as shown below

Login Screen with Tabs.

Now the issue I'm facing is that When the keyboard opens up for entering username or password, texFields hides behind the keyboard like this (Sorry for the image: iPhone does not show the keyboard when taking screenshots).

Textfields hides behind the keyboard.

I have tried the suggested solutions by adding

resizeToAvoidBottomInset: true,

padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom)

but nothing works out. When I tried this on individual screens without tabs, it worked. So, is there any Option to move tabBarView upwards when the keyboard appears.

Here is the source code:

Login

import 'dart:async';
import 'package:first_app/mvvm/repo/dataholder.dart';
import 'package:first_app/mvvm/viewmodels/app_viewmodel.dart';
import 'package:first_app/screens/login_tabs_screen.dart';
import 'package:first_app/utils/colors.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../mvvm/models/exchange_stats_feed_model.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  static const routeName = 'login';

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  late List<IndiceObj> _exchangeStatsList = [];
  late List<IndiceObj> _dropDownList = [];
  late int _selected;
  Timer? _timer;

  @override
  void initState() {
    _exchangeStatsList = DataHolder.indicesList;
    _dropDownList = DataHolder.indicesList;
    _selected = 0;
    keepUpdating();

    super.initState();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                buildIconButtons(Icons.whatsapp, _launchWhatsapp),
                buildIconButtons(Icons.call, () {})
              ],
            ),
            Image.asset(
              'assets/icons/js-logo.png',
              width: 100,
              height: 100,
              alignment: Alignment.center,
            ),

            _buildRateExchangeWidget(),
            const LoginTabsScreen(),
            // Padding(
            //   padding: EdgeInsets.only(
            //       bottom: MediaQuery.of(context).viewInsets.bottom),
            // )
          ],
        ),
      ),
    );
  }

  Widget _buildRateExchangeWidget() {
    IndiceObj indiceObj = _exchangeStatsList[_selected];
    double mainIndexChangePercentage = indiceObj.indexChange /
        double.parse(indiceObj.index.replaceAll(',', ''));
    mainIndexChangePercentage *= 100;
    return  Padding(
      padding: const EdgeInsets.only(left: 5, right: 5),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.5,
                child: DropdownButton<IndiceObj>(
                  underline: const SizedBox(),
                  value: indiceObj,
                  iconSize: 24,
                  elevation: 16,
                  isExpanded: true,
                  onChanged: (val) {
                    setState(() {
                      _selected = _dropDownList.indexWhere(
                          (element) => element.indexName == val!.indexName);
                    });
                  },
                  alignment: Alignment.center,
                  items: _dropDownList.map((IndiceObj exchangeStats) {
                    return DropdownMenuItem<IndiceObj>(
                        value: exchangeStats,
                        child: Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Text(
                            exchangeStats.indexName,
                            style: Theme.of(context).textTheme.titleMedium,
                            textAlign: TextAlign.start,
                          ),
                        ));
                  }).toList(),
                ),
              ),
              Text(
                indiceObj.index,
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              RichText(
                text: TextSpan(children: [
                  TextSpan(
                      text: 'M.Vol: ${indiceObj.marketVolume}| ',
                      style: Theme.of(context).textTheme.titleMedium),
                  indiceObj.marketStatus == 'Close'
                      ? const TextSpan(
                          text: 'Close',
                          style: TextStyle(
                              fontSize: 16,
                              fontFamily: 'assets/icons/Bahnscript',
                              color: maroon,
                              fontWeight: FontWeight.bold))
                      : TextSpan(
                          text: indiceObj.marketStatus,
                          style: TextStyle(
                              fontSize: 18,
                              color: Theme.of(context).primaryColor))
                ]),
              ),
              indiceObj.indexChange >= 0
                  ? indiceObj.indexChange == 0
                      ? Text(
                          '${indiceObj.indexChange} (0.0%)',
                          style:
                              TextStyle(color: Colors.blue[900], fontSize: 18),
                        )
                      : Text(
                          '+ ${indiceObj.indexChange} (${mainIndexChangePercentage.toStringAsFixed(2)}%)',
                          textAlign: TextAlign.end,
                          style: TextStyle(
                              fontSize: 18,
                              color: Theme.of(context).primaryColor),
                        )
                  : Expanded(
                      child: Text(
                        '${indiceObj.indexChange} (${mainIndexChangePercentage.toStringAsFixed(2)}%)',
                        textAlign: TextAlign.end,
                        style: TextStyle(
                          fontSize: 18,
                          color: Colors.red[700],
                        ),
                      ),
                    ),
            ],
          ),

        ],
      ),
    );
  }

  void _launchWhatsapp() async {
    var whatsapp = "+923443028878";
    var message = 'Hi, there';
    var whatsappSendMsg =
        Uri.parse("whatsapp://send?phone=$whatsapp&text=$message");
    if (await canLaunchUrl(whatsappSendMsg)) {
      await launchUrl(whatsappSendMsg);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("WhatsApp is not installed on the device"),
        ),
      );
    }
  }

  updateStatsExchangeList() async {
    String date = DateFormat("MMddyyyy").format(DateTime.now());
    await Provider.of<AppViewModel>(context, listen: false)
        .getExchangeStatsFeed(date);

    _exchangeStatsList = DataHolder.indicesList;
    setState(() {});
  }

  void keepUpdating() {
    int counter = 1;
    _timer = Timer.periodic(
        const Duration(seconds: 5), (Timer t) => updateStatsExchangeList());
    debugPrint("Invoked: $counter");
    counter++;
    // setState(() {});
  }

  buildIconButtons(IconData icon, VoidCallback callback) {
    return IconButton(
        onPressed: callback,
        icon: Icon(
          icon,
          color: Theme.of(context).primaryColor,
        ));
  }
}

Tabs Screen

import 'package:first_app/screens/global_lite.dart';
import 'package:first_app/screens/global_pro_login.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class LoginTabsScreen extends StatelessWidget {
  const LoginTabsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.only(top: 20),
        padding: const EdgeInsets.all(5),
        child: DefaultTabController(
          length: 2,
          child: SizedBox(
            height: 100.0,
            child: Column(
              children: <Widget>[
                 TabBar(
                   labelStyle: Theme.of(context).textTheme.titleMedium,
                   unselectedLabelColor: Colors.grey,
                  labelColor: Theme.of(context).primaryColor,
                  tabs: const <Widget>[
                     Tab(
                      text: "JS Global Pro",
                    ),
                    Tab(
                      text: "JS Global Lite",
                    )
                  ],
                ),
                const SizedBox(height: 10,),
                const Expanded(
                  child: TabBarView(
                    children: <Widget>[
                      GlobalProLogin(),
                      GlobalLightLogin()
                    ],
                  ),
                ),
              ],

            ),
          ),
        ),
      ),
    );
  }
}

I have tried to move upward the tabBarView and I am expecting this result.


问:
Is there a way to annotate PDF files in react.js
I am using the NPM library react-pdf to render user uploaded PDF file in a HTML<canvas> tag.
I am curious how can I add some labels on the content in that pdf by editing the canvas or is there any way of editing the canvas.


问:
How to save the dates that are active in local storage and display them on the calendar
I'm using the jQuery UI calendar. So right now i can select, save, display and remove the dates but i want to show the saved dates on the calendar (saved dates should always be active on the calendar with a different color), and save them automatically when i click on the number of the days.

HTML:

```<code><div id="datepicker"></div>
<div id="showdates"></div>
<button id="save">save</button>
<button id="restore">restore</button>
<button id="clear">clear</button>

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

</code>```

JavaScript:

```<code>const save = document.getElementById("save");
const restore = document.getElementById("restore");
const clear = document.getElementById("clear");
const showdates = document.getElementById("showdates");
const select = document.getElementsByClassName(".ui-datepicker-calendar tbody td a.ui-state-active");

$("#showdates").datepicker({
  dateFormat: "dd-mm-yy",
  duration: "fast",
});

save.addEventListener("click", function () {
  $("#showdates").datepicker({
    dateFormat: "yy-mm-dd",
  });

  //get date in a variable
  var date = $("#showdates").datepicker("getDate");
  var formatDate = $.datepicker.formatDate("yy-mm-dd", date);

  if (formatDate !== null) {
    localStorage.setItem(formatDate, formatDate);
  }
  const value = localStorage.getItem(formatDate);

  showdates.innerHTML += `Date: ${value}<br />`;
});

restore.addEventListener("click", function () {
  for (let i = 0; i < localStorage.length; i++) {
    const formatDate = localStorage.key(i);
    const value = localStorage.getItem(formatDate);

    showdates.innerHTML += `Date: ${value}<br />`;
  }
});

clear.addEventListener("click", function () {
  for (let i = 0; i < localStorage.length; i++) {
    const formatDate = localStorage.key(i);
    localStorage.clear(formatDate);
    const value = localStorage.getItem(formatDate);
    showdates.innerHTML += `Date: ${value}<br />`;

    if (value == null) {
      showdates.innerHTML = "Cleared";
    }
  }
});

</code>```

I searched a lot and tried some things, but they didn't work.

Body:
I'm using the jQuery UI calendar. So right now i can select, save, display and remove the dates but i want to show the saved dates on the calendar (saved dates should always be active on the calendar with a different color), and save them automatically when i click on the number of the days.

HTML:

<button id="save">save</button>
<button id="restore">restore</button>
<button id="clear">clear</button>

JavaScript:

const save = document.getElementById("save");
const restore = document.getElementById("restore");
const clear = document.getElementById("clear");
const showdates = document.getElementById("showdates");
const select = document.getElementsByClassName(".ui-datepicker-calendar tbody td a.ui-state-active");

$("#showdates").datepicker({
  dateFormat: "dd-mm-yy",
  duration: "fast",
});

save.addEventListener("click", function () {
  $("#showdates").datepicker({
    dateFormat: "yy-mm-dd",
  });

  //get date in a variable
  var date = $("#showdates").datepicker("getDate");
  var formatDate = $.datepicker.formatDate("yy-mm-dd", date);

  if (formatDate !== null) {
    localStorage.setItem(formatDate, formatDate);
  }
  const value = localStorage.getItem(formatDate);

  showdates.innerHTML += `Date: ${value}<br />`;
});

restore.addEventListener("click", function () {
  for (let i = 0; i < localStorage.length; i++) {
    const formatDate = localStorage.key(i);
    const value = localStorage.getItem(formatDate);

    showdates.innerHTML += `Date: ${value}<br />`;
  }
});

clear.addEventListener("click", function () {
  for (let i = 0; i < localStorage.length; i++) {
    const formatDate = localStorage.key(i);
    localStorage.clear(formatDate);
    const value = localStorage.getItem(formatDate);
    showdates.innerHTML += `Date: ${value}<br />`;

    if (value == null) {
      showdates.innerHTML = "Cleared";
    }
  }
});

I searched a lot and tried some things, but they didn't work.


问:
how to run a pygame projects on a github codespace
When i try to do any graphics projects on a codespace, the window does not popup, how to tackle this problem

I tried looking through the codespace guide but couldnt find anything


问:
Type Error store.dispatch is not a function + Redux Persist + Nextjs
I'm trying to use redux-persist in my next.js application. But I'm getting the store.dispatch is not a function error.

Here is the store.ts file:

```<code>import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit";
import { combineReducers } from "redux";
import { createWrapper } from "next-redux-wrapper";
import cReducer from "@features/cSlice";
import sSlice from "@features/sSlice";
import lSlice from "@features/lSlice";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

// #. Combine the reducers
const reducers = combineReducers({
  c: cReducer,
  i: iSlice,
  l: lSlice,
});
const persistConfig = {
  key: "root",
  storage: storage
};
const persistedReducer = persistReducer(persistConfig, reducers);

// #. Make the store
const makeStore:any = () =>
  configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== "production"
  });

makeStore.__persisitor = persistStore(makeStore);

export const wrapper = createWrapper(makeStore, { debug: false });
</code>```

And here is my _app.tsx file ;

```<code>function MyApp({ Component, pageProps }: AppProps) {
    const isLoading = useAppSelector(selectIsLoading);
    // rest of the code dropped off for clarity on the issue
  return (
    <>

               <Component {...pageProps} />

    </>
  );
}

export default appWithTranslation(wrapper.withRedux(MyApp));
</code>```

While running the application I'm getting the following error:

Type Error store.dispatch is not a function

Body:
I'm trying to use redux-persist in my next.js application. But I'm getting the store.dispatch is not a function error.

Here is the store.ts file:

import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit";
import { combineReducers } from "redux";
import { createWrapper } from "next-redux-wrapper";
import cReducer from "@features/cSlice";
import sSlice from "@features/sSlice";
import lSlice from "@features/lSlice";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

// #. Combine the reducers
const reducers = combineReducers({
  c: cReducer,
  i: iSlice,
  l: lSlice,
});
const persistConfig = {
  key: "root",
  storage: storage
};
const persistedReducer = persistReducer(persistConfig, reducers);

// #. Make the store
const makeStore:any = () =>
  configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== "production"
  });

makeStore.__persisitor = persistStore(makeStore);

export const wrapper = createWrapper(makeStore, { debug: false });

And here is my _app.tsx file ;

function MyApp({ Component, pageProps }: AppProps) {
    const isLoading = useAppSelector(selectIsLoading);
    // rest of the code dropped off for clarity on the issue
  return (
    <>

               <Component {...pageProps} />

    </>
  );
}

export default appWithTranslation(wrapper.withRedux(MyApp));

While running the application I'm getting the following error:

Type Error store.dispatch is not a function


问:
When I build an element and insert it into the DOM, I have no margin
I want to build a list. Each newly built row should have input field and a button next to it. When I build and insert this line with javascript there is no margin between the input field and the button. If I insert the built HTML static into the list there is a margin between input field and button. Why is that? And what do I have to do to make it behave the same as when I copy it statically into the dom?

const addBtn = document.querySelector('.addNewChoice');
const fieldsContainer = document.querySelector('#fields');
let count = 1;

function addNewChoice() {
  count++;
  const newFieldWrapper = document.createElement('div');

  newFieldWrapper.classList.add('mt-10');
  const newFieldInput = document.createElement('input');
  const removeBtn = document.createElement('button');
  newFieldInput.setAttribute('name', 'poll-choice-' + count);
  newFieldInput.setAttribute('placeholder', 'Choice ' + count)
  removeBtn.textContent = 'X';
  removeBtn.setAttribute('onclick', 'removeItem(this)');
  newFieldWrapper.appendChild(newFieldInput);
  newFieldWrapper.appendChild(removeBtn);
  fieldsContainer.appendChild(newFieldWrapper);
}

function removeItem(ev) {
  console.log('remove');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mt-10 {
  margin-top: 10px;
}</code>```

    <input name="poll-name" placeholder="title">

      <input name="poll-choice-1" value="" placeholder="Choice 1">
      <button class="addNewChoice" onclick="addNewChoice()">+</button>

```
</div>
</div>
</p>
<p>And here the generated HTML with Javascript:</p>
<pre class="lang-html prettyprint-override"><code><div class="mt-10"><input name="poll-choice-2" placeholder="Choice 2"><button onclick="removeItem(this)">X</button></div>
</code>```

Body:
I want to build a list. Each newly built row should have input field and a button next to it. When I build and insert this line with javascript there is no margin between the input field and the button. If I insert the built HTML static into the list there is a margin between input field and button. Why is that? And what do I have to do to make it behave the same as when I copy it statically into the dom?

const addBtn = document.querySelector('.addNewChoice');
const fieldsContainer = document.querySelector('#fields');
let count = 1;

function addNewChoice() {
  count++;
  const newFieldWrapper = document.createElement('div');

  newFieldWrapper.classList.add('mt-10');
  const newFieldInput = document.createElement('input');
  const removeBtn = document.createElement('button');
  newFieldInput.setAttribute('name', 'poll-choice-' + count);
  newFieldInput.setAttribute('placeholder', 'Choice ' + count)
  removeBtn.textContent = 'X';
  removeBtn.setAttribute('onclick', 'removeItem(this)');
  newFieldWrapper.appendChild(newFieldInput);
  newFieldWrapper.appendChild(removeBtn);
  fieldsContainer.appendChild(newFieldWrapper);
}

function removeItem(ev) {
  console.log('remove');
}

.mt-10 {
  margin-top: 10px;
}

    <input name="poll-name" placeholder="title">

      <input name="poll-choice-1" value="" placeholder="Choice 1">
      <button class="addNewChoice" onclick="addNewChoice()">+</button>

And here the generated HTML with Javascript:

<input name="poll-choice-2" placeholder="Choice 2"><button onclick="removeItem(this)">X</button>


问:
IMDB Dataset using Pandas and MongoDB
I'm using pandas with read_csv because the dataset that is available in TSV.

https://datasets.imdbws.com/ - dataset link

(I'm using name.basics.tsv in the example below.
https://www.imdb.com/interfaces/ - link to details of each file

What's my problem? By chance, at the time I started work, I thought it would be better to use MongoDB to store all the processing I've been doing.

Coming now to the end of the work, I come across a problem that is preventing me from continuing to create some Dashboards with Metabase.

I need to make sure that when reading the TSV, or when processing the data when creating the DataFrame before going to MongoDB, a field is created as an array, because it contains more than one piece of information, separated by a comma.

I know that within MongoDB you can do this (change the field type manually to array). But how to do this through Python? I made some attempts at treatment and alteration but without success. I'll show you how I'm currently reading the file.

Some dataset fields have more than one piece of information, and for the solution I'm using now to plot it, it would help me a lot if some fields were a string array type (below an example)

```<code>import pandas as pd
from pymongo import MongoClient
import numpy as np
from ast import literal_eval

mc = MongoClient("mongodb://localhost:27017/")
db = mc._database_default_options(name='imdbdash')

file = "../IMDBDATASET/name.basics.tsv"
dfname = pd.read_csv(filepath_or_buffer=file,
                      sep = '\t',
                      #dtype={'primaryProfession': np.array , 'knownForTitles':'np.array'},
                      #converters={'primaryProfession': literal_eval,'knownForTitles': literal_eval,},
                      low_memory=False,
                      header=0,
                      na_values=["\\N","nan","NaN"],
                      keep_default_na=False,
                      na_filter=True,
                      verbose=False)

                                   knownForTitles
0 tt0072308,tt0045537,tt0053137,tt0050419
1 tt0117057,tt0037382,tt0038355,tt0071877
2 tt0049189,tt0056404,tt0057345,tt0054452
3 tt0072562,tt0077975,tt0078723,tt0080455
4 tt0060827,tt0083922,tt0050976,tt0050986
... ...
12169467 tt11657662,tt2455546,tt14069590
12169468 NaN
12169469 tt8736744
12169470 NaN
12169471 NaN
------------------
                            primaryProfession
0 soundtrack, actor, miscellaneous
1 actress, sound track
2 actress, soundtrack, music_department
3 actor, soundtrack, writer
4 writer, director, actor
... ...
12169467 animation_department,art_department
12169468
12169469 cinematographer
12169470 cinematographer
12169471

</code>```

I thought about changing DB and playing in MySQL/SQL but I had a recent hope to not have to redo everything.

MongoDB has a function called $lookup and how to make relationships between collations, but now I need some fields to be saved as an array.

The Pandas documentation says that the dtype can be a dict, but the field is not formatted as such, they are huge files, this one for example has 12m of records.

https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html

Does anyone have an idea how to do this?

Mongo Example

I've already tried:

converters={'primaryProfession': ast.literal_eval,'knownForTitles': ast.literal_eval},

test = np.array(dfname['knownForTitles'].tolist())

"','".join(map(str,dfname['knownForTitles']))

dtype={'primaryProfession': np.array , 'knownForTitles':'np.array'}

Title: IMDB Dataset using Pandas and MongoDB

Body:
I'm using pandas with read_csv because the dataset that is available in TSV.

https://datasets.imdbws.com/ - dataset link

(I'm using name.basics.tsv in the example below.
https://www.imdb.com/interfaces/ - link to details of each file

What's my problem? By chance, at the time I started work, I thought it would be better to use MongoDB to store all the processing I've been doing.

Coming now to the end of the work, I come across a problem that is preventing me from continuing to create some Dashboards with Metabase.

I need to make sure that when reading the TSV, or when processing the data when creating the DataFrame before going to MongoDB, a field is created as an array, because it contains more than one piece of information, separated by a comma.

I know that within MongoDB you can do this (change the field type manually to array). But how to do this through Python? I made some attempts at treatment and alteration but without success. I'll show you how I'm currently reading the file.

Some dataset fields have more than one piece of information, and for the solution I'm using now to plot it, it would help me a lot if some fields were a string array type (below an example)

import pandas as pd
from pymongo import MongoClient
import numpy as np
from ast import literal_eval

mc = MongoClient("mongodb://localhost:27017/")
db = mc._database_default_options(name='imdbdash')

file = "../IMDBDATASET/name.basics.tsv"
dfname = pd.read_csv(filepath_or_buffer=file,
                      sep = '\t',
                      #dtype={'primaryProfession': np.array , 'knownForTitles':'np.array'},
                      #converters={'primaryProfession': literal_eval,'knownForTitles': literal_eval,},
                      low_memory=False,
                      header=0,
                      na_values=["\\N","nan","NaN"],
                      keep_default_na=False,
                      na_filter=True,
                      verbose=False)

                                   knownForTitles
0 tt0072308,tt0045537,tt0053137,tt0050419
1 tt0117057,tt0037382,tt0038355,tt0071877
2 tt0049189,tt0056404,tt0057345,tt0054452
3 tt0072562,tt0077975,tt0078723,tt0080455
4 tt0060827,tt0083922,tt0050976,tt0050986
... ...
12169467 tt11657662,tt2455546,tt14069590
12169468 NaN
12169469 tt8736744
12169470 NaN
12169471 NaN
------------------
                            primaryProfession
0 soundtrack, actor, miscellaneous
1 actress, sound track
2 actress, soundtrack, music_department
3 actor, soundtrack, writer
4 writer, director, actor
... ...
12169467 animation_department,art_department
12169468
12169469 cinematographer
12169470 cinematographer
12169471

I thought about changing DB and playing in MySQL/SQL but I had a recent hope to not have to redo everything.

MongoDB has a function called $lookup and how to make relationships between collations, but now I need some fields to be saved as an array.

The Pandas documentation says that the dtype can be a dict, but the field is not formatted as such, they are huge files, this one for example has 12m of records.

https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html

Does anyone have an idea how to do this?

Mongo Example

I've already tried:

converters={'primaryProfession': ast.literal_eval,'knownForTitles': ast.literal_eval},

test = np.array(dfname['knownForTitles'].tolist())

"','".join(map(str,dfname['knownForTitles']))

dtype={'primaryProfession': np.array , 'knownForTitles':'np.array'}


问:
Databricks Azure: Getting issue NoSuchMethodError: org.apache.spark.sql.Dataset.exprEnc()Lorg/apache/spark/sql/catalyst/encoders/ExpressionEncoder;
We are trying to run the job on spark databricks with Azure but getting the NoSuchMethodError: org.apache.spark.sql.Dataset.exprEnc()Lorg/apache/spark/sql/catalyst/encoders/ExpressionEncoder; error. We are using Databricks 10.4LTS version with spark 3.2.0-SNAPSHOT. Please find below the concerned code block.

```<code>import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.spark.api.java.function.MapPartitionsFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class Test1 implements MapPartitionsFunction<Row, Row>{

  private void doTest() {
    SparkSession session = SparkSession.builder().appName("DgDB").master("local[*]")
        .getOrCreate();

   Dataset<Row> dataSet = session.read().option("charset", "UTF-8")
    .format("text").load("<filePath>");
    Dataset<Row> singlePartition = dataSet.mapPartitions(this, dataSet.exprEnc()).repartition(1);

  }

  public static void main(String[] args) {

   System.out.println("helloo");
   Test1 test= new Test1();
   test.doTest();
  }

  @Override
  public Iterator<Row> call(Iterator<Row> input) throws Exception {
    while (input.hasNext()) {

      Row row = input.next();

      List<Object> columns = new ArrayList<>();
      for (int i = 0; i < row.length(); i++) {
        columns.add(row.get(i));
      }
      System.out.println("rowss: "+columns);
    }
    return null;
  }
}
</code>```

Furthermore, I have tried to find the jar version from where Dataset class is being loaded and I got "file:/databricks/jars/----workspace_spark_3_2--sql--core--core-hive-2.3__hadoop-3.2_2.12_deploy.jar". However, I am not able to track the path of this jar. From where this jar is loading ?

Could anyone please help to fix this issue

The same code block was working fine on databricks 7.4 version with Spark 2.x.

Body:
We are trying to run the job on spark databricks with Azure but getting the NoSuchMethodError: org.apache.spark.sql.Dataset.exprEnc()Lorg/apache/spark/sql/catalyst/encoders/ExpressionEncoder; error. We are using Databricks 10.4LTS version with spark 3.2.0-SNAPSHOT. Please find below the concerned code block.

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

import org.apache.spark.api.java.function.MapPartitionsFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class Test1 implements MapPartitionsFunction<Row, Row>{

  private void doTest() {
    SparkSession session = SparkSession.builder().appName("DgDB").master("local[*]")
        .getOrCreate();

   Dataset<Row> dataSet = session.read().option("charset", "UTF-8")
    .format("text").load("<filePath>");
    Dataset<Row> singlePartition = dataSet.mapPartitions(this, dataSet.exprEnc()).repartition(1);

  }

  public static void main(String[] args) {

   System.out.println("helloo");
   Test1 test= new Test1();
   test.doTest();
  }

  @Override
  public Iterator<Row> call(Iterator<Row> input) throws Exception {
    while (input.hasNext()) {

      Row row = input.next();

      List<Object> columns = new ArrayList<>();
      for (int i = 0; i < row.length(); i++) {
        columns.add(row.get(i));
      }
      System.out.println("rowss: "+columns);
    }
    return null;
  }
}

Furthermore, I have tried to find the jar version from where Dataset class is being loaded and I got "file:/databricks/jars/----workspace_spark_3_2--sql--core--core-hive-2.3__hadoop-3.2_2.12_deploy.jar". However, I am not able to track the path of this jar. From where this jar is loading ?

Could anyone please help to fix this issue

The same code block was working fine on databricks 7.4 version with Spark 2.x.


问:
How to get Kerberos Authentication on my HDFS Web UI?
Wanting to secure the Hadoop web UI. NOT USING AMBARI. RHEL 7 single node cluster. Parameters are shown in images from my core-site.xml and security auth error on web UI shown in image as well. My goal here is to either set a login screen to the web UI or use Kerberos to grant user authentication token. On this RHEL box, kinit username then typing in AD password works fine and krbtgt AD account grants ticket to said username. There is something I am missing or my parameters are incorrectly set. Please assist on adding security to my Hadoop cluster's web UI. Thanks! (Note: cookie domain param is my domain name & Kerberos principal param is the value I was returned from klist after kinit username)

WEB UI

Half of my core-site.xml params

Other half of my core-site.xml params

Tried to set the http security parameters. Was expecting login page to web UI or to just get authenticated through AD / kerberos to web UI, however, that is not the result currently.


问:
gulp.js allowEmpty:true does not work properly
In my gulp.js code, I use the replace method to replace the html tags src and href attributes:

```<code>// HTML
function html(callback) {
    return src([paths.src.html, '!./src/partials/**/*'])
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(replace(/[^(th:src)]src="(.{0,10})node_modules/g, 'src="$1assets/libs'))
        .pipe(replace(/[^(th:href)]href="(.{0,10})node_modules/g, 'href="$1assets/libs'))
        .pipe(useref())
        .pipe(replace(/[^(th:href)]href=".\//g, 'href="'))
        .pipe(replace(/[^(th:href)]href="(.{0,14})assets/g, 'href="../$1static/assets'))
        .pipe(replace(/[^(th:src)]src=".\//g, 'src="'))
        .pipe(replace(/[^(th:src)]src="(.{0,14})assets/g, 'src="../$1static/assets'))

    .pipe(cached())

    .pipe(dest(paths.dist.html))
        .pipe(browsersync.stream());
    callback();
}
</code>```

My HTML file is as follows:

```<code><!-- Libs JS -->
<script th:src="@{/assets/libs/jquery/dist/jquery.min.js}" src="@@webRoot/node_modules/jquery/dist/jquery.min.js"></script>
<script th:src="@{/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js}" src="@@webRoot/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script th:src="@{/assets/libs/simplebar/dist/simplebar.min.js}" src="@@webRoot/node_modules/simplebar/dist/simplebar.min.js"></script>

<!-- Theme JS -->
<!-- build:js @@webRoot/assets/js/theme.min.js -->
<script th:src="@{/assets/js/main.js}" src="@@webRoot/assets/js/main.js"></script>
<script th:src="@{/assets/js/darkMode.js}" src="@@webRoot/assets/js/darkMode.js"></script>
<!-- endbuild -->
</code>```

As you can see above, the 'th:src' and 'th:href' attributes should not be used to include anything (because they are Thymeleaf attributes with nothing to do with frontend), but (I assume) because they contain'src' and 'href' substrings/keywords, it considers including values of'src' and 'href' attributes.

To summarize, gulp.js should evaluate just the values of the'src' and 'href' properties to include, but not 'th:src' and 'th:href'.

This is the error I get:

```<code>[22:04:16] 'html' errored after 139 ms
[22:04:16] Error: Error: File not found with singular glob: C:\project_folder\src\@{/assets/css/theme.css} (if this was purposeful, use `allowEmpty` option)
    at DestroyableTransform.<anonymous> (C:\project_folder\node_modules\gulp-useref\index.js:63:32)
    at DestroyableTransform.emit (node:events:513:28)
    at DestroyableTransform.emit (node:domain:489:12)
    at Pumpify.emit (node:events:513:28)
    at Pumpify.emit (node:domain:489:12)
    at Pumpify.Duplexify._destroy (C:\project_folder\node_modules\duplexify\index.js:191:15)
    at C:\project_folder\node_modules\duplexify\index.js:182:10
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
[22:04:16] 'build' errored after 158 ms
</code>```

I attempted to solve the problem by using 'allowEmpty:true':

```<code>src([paths.src.html, '!./src/partials/**/*'],{allowEmpty:true})...
</code>```

It didn't work, and I received the same error.

If I've missed something about the problem and you cannot understand it, please let me know so I can include it here.

Thank you in advance!

Body:
In my gulp.js code, I use the replace method to replace the html tags src and href attributes:

// HTML
function html(callback) {
    return src([paths.src.html, '!./src/partials/**/*'])
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(replace(/[^(th:src)]src="(.{0,10})node_modules/g, 'src="$1assets/libs'))
        .pipe(replace(/[^(th:href)]href="(.{0,10})node_modules/g, 'href="$1assets/libs'))
        .pipe(useref())
        .pipe(replace(/[^(th:href)]href=".\//g, 'href="'))
        .pipe(replace(/[^(th:href)]href="(.{0,14})assets/g, 'href="../$1static/assets'))
        .pipe(replace(/[^(th:src)]src=".\//g, 'src="'))
        .pipe(replace(/[^(th:src)]src="(.{0,14})assets/g, 'src="../$1static/assets'))

    .pipe(cached())

    .pipe(dest(paths.dist.html))
        .pipe(browsersync.stream());
    callback();
}

My HTML file is as follows:

As you can see above, the 'th:src' and 'th:href' attributes should not be used to include anything (because they are Thymeleaf attributes with nothing to do with frontend), but (I assume) because they contain'src' and 'href' substrings/keywords, it considers including values of'src' and 'href' attributes.

To summarize, gulp.js should evaluate just the values of the'src' and 'href' properties to include, but not 'th:src' and 'th:href'.

This is the error I get:

[22:04:16] 'html' errored after 139 ms
[22:04:16] Error: Error: File not found with singular glob: C:\project_folder\src\@{/assets/css/theme.css} (if this was purposeful, use `allowEmpty` option)
    at DestroyableTransform.<anonymous> (C:\project_folder\node_modules\gulp-useref\index.js:63:32)
    at DestroyableTransform.emit (node:events:513:28)
    at DestroyableTransform.emit (node:domain:489:12)
    at Pumpify.emit (node:events:513:28)
    at Pumpify.emit (node:domain:489:12)
    at Pumpify.Duplexify._destroy (C:\project_folder\node_modules\duplexify\index.js:191:15)
    at C:\project_folder\node_modules\duplexify\index.js:182:10
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
[22:04:16] 'build' errored after 158 ms

I attempted to solve the problem by using 'allowEmpty:true':

src([paths.src.html, '!./src/partials/**/*'],{allowEmpty:true})...

It didn't work, and I received the same error.

If I've missed something about the problem and you cannot understand it, please let me know so I can include it here.

Thank you in advance!


问:
change node features in pytorch geometric
I am trying to change node features of mnistsuperpixel of pytorch geometric dataset but features don't change. feature extraction part is done by a simple cnn which create a 10X1 feature. accuracy of extraction is not important, my goal is to just change the node feature.

this is the process :

import torch
import torchvision

# Load the MNIST dataset
mnist_dataset = torchvision.datasets.MNIST(root='.', train=True, download=True, transform=torchvision.transforms.ToTensor())

# Define a model to extract features from the images
class FeatureExtractor(torch.nn.Module):
    def __init__(self):
        super(FeatureExtractor, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.fc1 = torch.nn.Linear(320, 50)
        self.fc2 = torch.nn.Linear(50, 10)

    def forward(self, x):
        x = torch.nn.functional.relu(torch.nn.functional.max_pool2d(self.conv1(x), 2))
        x = torch.nn.functional.relu(torch.nn.functional.max_pool2d(self.conv2(x), 2))
        x = x.view(-1, 320)
        x = torch.nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = FeatureExtractor()

# Extract features from the MNIST dataset
features = []
for i, (image, label) in enumerate(mnist_dataset):
    # Convert the image to a tensor and pass it through the model
    image = image.unsqueeze(0)
    feature = model(image).squeeze().tolist()

    # Save the feature and label to a list
    features.append((feature, label))

# Save the features to a file
with open('features.txt', 'w') as f:
    for feature, label in features:
        f.write(str(label) + ',' + ','.join([str(x) for x in feature]) + '\n')
```
<p>now features are stored in features.txt</p>
<p>If I get value for features and dataset node features I'll get bellow :</p>
<p><code>features[0]</code></p>
<pre class="lang-py prettyprint-override"><code>([0.04065924137830734,
  -0.17148707807064056,
  -0.028605971485376358,
  -0.08014429360628128,
  0.049180179834365845,
  -0.02591242454946041,
  -0.08026853948831558,
  -0.13666193187236786,
  -0.07752594351768494,
  0.06033480912446976],
 5)
</code>```

and

dataset[0].x
```
<pre class="lang-py prettyprint-override"><code>tensor([[0.6005],
        [0.7350],
        [0.5124],
        [0.7634],
        [0.5810],
        [0.7941],
        [0.7025],
        [0.6235],
        [0.7882],
        [0.5838],
        [0.5105],
        [0.2810],
        [0.5782],
        [0.7797],
        [0.4412],
        [0.6409],
        [0.2843],
        [0.7843],
        [0.6980],
        [0.5314],
        [0.8451],
        [0.7182],
        [0.2941],
        [0.6033],
        [0.8843],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000]])
</code>```

dataset[0].num_features # this will print 1
```
<p>now change the node features :</p>
<pre class="lang-py prettyprint-override"><code>import torch
import torch_geometric.data
from torch_geometric.loader import DataLoader

# Load the MNIST superpixels dataset from PyG
dataset = torch_geometric.datasets.MNISTSuperpixels(root='.', train=True)

# Load the extracted features from the file
features = []
with open('features.txt', 'r') as f:
    for line in f:
        label, feature_str = line.strip().split(',')[0], line.strip().split(',')[1:]
        feature = [float(x) for x in line.strip().split(',')[1:]]
        features.append((int(label), feature))

# Make sure the number of features matches the number of nodes in the dataset
assert len(features) == len(dataset)

# Create a list of Data objects with the label, edge index, pos, and features

for data, (label, feature) in zip(dataset, features):
    data.x = feature
</code>```

So now after changing data.x value, node features are still same:

dataset[0].x
```
<pre class="lang-py prettyprint-override"><code>tensor([[0.6005],
        [0.7350],
        [0.5124],
        [0.7634],
        [0.5810],
        [0.7941],
        [0.7025],
        [0.6235],
        [0.7882],
        [0.5838],
        [0.5105],
        [0.2810],
        [0.5782],
        [0.7797],
        [0.4412],
        [0.6409],
        [0.2843],
        [0.7843],
        [0.6980],
        [0.5314],
        [0.8451],
        [0.7182],
        [0.2941],
        [0.6033],
        [0.8843],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000]])
</code>```

dataset[0].num_features # will print 1 again
```

Body:
I am trying to change node features of mnistsuperpixel of pytorch geometric dataset but features don't change. feature extraction part is done by a simple cnn which create a 10X1 feature. accuracy of extraction is not important, my goal is to just change the node feature.

this is the process :

import torch
import torchvision

# Load the MNIST dataset
mnist_dataset = torchvision.datasets.MNIST(root='.', train=True, download=True, transform=torchvision.transforms.ToTensor())

# Define a model to extract features from the images
class FeatureExtractor(torch.nn.Module):
    def __init__(self):
        super(FeatureExtractor, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.fc1 = torch.nn.Linear(320, 50)
        self.fc2 = torch.nn.Linear(50, 10)

    def forward(self, x):
        x = torch.nn.functional.relu(torch.nn.functional.max_pool2d(self.conv1(x), 2))
        x = torch.nn.functional.relu(torch.nn.functional.max_pool2d(self.conv2(x), 2))
        x = x.view(-1, 320)
        x = torch.nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = FeatureExtractor()

# Extract features from the MNIST dataset
features = []
for i, (image, label) in enumerate(mnist_dataset):
    # Convert the image to a tensor and pass it through the model
    image = image.unsqueeze(0)
    feature = model(image).squeeze().tolist()

    # Save the feature and label to a list
    features.append((feature, label))

# Save the features to a file
with open('features.txt', 'w') as f:
    for feature, label in features:
        f.write(str(label) + ',' + ','.join([str(x) for x in feature]) + '\n')

now features are stored in features.txt

If I get value for features and dataset node features I'll get bellow :

features[0]

([0.04065924137830734,
  -0.17148707807064056,
  -0.028605971485376358,
  -0.08014429360628128,
  0.049180179834365845,
  -0.02591242454946041,
  -0.08026853948831558,
  -0.13666193187236786,
  -0.07752594351768494,
  0.06033480912446976],
 5)

and

dataset[0].x

tensor([[0.6005],
        [0.7350],
        [0.5124],
        [0.7634],
        [0.5810],
        [0.7941],
        [0.7025],
        [0.6235],
        [0.7882],
        [0.5838],
        [0.5105],
        [0.2810],
        [0.5782],
        [0.7797],
        [0.4412],
        [0.6409],
        [0.2843],
        [0.7843],
        [0.6980],
        [0.5314],
        [0.8451],
        [0.7182],
        [0.2941],
        [0.6033],
        [0.8843],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000]])

dataset[0].num_features # this will print 1

now change the node features :

import torch
import torch_geometric.data
from torch_geometric.loader import DataLoader

# Load the MNIST superpixels dataset from PyG
dataset = torch_geometric.datasets.MNISTSuperpixels(root='.', train=True)

# Load the extracted features from the file
features = []
with open('features.txt', 'r') as f:
    for line in f:
        label, feature_str = line.strip().split(',')[0], line.strip().split(',')[1:]
        feature = [float(x) for x in line.strip().split(',')[1:]]
        features.append((int(label), feature))

# Make sure the number of features matches the number of nodes in the dataset
assert len(features) == len(dataset)

# Create a list of Data objects with the label, edge index, pos, and features

for data, (label, feature) in zip(dataset, features):
    data.x = feature

So now after changing data.x value, node features are still same:

dataset[0].x

tensor([[0.6005],
        [0.7350],
        [0.5124],
        [0.7634],
        [0.5810],
        [0.7941],
        [0.7025],
        [0.6235],
        [0.7882],
        [0.5838],
        [0.5105],
        [0.2810],
        [0.5782],
        [0.7797],
        [0.4412],
        [0.6409],
        [0.2843],
        [0.7843],
        [0.6980],
        [0.5314],
        [0.8451],
        [0.7182],
        [0.2941],
        [0.6033],
        [0.8843],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000],
        [0.0000]])

dataset[0].num_features # will print 1 again


问:
p4v: You need to get version 2.0 (or later) of PyGTK for this to work
I installed p4vasp and I am getting an error which I am not able to resolve.

```<code>You need to get version 2.0 (or later) of PyGTK for this to work. You
             can get source code from http://www.pygtk.org
</code>```

I have also attached diagnostic script. Kindly help me with the installation of pyGTK. I installed the same but still getting the same error.

I guess python different versions are causing the error. But I don't know how to resolve it.

Body:
I installed p4vasp and I am getting an error which I am not able to resolve.

You need to get version 2.0 (or later) of PyGTK for this to work. You
             can get source code from http://www.pygtk.org

I have also attached diagnostic script. Kindly help me with the installation of pyGTK. I installed the same but still getting the same error.

I guess python different versions are causing the error. But I don't know how to resolve it.


问:
Suricatta daemon mode: No suitable .swu image found
I'm trying to use hawkbit + swupdate to update my embedded linux system, the swupdate is already working, I can update the system locally. But when I try to use with hawkbit some erros appears.

[ERROR] : SWUPDATE failed [0] ERROR corelib/channel_curl.c : channel_get_file : 855 : Cannot initialize sha1 checksum context.

[ERROR] : SWUPDATE failed [0] ERROR suricatta/server_hawkbit.c : server_hawkbit_error : 174 : No suitable .swu image found

[ERROR] : SWUPDATE failed [0] ERROR suricatta/server_hawkbit.c : server_install_update : 1241 : Error processing update chunk named 'rootfs', version 1.0, part os

I don't understand why isn't working because I can update the system locally with this .swu file using the command "swupdate -i <swu-file>"

I'm trying update my embbeded linux system via suricatta but its not working