问:
Xamarin Forms application - Force IPv4 to HttpClient
It appears that this can be achieved by setting up a callback function to the ServicePoint.

The solution (although the goal is different, the same technique can be used) is discussed in this question Specify the local endpoint for HTTP request.

Following it, I tried

```<code>var servicePoint = ServicePointManager.FindServicePoint(new Uri(uri));
servicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) =>
{
  if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  {
    return new IPEndPoint(IPAddress.Any, 0);
  }

  throw new InvalidOperationException("no IPv4 address");
};

var _client = new HttpClient();
HttpResponseMessage response = await _client.GetAsync(uri);
</code>```

expecting that the callback is called at the GetAsync() but it is not.

It would be much appreciated if someone tells me what I am missing.
Or, a completely different approach to achieve my goal, to force IPv4 at connections that HttpClient makes, would also be very much welcome.

Thanks in advance for your help.

Update

In the question How to use HttpClient to send a Request from a specific IP address? C#, someone says "... the .net core team have implemented the HttpClientHandler etc without bothering to put anything related to service points in there ..."
To confirm, I build the above code both with Framework4.7 and Core3.1 to find out that indeed, when built with Core, the callback is NOT called.

A Xamarin project targets .Net standard, which is a Core if I am not mistaken. I guess I need to forget this ServicePoint stuff and look for other solutions...

Again, your insight will be very much appreciated!

Body:
It appears that this can be achieved by setting up a callback function to the ServicePoint.

The solution (although the goal is different, the same technique can be used) is discussed in this question Specify the local endpoint for HTTP request.

Following it, I tried

var servicePoint = ServicePointManager.FindServicePoint(new Uri(uri));
servicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) =>
{
  if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  {
    return new IPEndPoint(IPAddress.Any, 0);
  }

  throw new InvalidOperationException("no IPv4 address");
};

var _client = new HttpClient();
HttpResponseMessage response = await _client.GetAsync(uri);

expecting that the callback is called at the GetAsync() but it is not.

It would be much appreciated if someone tells me what I am missing.
Or, a completely different approach to achieve my goal, to force IPv4 at connections that HttpClient makes, would also be very much welcome.

Thanks in advance for your help.

Update

In the question How to use HttpClient to send a Request from a specific IP address? C#, someone says "... the .net core team have implemented the HttpClientHandler etc without bothering to put anything related to service points in there ..."
To confirm, I build the above code both with Framework4.7 and Core3.1 to find out that indeed, when built with Core, the callback is NOT called.

A Xamarin project targets .Net standard, which is a Core if I am not mistaken. I guess I need to forget this ServicePoint stuff and look for other solutions...

Again, your insight will be very much appreciated!


来源: stackexchange

问:
setState function was working in React.js but not working in Next.js
I've been struggling with this one for 2-3 days and hope someone can help.  I am moving a blog project over from React to Next, and in one particular case a setState function isn't working.

The code below lives in the _app.tsx function at the top of my project. The editPost function is called from a button in a child component. The code pulls the selected blog post from the database then updates the state of postToEdit. This data is meant to be injected into an edit form via props-- and works fine in the React version of the blog.

In this case, the setState (setPostToEdit) function seems to do nothing. In the console.log function after setPostToEdit(newPostToEdit), you can see that the data has been pulled from Postgres correctly, but the state doesn't change.

In the deletePost and getPosts function in this same _app component, everything works fine.  Weird! Any help sincerely appreciated, I'm new to both React and Next.

```<code>import '../styles/globals.css'
import React, { useState, useEffect } from 'react'
import type { AppProps } from 'next/app'
import Layout from '../components/Layout'

export default function App({ Component, pageProps }: AppProps) {
  const initPostToEdit = {
    post_id: '',
    title: 'initial post title',
    sub_title: '',
    main_content: '',
    post_url: 'initial URL',
    page_title: '',
    meta_description: '',
    meta_keywords: ''
  }

  const [posts, setPosts] = useState([]);
  const [postToEdit, setPostToEdit] = useState(initPostToEdit);
  const [blogValues, setBlogValues] = useState(initPostToEdit);

  const deletePost = async (id) => {
    try {
      await fetch(`http://localhost:5001/blog-edit/${id}`, {
        method: "DELETE"
      })
      setPosts(posts.filter(post => post.post_id !== id))

    } catch (error) {
      console.error(error.message)
    }
  }

  const editPost = async (id) => {
    try {
      const response = await fetch(`http://localhost:5001/blog-edit/${id}`, {
        method: "GET"
      })
      const newPostToEdit = await response.json()

      setPostToEdit(newPostToEdit)

      console.log('postToEdit:', newPostToEdit[0], postToEdit)

      window.location.assign("/admin/blog-edit");

    } catch (error) {
      console.error(error.message)
    }
  }

  const getPosts = async () => {
    try {
      const response = await fetch("http://localhost:5001/blog-edit");
      const jsonData = await response.json();
      setPosts(jsonData);
    } catch (error) {
      console.error(error.message)
    }
  }

  useEffect(() => { getPosts(); }, [])

  return (
    <div>
      <Layout>
        <Component
          {...pageProps}
          editPost={editPost}
          postToEdit={postToEdit}
          setPostToEdit={setPostToEdit}
          blogValues={blogValues}
          setBlogValues={setBlogValues}
          posts={posts}
          deletePost={deletePost}
        />
      </Layout>
    </div>
  )
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been struggling with this one for 2-3 days and hope someone can help.  I am moving a blog project over from React to Next, and in one particular case a setState function isn't working.

The code below lives in the _app.tsx function at the top of my project. The editPost function is called from a button in a child component. The code pulls the selected blog post from the database then updates the state of postToEdit. This data is meant to be injected into an edit form via props-- and works fine in the React version of the blog.

In this case, the setState (setPostToEdit) function seems to do nothing. In the console.log function after setPostToEdit(newPostToEdit), you can see that the data has been pulled from Postgres correctly, but the state doesn't change.

In the deletePost and getPosts function in this same _app component, everything works fine.  Weird! Any help sincerely appreciated, I'm new to both React and Next.

import '../styles/globals.css'
import React, { useState, useEffect } from 'react'
import type { AppProps } from 'next/app'
import Layout from '../components/Layout'

export default function App({ Component, pageProps }: AppProps) {
  const initPostToEdit = {
    post_id: '',
    title: 'initial post title',
    sub_title: '',
    main_content: '',
    post_url: 'initial URL',
    page_title: '',
    meta_description: '',
    meta_keywords: ''
  }

  const [posts, setPosts] = useState([]);
  const [postToEdit, setPostToEdit] = useState(initPostToEdit);
  const [blogValues, setBlogValues] = useState(initPostToEdit);

  const deletePost = async (id) => {
    try {
      await fetch(`http://localhost:5001/blog-edit/${id}`, {
        method: "DELETE"
      })
      setPosts(posts.filter(post => post.post_id !== id))

    } catch (error) {
      console.error(error.message)
    }
  }

  const editPost = async (id) => {
    try {
      const response = await fetch(`http://localhost:5001/blog-edit/${id}`, {
        method: "GET"
      })
      const newPostToEdit = await response.json()

      setPostToEdit(newPostToEdit)

      console.log('postToEdit:', newPostToEdit[0], postToEdit)

      window.location.assign("/admin/blog-edit");

    } catch (error) {
      console.error(error.message)
    }
  }

  const getPosts = async () => {
    try {
      const response = await fetch("http://localhost:5001/blog-edit");
      const jsonData = await response.json();
      setPosts(jsonData);
    } catch (error) {
      console.error(error.message)
    }
  }

  useEffect(() => { getPosts(); }, [])

  return (

      <Layout>
        <Component
          {...pageProps}
          editPost={editPost}
          postToEdit={postToEdit}
          setPostToEdit={setPostToEdit}
          blogValues={blogValues}
          setBlogValues={setBlogValues}
          posts={posts}
          deletePost={deletePost}
        />
      </Layout>

  )
}


问:
facing issue with gradle install command: `java.lang.NoSuchMethodError: org.gradle.internal.jvm.inspection.JvmMetadataDetector.getMetadata `
I am trying to run gradle install. The goal is to convert to the gradle project to a mvn project. For that we have the mvn plugin as a part of gradle project.

gradle version is 7.6

java version is java 11

gradle build file:

```<code>
plugins {
    id 'java'
    id 'idea'
    id 'jacoco'
    id 'maven-publish'
    id 'com.diffplug.spotless' version '5.11.0'
    id 'checkstyle'
    id 'nebula.ospackage'  version "8.3.0"
    id "org.gradle.test-retry" version "1.3.1"
}

spotless {
  java {
    // note: you can use an empty string for all the imports you didn't specify explicitly, and '\\#` prefix for static imports
    importOrder('java', 'javax', '', 'com.amazon', 'org.opensearch', '\\#')
  }
}

java.sourceCompatibility = JavaVersion.VERSION_11
java.targetCompatibility = JavaVersion.VERSION_11

tasks.withType(Checkstyle) {
    showViolations true
    reports {
        ignoreFailures = false
    }
}

tasks.withType(JavaCompile) {
    configure(options) {
        options.encoding = 'UTF-8'
        options.compilerArgs << '-Xlint:removal' << '-Werror'
    }
}

tasks.test.finalizedBy(jacocoTestReport)  // report is always generated after tests run
tasks.jacocoTestReport.dependsOn(test) // tests are required to run before generating the report

allprojects {
    tasks.withType(Javadoc).all { enabled = false }
}

bundlePlugin {
    from('plugin-security.policy')
    from('config') {
        into 'config'
    }
    from('tools') {
        into 'tools'
    }
}
</code>```

But facing the below issue:

```<code>org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:49)
Caused by: java.lang.NoSuchMethodError: org.gradle.internal.jvm.inspection.JvmMetadataDetector.getMetadata(Ljava/io/File;)Lorg/gradle/internal/jvm/inspection/JvmInstallationMetadata;
        at
    ```
```

Body:
I am trying to run gradle install. The goal is to convert to the gradle project to a mvn project. For that we have the mvn plugin as a part of gradle project.

gradle version is 7.6

java version is java 11

gradle build file:

plugins {
    id 'java'
    id 'idea'
    id 'jacoco'
    id 'maven-publish'
    id 'com.diffplug.spotless' version '5.11.0'
    id 'checkstyle'
    id 'nebula.ospackage'  version "8.3.0"
    id "org.gradle.test-retry" version "1.3.1"
}

spotless {
  java {
    // note: you can use an empty string for all the imports you didn't specify explicitly, and '\\#` prefix for static imports
    importOrder('java', 'javax', '', 'com.amazon', 'org.opensearch', '\\#')
  }
}

java.sourceCompatibility = JavaVersion.VERSION_11
java.targetCompatibility = JavaVersion.VERSION_11

tasks.withType(Checkstyle) {
    showViolations true
    reports {
        ignoreFailures = false
    }
}

tasks.withType(JavaCompile) {
    configure(options) {
        options.encoding = 'UTF-8'
        options.compilerArgs << '-Xlint:removal' << '-Werror'
    }
}

tasks.test.finalizedBy(jacocoTestReport)  // report is always generated after tests run
tasks.jacocoTestReport.dependsOn(test) // tests are required to run before generating the report

allprojects {
    tasks.withType(Javadoc).all { enabled = false }
}

bundlePlugin {
    from('plugin-security.policy')
    from('config') {
        into 'config'
    }
    from('tools') {
        into 'tools'
    }
}

But facing the below issue:

org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:49)
Caused by: java.lang.NoSuchMethodError: org.gradle.internal.jvm.inspection.JvmMetadataDetector.getMetadata(Ljava/io/File;)Lorg/gradle/internal/jvm/inspection/JvmInstallationMetadata;
        at
    ```


问:
How to upload upload image/file to akamai server using play framework
This is the code in scala how can we do a similar thing in java using the play framework
reference: -> Play WS - post multipart/form-data from scala - Bad Request

```<code>import akka.stream.scaladsl.FileIO
    import akka.stream.scaladsl.Source
    import play.api.libs.ws.WSClient
    import play.api.mvc.MultipartFormData._

    val pathToFile = "./sampleCV.pdf"
    val fileName = "sampleCV.pdf"
    val futureResponse = ws.url(url).withRequestTimeout(Duration.create(55, TimeUnit.SECONDS))
          .addHttpHeaders("authorization" -> s"bearer $access_token")
          .addHttpHeaders("accept" -> "*/*")
          .addHttpHeaders("content-type" -> "multipart/form-data")
          .post(Source(
            FilePart("File", fileName, Option("application/pdf"), FileIO.fromPath(Paths.get(pathToFile)))  :: List()
          ))
</code>```

I had tried but got 412 as the response code as I was using an HTTP multipart file.

Body:
This is the code in scala how can we do a similar thing in java using the play framework
reference: -> Play WS - post multipart/form-data from scala - Bad Request

import akka.stream.scaladsl.FileIO
    import akka.stream.scaladsl.Source
    import play.api.libs.ws.WSClient
    import play.api.mvc.MultipartFormData._

    val pathToFile = "./sampleCV.pdf"
    val fileName = "sampleCV.pdf"
    val futureResponse = ws.url(url).withRequestTimeout(Duration.create(55, TimeUnit.SECONDS))
          .addHttpHeaders("authorization" -> s"bearer $access_token")
          .addHttpHeaders("accept" -> "*/*")
          .addHttpHeaders("content-type" -> "multipart/form-data")
          .post(Source(
            FilePart("File", fileName, Option("application/pdf"), FileIO.fromPath(Paths.get(pathToFile)))  :: List()
          ))

I had tried but got 412 as the response code as I was using an HTTP multipart file.


问:
HTTP 400 Bad Request IIS Manager
I hosted a website on IIS server and it was done successfully. I am able to access the website from outside of the server and it works fine BUT when I try to run the website from my IIS server by clickin on Browse link on IIS I get the login page but once I login I get 400 BAD REQUEST error.

Error Message Image

Can anyone guide me how to fix this issue on IIS so that I am able to run the website from my IIS server also.

Would appreciate the help.

Thanks.

Title: HTTP 400 Bad Request IIS Manager


问:
How to bind double click on row to command in GridView that inside ListView in MVVM WPF
I'm prrety new to wpf, and i try to make a GridView that inside ListView to response to double click on row in the view

I try to make this-

```<code>    <ListView
        ItemsSource="{Binding Products}">
        <ListView.InputBindings>
            <MouseBinding
                MouseAction="LeftDoubleClick"
                Command="{Binding Test}" />
        </ListView.InputBindings>
        <ListView.View>
            <GridView>
                </GridView.ColumnHeaderContainerStyle>
                <GridViewColumn
                    Header="ID"
                    DisplayMemberBinding="{Binding ID}" />
                <GridViewColumn
                    Header="Name"
                    DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn
                    Header="Category"
                    DisplayMemberBinding="{Binding Category}" />
                <GridViewColumn
                    Header="Price"
                    DisplayMemberBinding="{Binding Price}" />
            </GridView>
        </ListView.View>
     <ListView />
</code>```

when Test is an ICommand property in the view model.
But it's not responding to double click.
What am I getting wrong, and mabye there is another way?

Body:
I'm prrety new to wpf, and i try to make a GridView that inside ListView to response to double click on row in the view

I try to make this-

    <ListView
        ItemsSource="{Binding Products}">
        <ListView.InputBindings>
            <MouseBinding
                MouseAction="LeftDoubleClick"
                Command="{Binding Test}" />
        </ListView.InputBindings>
        <ListView.View>
            <GridView>
                </GridView.ColumnHeaderContainerStyle>
                <GridViewColumn
                    Header="ID"
                    DisplayMemberBinding="{Binding ID}" />
                <GridViewColumn
                    Header="Name"
                    DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn
                    Header="Category"
                    DisplayMemberBinding="{Binding Category}" />
                <GridViewColumn
                    Header="Price"
                    DisplayMemberBinding="{Binding Price}" />
            </GridView>
        </ListView.View>
     <ListView />

when Test is an ICommand property in the view model.
But it's not responding to double click.
What am I getting wrong, and mabye there is another way?


问:
tkinter plot auto rescale
I'm trying to create a GUI that will plot data from an array that is updated when I click a button (in this case move a slider), I can get the data to replot, however, the scale doesn't update and I can't work out how to do it. does anyone have any ideas?
the data is created in a function dataMaker and just returns 2 arrays, one of the time increments and the other of random data.
many thanks

```<code>import tkinter

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure

import numpy as np
import dataMaker as DM

root = tkinter.Tk()
root.wm_title("Embedding in Tk")

fig = Figure(figsize=(5, 4), dpi=100)
rt_data = DM.comboP(1, 1000)
sample = rt_data[1]
torque = rt_data[2]

ax = fig.add_subplot()
line, = ax.plot(sample, torque)

canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()

# pack_toolbar=False will make it easier to use a layout manager later on.
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()

canvas.mpl_connect(
    "key_press_event", lambda event: print(f"you pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)

button_quit = tkinter.Button(master=root, text="Quit", command=root.destroy)

def update_frequency(new_val):
    rt_data = DM.comboP(1, 1000)
    sample = rt_data[1]
    torque = rt_data[2]
    line.set_data(sample, torque)
    ax.autoscale_view()
    # required to update canvas and attached toolbar!
    canvas.draw()

slider_update = tkinter.Scale(root, from_=1, to=5, orient=tkinter.HORIZONTAL,
                              command=update_frequency, label="Frequency [Hz]")

# Packing order is important. Widgets are processed sequentially and if there
# is no space left, because the window is too small, they are not displayed.
# The canvas is rather flexible in its size, so we pack it last which makes
# sure the UI controls are displayed as long as possible.
button_quit.pack(side=tkinter.BOTTOM)
slider_update.pack(side=tkinter.BOTTOM)
toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=True)

tkinter.mainloop()

</code>```

I've searched the internet but can't find a solution, id  like the scale the change to fit the data that's in the array

Title: tkinter plot auto rescale

Body:
I'm trying to create a GUI that will plot data from an array that is updated when I click a button (in this case move a slider), I can get the data to replot, however, the scale doesn't update and I can't work out how to do it. does anyone have any ideas?
the data is created in a function dataMaker and just returns 2 arrays, one of the time increments and the other of random data.
many thanks

import tkinter

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure

import numpy as np
import dataMaker as DM

root = tkinter.Tk()
root.wm_title("Embedding in Tk")

fig = Figure(figsize=(5, 4), dpi=100)
rt_data = DM.comboP(1, 1000)
sample = rt_data[1]
torque = rt_data[2]

ax = fig.add_subplot()
line, = ax.plot(sample, torque)

canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()

# pack_toolbar=False will make it easier to use a layout manager later on.
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()

canvas.mpl_connect(
    "key_press_event", lambda event: print(f"you pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)

button_quit = tkinter.Button(master=root, text="Quit", command=root.destroy)

def update_frequency(new_val):
    rt_data = DM.comboP(1, 1000)
    sample = rt_data[1]
    torque = rt_data[2]
    line.set_data(sample, torque)
    ax.autoscale_view()
    # required to update canvas and attached toolbar!
    canvas.draw()

slider_update = tkinter.Scale(root, from_=1, to=5, orient=tkinter.HORIZONTAL,
                              command=update_frequency, label="Frequency [Hz]")

# Packing order is important. Widgets are processed sequentially and if there
# is no space left, because the window is too small, they are not displayed.
# The canvas is rather flexible in its size, so we pack it last which makes
# sure the UI controls are displayed as long as possible.
button_quit.pack(side=tkinter.BOTTOM)
slider_update.pack(side=tkinter.BOTTOM)
toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=True)

tkinter.mainloop()

I've searched the internet but can't find a solution, id  like the scale the change to fit the data that's in the array


问:
How to retrieve data from connected table with connected ID
I have tables like this:

User:

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty
@Size(min = 3, max = 20)
private String username;

... more fields, not important
</code>```

Wallet:

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty(message = "Please, insert a wallet name")
private String walletName;

private double initialBalance;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private User user;
</code>```

As you can see those two tables are connected, and I can assignee wallet to user.

Now, I created a userProfile HTML page and want to display next stuff: Username, email, initalBalance.

I managed somehow to get principals from logged user:

```<code><h1>Username </h1>
<h1 th:text="${#authentication.getPrincipal().getUsername()}"></h1>
<br>
<h1>Email </h1>
<h1 th:text="${#authentication.getPrincipal().getEmail()}"></h1>
</code>```

But I have problem to show initialBalance of his wallet.

When I try with walletRepository.findAll() obviously that return initialBalances from all users.

This is how I tried so far:

```<code>@GetMapping("/userWallet/{user_id}/balance")
public String getUserWallet(@PathVariable(value = "user_id") Long user_id, Model model, Wallet wallet) {
    model.addAttribute("wallet", walletRepository.findByUserIdAndInitialBalance(user_id, wallet.getInitialBalance()));
    return "userProfile";
}
</code>```

And in HTML:

```<code><tr th:each="wallets:${wallet}">
<div class="title">
    <h1>Balance </h1>
    <h1 th:text="${wallets.initialBalance}"></h1>
</div>
</code>```

But nothing is printed at screen.

So just to be clear, I want to provide a initialBalance from user wallet.

Body:
I have tables like this:

User:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty
@Size(min = 3, max = 20)
private String username;

... more fields, not important

Wallet:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty(message = "Please, insert a wallet name")
private String walletName;

private double initialBalance;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private User user;

As you can see those two tables are connected, and I can assignee wallet to user.

Now, I created a userProfile HTML page and want to display next stuff: Username, email, initalBalance.

I managed somehow to get principals from logged user:

Username

Email

But I have problem to show initialBalance of his wallet.

When I try with walletRepository.findAll() obviously that return initialBalances from all users.

This is how I tried so far:

@GetMapping("/userWallet/{user_id}/balance")
public String getUserWallet(@PathVariable(value = "user_id") Long user_id, Model model, Wallet wallet) {
    model.addAttribute("wallet", walletRepository.findByUserIdAndInitialBalance(user_id, wallet.getInitialBalance()));
    return "userProfile";
}

And in HTML:

Balance

But nothing is printed at screen.

So just to be clear, I want to provide a initialBalance from user wallet.


问:
How do I draw my sprite using strictly public Character and a function
So I have to make Boulder Dash from C64 with C# as a project for school but I'm stuck at the place where I have to draw Rockford(the character). My english is pretty poor for what I want to explain but when you'll see the code, it'll be easier to understand. Everything that's about the character is in the class "Character" and then I have to use public Character to create the sprite, to draw it, I have a function

I don't know how to transfer the sprite from public Character to the function, I tried many things, recreating the character in the function, even tried calling "public Character" in my Draw function

```<code>public Character(string Image, int x, int y, Direction dir)
{
   Image = "images/heros24.bmp";
   x = 4;
   y = 3;
   dir = Direction.Left;
   Texture tRockford = new Texture(Image);
   Sprite sRockford = new Sprite(tRockford);
}

public void Afficher(RenderWindow fenetre, float PixelByCase)
{
 string Image = "images/heros24.bmp";
 int x = 4;
 int y = 3;
 Direction dir = Direction.Left;
 Character p = new Character(Image, x, y, dir);
 Vector2f position = new Vector2f(X * PixelsParCell, Y * PixelsParCell);
 p.Position = position;
 fenetre.Draw(p);
}
</code>```

Body:
So I have to make Boulder Dash from C64 with C# as a project for school but I'm stuck at the place where I have to draw Rockford(the character). My english is pretty poor for what I want to explain but when you'll see the code, it'll be easier to understand. Everything that's about the character is in the class "Character" and then I have to use public Character to create the sprite, to draw it, I have a function

I don't know how to transfer the sprite from public Character to the function, I tried many things, recreating the character in the function, even tried calling "public Character" in my Draw function

public Character(string Image, int x, int y, Direction dir)
{
   Image = "images/heros24.bmp";
   x = 4;
   y = 3;
   dir = Direction.Left;
   Texture tRockford = new Texture(Image);
   Sprite sRockford = new Sprite(tRockford);
}

public void Afficher(RenderWindow fenetre, float PixelByCase)
{
 string Image = "images/heros24.bmp";
 int x = 4;
 int y = 3;
 Direction dir = Direction.Left;
 Character p = new Character(Image, x, y, dir);
 Vector2f position = new Vector2f(X * PixelsParCell, Y * PixelsParCell);
 p.Position = position;
 fenetre.Draw(p);
}


问:
Rasterio for reading large Tiff files
I am trying to convert a large Tiff file into GeoJson. The problem I am facing here is that given the my Tif file is in gigabytes (3.5GB), the programme is getting out of memory.

Is there any way to process this in chunks and write a chunk to the output file every time?

```<code>import rasterio
import rasterio.features
import rasterio.warp

with rasterio.open('MyBigFile.tif') as dataset:

    # Read the dataset's valid data mask as a ndarray.
    mask = dataset.dataset_mask()

    # Extract feature shapes and values from the array.
    for geom, val in rasterio.features.shapes(mask, transform=dataset.transform):

        # Transform shapes from the dataset's own coordinate
        # reference system to CRS84 (EPSG:4326).
        geom = rasterio.warp.transform_geom(
            dataset.crs, 'EPSG:4326', geom, precision=6)

        with open('output.json', 'w') as f:
            f.write(geom)
</code>```

Title: Rasterio for reading large Tiff files

Body:
I am trying to convert a large Tiff file into GeoJson. The problem I am facing here is that given the my Tif file is in gigabytes (3.5GB), the programme is getting out of memory.

Is there any way to process this in chunks and write a chunk to the output file every time?

import rasterio
import rasterio.features
import rasterio.warp

with rasterio.open('MyBigFile.tif') as dataset:

    # Read the dataset's valid data mask as a ndarray.
    mask = dataset.dataset_mask()

    # Extract feature shapes and values from the array.
    for geom, val in rasterio.features.shapes(mask, transform=dataset.transform):

        # Transform shapes from the dataset's own coordinate
        # reference system to CRS84 (EPSG:4326).
        geom = rasterio.warp.transform_geom(
            dataset.crs, 'EPSG:4326', geom, precision=6)

        with open('output.json', 'w') as f:
            f.write(geom)


问:
Programmatically add an access key to a bitbucket repo (Bitbucket cloud API)
The documentation of the Bitbucket Cloud API specifies how to add an SSH key to a specific user.

However, the Bitbucket website also allows to add several SSH "Access keys" (a.k.a. Deployment keys) to a repository, enabling read-only access to the key holders.

Is it possible to add the access keys via the Bitbucket Cloud API?


问:
How to convert RTF ANSI to HTML using Javascript or Any React text editor which support RTF format
I have to render RTF ANSI format data in the React Draft Wysiwyg / any other react editor.

we are getting API response as RTF ANSI format, which I have render in the rich text editor after any changes in the editor text, I have to covert into RTF and save into the DB, I haven't found any solution or Editor which will meet my requirements.

Example RTF String: '{\rtf1ansiansicpg1252deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Arial Black;}{\f2\fnil\fcharset0 Courier New;}{\f3\fnil\fcharset0 Georgia;}{\f4\fnil\fcharset0 Tahoma;}{\f5\fnil\fcharset0 Times New Roman;}{\f6\fnil\fcharset0 Verdana;}}{colortbl ;}{pard\fs34qc Hello Worldsb70par}}'

This is how it look after render in the rich text editor.

I have tried with many converters but no help.

Example: https://stackblitz.com/edit/react-5avkvj?file=src/index.js

Thanks in advance.


问:
Create multiple subscriptions with for_each in terraform returns context deadline exceeded
I have created a module that creates a subscription and other resources via terraform.

As you can see it iterates over this two times. One time where env is "dev" and one time where env is "prod".

the problem is: It creates the subscription "-prod", but it will not create "-dev". The pipeline says "Error: context deadline exceeded" after 30 minutes.

In terraform plan it says that it is all good and it will add the subscription, but it will not do it.

module "wmind_subscription" {
  source = "./subscription"

  for_each            = toset(["dev", "prod"])
  env                 = each.key
  name                = "wmind-it"
  management_group_id = module.wmind_management_group.management_group_id

  repo_name = module.wmind_github.repo_name

}```
</div>
</div>
</p>
<p>The terraform resource thats creates the subscription:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>resource "azurerm_subscription" "this" {
  subscription_name = "${var.name}-${var.env}"
  billing_scope_id  = data.azurerm_billing_mca_account_scope.this.id
}</code>```

full error message:

╷
│ Error: creating new Subscription (Alias "***"): subscription.AliasClient#Create: Failure sending request: StatusCode=0 -- Original Error: context deadline exceeded
│
│   with module.wmind_subscription["dev"].azurerm_subscription.this,
│   on subscription/subscription.tf line 10, in resource "azurerm_subscription" "this":
│   10: resource "azurerm_subscription" "this" {
│
╵```

hope someone can help me, thank you

Body:
I have created a module that creates a subscription and other resources via terraform.

As you can see it iterates over this two times. One time where env is "dev" and one time where env is "prod".

the problem is: It creates the subscription "-prod", but it will not create "-dev". The pipeline says "Error: context deadline exceeded" after 30 minutes.

In terraform plan it says that it is all good and it will add the subscription, but it will not do it.

module "wmind_subscription" {
  source = "./subscription"

  for_each            = toset(["dev", "prod"])
  env                 = each.key
  name                = "wmind-it"
  management_group_id = module.wmind_management_group.management_group_id

  repo_name = module.wmind_github.repo_name

}

The terraform resource thats creates the subscription:

resource "azurerm_subscription" "this" {
  subscription_name = "${var.name}-${var.env}"
  billing_scope_id  = data.azurerm_billing_mca_account_scope.this.id
}

full error message:

╷
│ Error: creating new Subscription (Alias "***"): subscription.AliasClient#Create: Failure sending request: StatusCode=0 -- Original Error: context deadline exceeded
│
│   with module.wmind_subscription["dev"].azurerm_subscription.this,
│   on subscription/subscription.tf line 10, in resource "azurerm_subscription" "this":
│   10: resource "azurerm_subscription" "this" {
│
╵

hope someone can help me, thank you


问:
Search for property in zillow by MLS id
I see that properties in zillow list their MLS id if they have one. Is there a way to search for a property in zillow by its MLS number?

Thanks

Title: Search for property in zillow by MLS id


问:
Is the first write of default values forcefully flushed to main memory in Java?
I heard from somewhere that

The first write to shared primitive variables' default values are immediately visible to other threads

I guess it wants to say that the first write to default values are flushed to memory instead of being cached in local memory.

Like

static boolean flag;
// thread 1
flag = true; // and flushed it to main memory
// thread 2
read(flag); // and flag==true is immediately visible to thread 2 if it fetches it from memory using getstatic after flag = true is executed by thread 1

```

But I was not able to find any resources verifying it. Nor could I make a experiment to reproduce it.(I don't know how to inspect main memory values).

So does anyone with relevant knowledge verify it to be true or false?

Body:
I heard from somewhere that

The first write to shared primitive variables' default values are immediately visible to other threads

I guess it wants to say that the first write to default values are flushed to memory instead of being cached in local memory.

Like

static boolean flag;
// thread 1
flag = true; // and flushed it to main memory
// thread 2
read(flag); // and flag==true is immediately visible to thread 2 if it fetches it from memory using getstatic after flag = true is executed by thread 1

But I was not able to find any resources verifying it. Nor could I make a experiment to reproduce it.(I don't know how to inspect main memory values).

So does anyone with relevant knowledge verify it to be true or false?


问:
How to create index of unique elements of a column in R dataframe
I have this table here, ordered by country:

country
city

Canada
Montreal

Canada
Toronto

France
Paris

France
Lyon

Australia
Melbourne

Japan
Nagoya

I want to create an index col of countries, something like:

index
country
city

1
Canada
Montreal

1
Canada
Toronto

2
France
Paris

2
France
Lyon

3
Australia
Melbourne

4
Japan
Nagoya

I know I can create another df with distinct countries and then merge. I'm looking for something that can be includide in a pipeline.

Here is a reproductible code:

```<code>tibble(country = c('Canada','Canada','France','France','Australia','Japan'),
city = c('Montreal','Toronto','Paris','Lyon','Melbourne','Nagoya'))
</code>```

Thanks!

Body:
I have this table here, ordered by country:

country
city

Canada
Montreal

Canada
Toronto

France
Paris

France
Lyon

Australia
Melbourne

Japan
Nagoya

I want to create an index col of countries, something like:

index
country
city

1
Canada
Montreal

1
Canada
Toronto

2
France
Paris

2
France
Lyon

3
Australia
Melbourne

4
Japan
Nagoya

I know I can create another df with distinct countries and then merge. I'm looking for something that can be includide in a pipeline.

Here is a reproductible code:

tibble(country = c('Canada','Canada','France','France','Australia','Japan'),
city = c('Montreal','Toronto','Paris','Lyon','Melbourne','Nagoya'))

Thanks!


问:
NextGen Gallery Display image ID
I am working with a client who has the Imagely Theme and NextGen plugin installed. He has a massive number of images he displays in galleries and sells images but not online. The thumbnail images open to a lightbox image which displays the ALT & TITLE TEXT / DESCRIPTION but to enable a client to specify exactly which image he wants to purchase my client wants the image ID to appear.  NextGen does not seem to have this as an option even though every image in a gallery has an ID. Example: (2000000152) which is visible in Manage Gallery. I am looking to see if there is any way to edit the code so that the Image ID will also display along with, or in addition to, the currently displaying Title Text/Description.
Thanks</p>

Title: NextGen Gallery Display image ID


问:
How to create a bar chart in R using with both X and Y axis defined?
I want to create a Bar chart in R with both the x and y axis defined, what should I do? I tried but it is showing an error that I can only define either X or Y. What am I doing wrong?

The code:

```<code>a<- c(1, 2, 3, 2, 1)

d<- c("A", "B", "C", "D", "E")

data<- data.frame(a,d)

ggplot(data = data) +

geom_bar(mapping = aes(x= d, y = a, fill = d))
</code>```

enter image description here

I tried to create a Bar chart with both X and Y axis pre defined.

Body:
I want to create a Bar chart in R with both the x and y axis defined, what should I do? I tried but it is showing an error that I can only define either X or Y. What am I doing wrong?

The code:

a<- c(1, 2, 3, 2, 1)

d<- c("A", "B", "C", "D", "E")

data<- data.frame(a,d)

ggplot(data = data) +

geom_bar(mapping = aes(x= d, y = a, fill = d))

enter image description here

I tried to create a Bar chart with both X and Y axis pre defined.


问:
Prevent Bootstrap Modal if not Validated
How can I prevent the modal from popping up if all of the required fields are not validated?

As you can see, the validation works in the background, but I'm trying to present a summary of the form in the modal and I don't want it to display if it is not filled out correctly.

I would like the modal to just not display and force the user to correct the needed elements.

window.addEventListener('load', function () {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function (form) {
        form.addEventListener('submit', function (event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
        // modalOn();
    });
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
</head>
<body>
<form class="needs-validation" novalidate>
            <div class="mb-3">
                <label for="validationCustom01">Name</label>
                <input type="text" class="form-control" id="validationCustom01" required>
                <div class="invalid-feedback">
                    Please provide your name.
                </div>
            </div>
            <div class="mb-3">
                <label for="validationCustom01">Email</label>
                <input type="email" class="form-control" id="validationCustom01" required>
                <div class="invalid-feedback">
                    Please provide a valid email.
                </div>
            </div>
            <div class="mb-3">
                <label for="validationCustom01">Phone</label>
                <input type="tel" class="form-control" id="phone" pattern="\d{3}-\d{3}-\d{4}" required>
                <div class="invalid-feedback">
                    Please provide a valid phone number.
                </div>
            </div>
            <br>
            <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                Launch demo modal
            </button>
            <!-- <div class="container">
                <div class="row">
                    <div class="col text-center">
                        <button class="btn btn-primary" id="submit-button">Submit form</button>
                    </div>
                </div>
            </div> -->
        </form>
        <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
        integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js"
        integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+"
        crossorigin="anonymous"></script>
</body></code>```

Body:
How can I prevent the modal from popping up if all of the required fields are not validated?

As you can see, the validation works in the background, but I'm trying to present a summary of the form in the modal and I don't want it to display if it is not filled out correctly.

I would like the modal to just not display and force the user to correct the needed elements.

window.addEventListener('load', function () {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function (form) {
        form.addEventListener('submit', function (event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
        // modalOn();
    });
}, false);

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

<form class="needs-validation" novalidate>

                Name
                <input type="text" class="form-control" id="validationCustom01" required>

                    Please provide your name.

                Email
                <input type="email" class="form-control" id="validationCustom01" required>

                    Please provide a valid email.

                Phone
                <input type="tel" class="form-control" id="phone" pattern="\d{3}-\d{3}-\d{4}" required>

                    Please provide a valid phone number.

            <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                Launch demo modal
            </button>

        </form>

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    ...

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save changes</button>


问:
Mock API calls using Mock Service Worker, with environment variables
I am using Mock Service Worker (MSW), in my Vite React app which is working fine when the handler paths were hardcoded and my handler URL matched my fetch URL.

But as the project is progressing, we now have different APIs for development and QA/Staging.

We are using Environment variables for our API URLs, and things are working with fetching the data. But our tests fail when mocking, which I think is caused by the use of environment variables.

Here is an example of one of the endpoints for the API.

```<code>export const USER_URL = `${import.meta.env.VITE_API_URL_USER}/api/v1/userroles`;
</code>```

When we import this, and use this to make a fetch request, everything is working as intended. And confirmed using the Network tab in the browser that the correct URL is being used in development.

Here is the handler, for MSW but the mocked API unit test always seems to fail.

If I hard code the URL for both the handler and fetch, its works fine, but we need the URL in the component to be dynamic, so it uses the correct API endpoint in staging/QA

```<code>  // User Roles
  rest.get(USER_URL, (req, res, ctx) => {
    return res(
      ctx.json([
        {
          firstName: 'Admin',
          lastName: 'Admin',
          fullName: 'Admin Admin',
        }
      ])
    );
  })
</code>```

Here is the unit test that fails, render template is being used, as to avoid having to re-write the providers, which is all written outside the describe function.

```<code>  it('should show the fullname of the user after api data has been loaded', async () => {
    render(renderTemplate);

    const heading = await screen.findByText('Admin Admin');
    expect(heading).toBeInTheDocument();
  });
</code>```

I hardcoded the values initially to make the handler and unit test worked and MSW was set up correctly as I followed the documentation. This was working fine.

I kept a hardcoded path in the handler, and updated the fetch URL to use to dynamic value, and this failed the test.

I am not sure how to proceed with this test and would love to learn how to work with environment variables and testing.

Body:
I am using Mock Service Worker (MSW), in my Vite React app which is working fine when the handler paths were hardcoded and my handler URL matched my fetch URL.

But as the project is progressing, we now have different APIs for development and QA/Staging.

We are using Environment variables for our API URLs, and things are working with fetching the data. But our tests fail when mocking, which I think is caused by the use of environment variables.

Here is an example of one of the endpoints for the API.

export const USER_URL = `${import.meta.env.VITE_API_URL_USER}/api/v1/userroles`;

When we import this, and use this to make a fetch request, everything is working as intended. And confirmed using the Network tab in the browser that the correct URL is being used in development.

Here is the handler, for MSW but the mocked API unit test always seems to fail.

If I hard code the URL for both the handler and fetch, its works fine, but we need the URL in the component to be dynamic, so it uses the correct API endpoint in staging/QA

  // User Roles
  rest.get(USER_URL, (req, res, ctx) => {
    return res(
      ctx.json([
        {
          firstName: 'Admin',
          lastName: 'Admin',
          fullName: 'Admin Admin',
        }
      ])
    );
  })

Here is the unit test that fails, render template is being used, as to avoid having to re-write the providers, which is all written outside the describe function.

  it('should show the fullname of the user after api data has been loaded', async () => {
    render(renderTemplate);

    const heading = await screen.findByText('Admin Admin');
    expect(heading).toBeInTheDocument();
  });

I hardcoded the values initially to make the handler and unit test worked and MSW was set up correctly as I followed the documentation. This was working fine.

I kept a hardcoded path in the handler, and updated the fetch URL to use to dynamic value, and this failed the test.

I am not sure how to proceed with this test and would love to learn how to work with environment variables and testing.


问:
Python logging stops working if getLogger is called more than once for the same logger
I apologize if this was already answered, but it is kind of hard to search for this particular behaviour.

Using the following snippet of code as an example:

```<code>import logging
import logging.config
import yaml

myconfig = '''version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  standard_output:
    class: logging.StreamHandler
    formatter: simple
    stream: ext://sys.stdout
root:
  level: DEBUG
  handlers: [standard_output]
'''

def get_logger(name):
  logging.config.dictConfig(yaml.safe_load(myconfig))
  mylogger = logging.getLogger(name)
  return mylogger

l = get_logger(__name__)
for i in range(0, 10):
  l.error("Test")

def tryme(msg):
  l = get_logger(__name__)
  l.error(msg)

tryme("one")
tryme("two")
</code>```

The loop seems to work just fine and I can see the Test message printed 10 times. But the other two log messages that should be printed via tryme() don't show up. If I change the logger name so something else it works fine as long as I do call it more than once. Why?

I was expecting a new instance of the logger object fully usable.

Body:
I apologize if this was already answered, but it is kind of hard to search for this particular behaviour.

Using the following snippet of code as an example:

import logging
import logging.config
import yaml

myconfig = '''version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  standard_output:
    class: logging.StreamHandler
    formatter: simple
    stream: ext://sys.stdout
root:
  level: DEBUG
  handlers: [standard_output]
'''

def get_logger(name):
  logging.config.dictConfig(yaml.safe_load(myconfig))
  mylogger = logging.getLogger(name)
  return mylogger

l = get_logger(__name__)
for i in range(0, 10):
  l.error("Test")

def tryme(msg):
  l = get_logger(__name__)
  l.error(msg)

tryme("one")
tryme("two")

The loop seems to work just fine and I can see the Test message printed 10 times. But the other two log messages that should be printed via tryme() don't show up. If I change the logger name so something else it works fine as long as I do call it more than once. Why?

I was expecting a new instance of the logger object fully usable.


问:
In Windows 11, is there a way to always show all system tray icons in the taskbar?
In Windows 10, I was able to do this.

In Windows 11, I have to right click the task bar, choose task bar settings, choose Other system tray icons, and manually enable each one (see screenshots below).

The issue is, some applications seem to create new system tray icons and I have to repeat this process.

Is there a way to always display all system tray icons in the taskbar?


问:
Where can i download the the geopandas .whl file?
I am trying to install geopandas library without having to use pip install geopandas (admin constraints).

My work around is to download the binaries and install this way. I can't find the geopandas windows binary, but I've been able to locate the other dependencies.

I am looking on https://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype

Could someone please point me in the right site?


问:
Website Redirect Code Error, how do I fix it?
Can anyone see why this script would fail to redirect?

```<code> $.ajax({
            url: url,
            data: JSON.stringify(viewModel),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            type: "POST",
            success: function (result) {
                if (result.success === true) {
                    showFullScreenLoadMask(false);
                    //var redirect = "/Login/Index";
                    //window.location.href = getUrlPath() + redirect;
                    var redirecturl = getUrlPath() + "/Login/Index";
                     /*F5_*/  F5_Deflate_location( /*_5F##*/ window /*F5_*/ ) /*_5F#.location#*/ .assign = redirecturl;

                } else {

                    // hide any previous errors
                    $("#divPasswordHistoryError").hide();
                    $("#divFullNameError").hide();
                    $("#divCurrentPasswordError").hide();

                    if (result.vm.ShowPreviousPasswordFail === true) {
                        $("#divPasswordHistoryError").show();
                        $("#divPasswordHistoryError").removeClass("hidden");
                    }

                    if (result.vm.ShowFullNameError === true) {
                        $("#divFullNameError").show();
                        $("#divFullNameError").removeClass("hidden");
                    }

                    if (result.vm.ShowCurrentPasswordFail === true) {
                        $("#divCurrentPasswordError").show();
                        $("#divCurrentPasswordError").removeClass("hidden");
                    }

                    $("#Username").val(result.vm.Username);
                    $("#Password").val(result.vm.Password);
                    $("#NewPassword").val("");
                }
            },
            error: function (responseText, textStatus, errorThrown) {
                alert('Error - ' + errorThrown);
            }
        });
</code>```

Above is the code I have on my login script, but for the life of me, I cant get my head around as to why it would not be redirecting to the correct page after someone enters their password.

Body:
Can anyone see why this script would fail to redirect?

 $.ajax({
            url: url,
            data: JSON.stringify(viewModel),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            type: "POST",
            success: function (result) {
                if (result.success === true) {
                    showFullScreenLoadMask(false);
                    //var redirect = "/Login/Index";
                    //window.location.href = getUrlPath() + redirect;
                    var redirecturl = getUrlPath() + "/Login/Index";
                     /*F5_*/  F5_Deflate_location( /*_5F##*/ window /*F5_*/ ) /*_5F#.location#*/ .assign = redirecturl;

                } else {

                    // hide any previous errors
                    $("#divPasswordHistoryError").hide();
                    $("#divFullNameError").hide();
                    $("#divCurrentPasswordError").hide();

                    if (result.vm.ShowPreviousPasswordFail === true) {
                        $("#divPasswordHistoryError").show();
                        $("#divPasswordHistoryError").removeClass("hidden");
                    }

                    if (result.vm.ShowFullNameError === true) {
                        $("#divFullNameError").show();
                        $("#divFullNameError").removeClass("hidden");
                    }

                    if (result.vm.ShowCurrentPasswordFail === true) {
                        $("#divCurrentPasswordError").show();
                        $("#divCurrentPasswordError").removeClass("hidden");
                    }

                    $("#Username").val(result.vm.Username);
                    $("#Password").val(result.vm.Password);
                    $("#NewPassword").val("");
                }
            },
            error: function (responseText, textStatus, errorThrown) {
                alert('Error - ' + errorThrown);
            }
        });

Above is the code I have on my login script, but for the life of me, I cant get my head around as to why it would not be redirecting to the correct page after someone enters their password.


问:
SOAP webservice not providing class methods when using extended classes
Base class

```<code>public class Identity {
    private String a;

    public Identity() { }

    public Identity(String a) {
        this.a = a;
    }

    public String getA() { return a;}

    public void setA() { this.a = a;}
}
</code>```

This is used by userId class

```<code>public class UserId extends Identity {
    private String id;

    public UserId(String id) {
        super(id);
        this.id = id; }

    public String getId() { return id;}

    public void setId(String id) {this.id = id; }
}
</code>```

My webservice method

```<code>    @Override
    public UserId testUserId() {
        final String messageId = "IDString";
        UserId userId = new UserId(messageId);
        return userId;
    }
</code>```

My SOAP client imports the Identity and UserId class.  However, the Identity class has no methods
wsimport -keep -p myclient http://localhost:8080/Uesrs.wsdl

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "identity")
@XmlSeeAlso({
    UserId.class
})
public class Identity {

}
</code>```

When the SOAP client gets the object of type UserId, it only has getID() method and not getA() method.

Can anyone advise how to used extended classes in SOAP?

Body:
Base class

public class Identity {
    private String a;

    public Identity() { }

    public Identity(String a) {
        this.a = a;
    }

    public String getA() { return a;}

    public void setA() { this.a = a;}
}

This is used by userId class

public class UserId extends Identity {
    private String id;

    public UserId(String id) {
        super(id);
        this.id = id; }

    public String getId() { return id;}

    public void setId(String id) {this.id = id; }
}

My webservice method

    @Override
    public UserId testUserId() {
        final String messageId = "IDString";
        UserId userId = new UserId(messageId);
        return userId;
    }

My SOAP client imports the Identity and UserId class.  However, the Identity class has no methods
wsimport -keep -p myclient http://localhost:8080/Uesrs.wsdl

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "identity")
@XmlSeeAlso({
    UserId.class
})
public class Identity {

}

When the SOAP client gets the object of type UserId, it only has getID() method and not getA() method.

Can anyone advise how to used extended classes in SOAP?


问:
How to catch a Python exception from VBA?
I’m using xlwings and calling python from VBA using the RunPython function. However exceptions such as ValueError  are not caught by VBA in the standard way, for example:

```<code>Sub Test()
   On Error Goto PythonError
   RunPython(“…”)
   Exit Sub
PythonEror:
   ‘Do something sensible
End Sub
</code>```

the error gets propagated to Excel nevertheless. What should I do differently to be able to catch and handle the exception from VBA?

Body:
I’m using xlwings and calling python from VBA using the RunPython function. However exceptions such as ValueError  are not caught by VBA in the standard way, for example:

Sub Test()
   On Error Goto PythonError
   RunPython(“…”)
   Exit Sub
PythonEror:
   ‘Do something sensible
End Sub

the error gets propagated to Excel nevertheless. What should I do differently to be able to catch and handle the exception from VBA?


问:
Is it possible to have a multi-endpoint REST API on Google Cloud Functions? (Aws Lambda migration to GCF)
My company has been using AWS Lambda for many years to run our Spring Boot REST API. We are migrating to GCP and they want me to deploy our code to GCF the same way we were with AWS Lambda, but I am not sure that GCF works that way.

According to Google Cloud Functions are only good for Single Endpoints and can only work as a web server using the functions framework.

Spring has a document that uses the GcfJarLauncher, but that is still in alpha and I can only get it to work for a single endpoint. Any additional functions I put into the code are ignored and every endpoint triggers the same function.

There were some posts here on SO that talked about using Functional Beans to map to multiple functions, but I couldn't fully get it working and my boss isn't interested in that.

I've also read of people putting the endpoint in the request payload and then mapping to the proper function, but we are not interested in doing that either.

TLDR/Conclusion:

Is it even possible to deploy our app to GCF or do we need to use Cloud Run (as Google suggests in my first link)?


问:
Unity M2MQTT WEBGL. SocketException: Could not resolve host
I am trying to build a WebGL application that uses m2mqtt to retrieve data on Unity. The application works fine in editor and windows build but this error comes out when I am trying to run it as WebGL.

.

Here's the error that pops out.

I've tried removing firewalls and CORS from my web browsers and its not working. Was wondering if WebGL from Unity does not support these kinds of connections.


问:
Using an Abstract class for mutations in NestJS with dynamic input @Args for the update mutation throws type error
Have been working on adding an abstract class to support versioning for Resolvers for a floorPlan feature and was wondering how I might fix this error. At the moment I do not get any Type errors but when the code compiles NestJs throws this error:

```<code>Undefined type error. Make sure you are providing an explicit type for the "floorPlanUpdate" (parameter at index [2]) of the "BaseResolverHost" class.
</code>```

In a normal resolver this is not a problem as you pass in the type e.g.:

```<code>    @Args('input') input: UpdateFloorPlanV1Input,
</code>```

However as I am trying to determine the input type based off the version of the Floorplan using this line:

```<code>      @Args('input') input: UpdateFloorPlanVersion<FloorPlanVersion>,
</code>```

So it is not possible to explicitly declare it here. Let me know if this is possible or if anyone has any other approaches

This is the abstract Resolver code:

```<code>import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UserId } from 'src/users/decorators/user-id.decorator';
import { CreateFloorPlanInput } from './v1/dto/create-floor-plan.input';
import { UpdateFloorPlanV1Input } from './v1/dto/update-floor-plan.input';
import { FloorPlanV1 } from './v1/models/floor-plan.model';
import { UpdateFloorPlanV2Input } from './v2/dto/update-floor-plan.input';
import { FloorPlanV2 } from './v2/models/floor-plan.model';

export type FloorPlanVersion = FloorPlanV1 | FloorPlanV2;

export type UpdateFloorPlanVersion<T extends FloorPlanVersion> =
  T extends FloorPlanV1 ? UpdateFloorPlanV1Input : UpdateFloorPlanV2Input;

export interface FloorPlanServiceInterface<FloorPlanVersion> {
  create(
    userId: string,
    createFloorPlanInput: CreateFloorPlanInput,
  ): Promise<FloorPlanVersion>;
  findOne(userId: string, floorPlanId: string): Promise<FloorPlanVersion>;
  update(
    userId: string,
    floorPlanId: string,
    input: UpdateFloorPlanV1Input,
  ): Promise<FloorPlanVersion>;
}

export function BaseResolver<T extends Type<FloorPlanVersion>>(
  classRef: T,
  version: string,
) {
  @Resolver({ isAbstract: true })
  abstract class BaseResolverHost {
    floorPlanService: FloorPlanServiceInterface<FloorPlanVersion>;
    constructor(readonly service: FloorPlanServiceInterface<FloorPlanVersion>) {
      this.floorPlanService = service;
    }

    @Mutation(() => classRef, { name: `floorPlanCreate${version}` })
    async floorPlanCreate(
      @UserId() userId,
      @Args('input')
      input: CreateFloorPlanInput,
    ) {
      return this.floorPlanService.create(userId, input);
    }

    @Query(() => classRef, { name: `floorPlan${version}` })
    async floorPlan(@UserId() userId, @Args('id') id: string) {
      return this.floorPlanService.findOne(userId, id);
    }

    @Mutation(() => classRef, { name: `floorPlanUpdate${version}` })
    async floorPlanUpdate(
      @UserId() userId,
      @Args('id') id: string,
      @Args('input') input: UpdateFloorPlanVersion<FloorPlanVersion>,
    ) {
      return this.floorPlanService.update(userId, id, input);
    }
  }
  return BaseResolverHost;
}
</code>```

And then it is called like this:

```<code>@Resolver(() => FloorPlanV2)
export class FloorPlanV2Resolver extends BaseResolver(FloorPlanV2, 'V2') {
  constructor(
    readonly floorPlanService: FloorPlanService,
  ) {
    super(floorPlanService);
  }
}
</code>```

So if the ObjectType was FloorPlanV2 we would expect the UpdateFloorPlanInputType to be UpdateFloorPlanV2Input

Body:
Have been working on adding an abstract class to support versioning for Resolvers for a floorPlan feature and was wondering how I might fix this error. At the moment I do not get any Type errors but when the code compiles NestJs throws this error:

Undefined type error. Make sure you are providing an explicit type for the "floorPlanUpdate" (parameter at index [2]) of the "BaseResolverHost" class.

In a normal resolver this is not a problem as you pass in the type e.g.:

    @Args('input') input: UpdateFloorPlanV1Input,

However as I am trying to determine the input type based off the version of the Floorplan using this line:

      @Args('input') input: UpdateFloorPlanVersion<FloorPlanVersion>,

So it is not possible to explicitly declare it here. Let me know if this is possible or if anyone has any other approaches

This is the abstract Resolver code:

import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UserId } from 'src/users/decorators/user-id.decorator';
import { CreateFloorPlanInput } from './v1/dto/create-floor-plan.input';
import { UpdateFloorPlanV1Input } from './v1/dto/update-floor-plan.input';
import { FloorPlanV1 } from './v1/models/floor-plan.model';
import { UpdateFloorPlanV2Input } from './v2/dto/update-floor-plan.input';
import { FloorPlanV2 } from './v2/models/floor-plan.model';

export type FloorPlanVersion = FloorPlanV1 | FloorPlanV2;

export type UpdateFloorPlanVersion<T extends FloorPlanVersion> =
  T extends FloorPlanV1 ? UpdateFloorPlanV1Input : UpdateFloorPlanV2Input;

export interface FloorPlanServiceInterface<FloorPlanVersion> {
  create(
    userId: string,
    createFloorPlanInput: CreateFloorPlanInput,
  ): Promise<FloorPlanVersion>;
  findOne(userId: string, floorPlanId: string): Promise<FloorPlanVersion>;
  update(
    userId: string,
    floorPlanId: string,
    input: UpdateFloorPlanV1Input,
  ): Promise<FloorPlanVersion>;
}

export function BaseResolver<T extends Type<FloorPlanVersion>>(
  classRef: T,
  version: string,
) {
  @Resolver({ isAbstract: true })
  abstract class BaseResolverHost {
    floorPlanService: FloorPlanServiceInterface<FloorPlanVersion>;
    constructor(readonly service: FloorPlanServiceInterface<FloorPlanVersion>) {
      this.floorPlanService = service;
    }

    @Mutation(() => classRef, { name: `floorPlanCreate${version}` })
    async floorPlanCreate(
      @UserId() userId,
      @Args('input')
      input: CreateFloorPlanInput,
    ) {
      return this.floorPlanService.create(userId, input);
    }

    @Query(() => classRef, { name: `floorPlan${version}` })
    async floorPlan(@UserId() userId, @Args('id') id: string) {
      return this.floorPlanService.findOne(userId, id);
    }

    @Mutation(() => classRef, { name: `floorPlanUpdate${version}` })
    async floorPlanUpdate(
      @UserId() userId,
      @Args('id') id: string,
      @Args('input') input: UpdateFloorPlanVersion<FloorPlanVersion>,
    ) {
      return this.floorPlanService.update(userId, id, input);
    }
  }
  return BaseResolverHost;
}

And then it is called like this:

@Resolver(() => FloorPlanV2)
export class FloorPlanV2Resolver extends BaseResolver(FloorPlanV2, 'V2') {
  constructor(
    readonly floorPlanService: FloorPlanService,
  ) {
    super(floorPlanService);
  }
}

So if the ObjectType was FloorPlanV2 we would expect the UpdateFloorPlanInputType to be UpdateFloorPlanV2Input


问:
Text Field with random quotes changes when text is entered in another text field
So, I'm just trying to learn and I'm trying a fun take on a tip calculator. When typing in any textfield the textfield that's supposed to show a random quote gets updated on every keystroke. I want it just to change after the user picks what percentage of tip to give.

Any suggestions?
`

```<code>//
//  ContentView.swift
//
//

import SwiftUI

struct ContentView: View {

    @State private var textFieldId: String = UUID().uuidString
    @State private var checkAmount = ""
    @State private var numberOfPeople = ""
    @State var tipPercentage = 0
    @State private var randomQuote = ""

    let tipPercentages = [0, 5, 10, 15, 20, 25, 35, 50, 75, 100]
  // doesnt work...
    func insultChooser() -> String {
        if tipPercentage < 15 {

            randomQuote = brokeQuotes.randomElement() ?? "no quote here"

        } else if tipPercentage > 15 && tipPercentage <= 25 {

            randomQuote = NeutralQuotes.randomElement() ?? "no quote here"

        }else {

            randomQuote = RichQuotes.randomElement() ?? "no quote here"
        }

        return randomQuote

    }
    var totalPerPerson: Double {
        //calculate total per person
        let peopleCount = Double(numberOfPeople) ?? 1

        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue
        let amountPerPerson = grandTotal / peopleCount

        return amountPerPerson
    }

    var total: Double {
        let peopleCount = Double(numberOfPeople) ?? 1

        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue

        return grandTotal
    }
    var tipAmount: Double {
        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection

        return tipValue
    }
    var tipSelection: Double {
        let tipSelection = Double(tipPercentages[tipPercentage])
        return tipSelection
    }

    var body: some View {

        NavigationView {
            ZStack {
                Form{
                    Section{
                        TextField("Amount: ", text: $checkAmount)
                            .keyboardType(.decimalPad)

                        TextField("How many people owe you money?", text: $numberOfPeople)
                            .keyboardType(.decimalPad)
                    }
                    Section(header: Text("How much tip do you want to leave")){
                        Picker("Tip Percentage", selection: $tipPercentage) {
                            ForEach(0 ..< tipPercentages.count){
                                Text("\(self.tipPercentages[$0])%")
                            }
                        }
                        Text("$\(tipAmount, specifier: "%.2f")")
                        // Text(self.insultChooser())
                    }
                        Section {
                           if tipPercentage < 15 {

                               Text(brokeQuotes.randomElement() ?? "no quote here")

                            } else if tipPercentage > 15 && tipPercentage <= 25 {

                                Text(NeutralQuotes.randomElement() ?? "no quote here")

                            }else if tipPercentage > 25 {

                                Text(RichQuotes.randomElement() ?? "no quote here")
                            }
                        }
                    Section(header: Text("total")){
                        Text("\(total, specifier: "%.2f")")
                            .foregroundColor(tipPercentages[tipPercentage] < 19 ? Color.red : Color.black)

                    }
                    if numberOfPeople == "" {

                    } else {
                        Section(header: Text("Each Person Should send you: ")){
                            Text("$\(totalPerPerson, specifier: "%.2f")")
                                .foregroundColor(tipPercentages[tipPercentage] < 19 ? Color.red : Color.black)

                        }
                    }

                }
                .navigationTitle("split it.")

            }

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

</code>```

`

In the section for this View I've tried changing the if statement with the tipSelection function but that had the same result, or didn't work altogether.

Body:
So, I'm just trying to learn and I'm trying a fun take on a tip calculator. When typing in any textfield the textfield that's supposed to show a random quote gets updated on every keystroke. I want it just to change after the user picks what percentage of tip to give.

Any suggestions?
`

//
//  ContentView.swift
//
//

import SwiftUI

struct ContentView: View {

    @State private var textFieldId: String = UUID().uuidString
    @State private var checkAmount = ""
    @State private var numberOfPeople = ""
    @State var tipPercentage = 0
    @State private var randomQuote = ""

    let tipPercentages = [0, 5, 10, 15, 20, 25, 35, 50, 75, 100]
  // doesnt work...
    func insultChooser() -> String {
        if tipPercentage < 15 {

            randomQuote = brokeQuotes.randomElement() ?? "no quote here"

        } else if tipPercentage > 15 && tipPercentage <= 25 {

            randomQuote = NeutralQuotes.randomElement() ?? "no quote here"

        }else {

            randomQuote = RichQuotes.randomElement() ?? "no quote here"
        }

        return randomQuote

    }
    var totalPerPerson: Double {
        //calculate total per person
        let peopleCount = Double(numberOfPeople) ?? 1

        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue
        let amountPerPerson = grandTotal / peopleCount

        return amountPerPerson
    }

    var total: Double {
        let peopleCount = Double(numberOfPeople) ?? 1

        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue

        return grandTotal
    }
    var tipAmount: Double {
        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection

        return tipValue
    }
    var tipSelection: Double {
        let tipSelection = Double(tipPercentages[tipPercentage])
        return tipSelection
    }

    var body: some View {

        NavigationView {
            ZStack {
                Form{
                    Section{
                        TextField("Amount: ", text: $checkAmount)
                            .keyboardType(.decimalPad)

                        TextField("How many people owe you money?", text: $numberOfPeople)
                            .keyboardType(.decimalPad)
                    }
                    Section(header: Text("How much tip do you want to leave")){
                        Picker("Tip Percentage", selection: $tipPercentage) {
                            ForEach(0 ..< tipPercentages.count){
                                Text("\(self.tipPercentages[$0])%")
                            }
                        }
                        Text("$\(tipAmount, specifier: "%.2f")")
                        // Text(self.insultChooser())
                    }
                        Section {
                           if tipPercentage < 15 {

                               Text(brokeQuotes.randomElement() ?? "no quote here")

                            } else if tipPercentage > 15 && tipPercentage <= 25 {

                                Text(NeutralQuotes.randomElement() ?? "no quote here")

                            }else if tipPercentage > 25 {

                                Text(RichQuotes.randomElement() ?? "no quote here")
                            }
                        }
                    Section(header: Text("total")){
                        Text("\(total, specifier: "%.2f")")
                            .foregroundColor(tipPercentages[tipPercentage] < 19 ? Color.red : Color.black)

                    }
                    if numberOfPeople == "" {

                    } else {
                        Section(header: Text("Each Person Should send you: ")){
                            Text("$\(totalPerPerson, specifier: "%.2f")")
                                .foregroundColor(tipPercentages[tipPercentage] < 19 ? Color.red : Color.black)

                        }
                    }

                }
                .navigationTitle("split it.")

            }

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

`

In the section for this View I've tried changing the if statement with the tipSelection function but that had the same result, or didn't work altogether.


问:
Can A Google Apps Script Retroactively Set The Google Drive indexableText attribute For Uploaded Files
TLDR: Google Drive does not index markdown files or mime type text/markdown by default. I'm looking for a way to make sure that all files in a specified directory are being indexed by Google Drive.

I have applications on Windows desktop and Android mobile such as Obsidian and Markor that saves markdown document files (.md) to a Google Drive folder with a mime type of text/markdown.

When I attempt to search for terms in the content of the markdown files from the Google Drive website, they do not appear to have been indexed and cannot be found. I can only find terms in the filename of the markdown files.

I can create a text document (.txt) with the same content as the markdown file and they are saved to Google Drive with a mime type of text/plain. The content of these text files are indexed and can be found using search on the Google Drive website.

I came across the following article indicating that there is a way via the Google Drive API/SDK to mark a special Google Drive attribute called indexableText to 'true' for mime types that are not indexed by default by Google Drive.

https://gsuite-developers.googleblog.com/2013/02/how-to-make-files-searchable-in-google.html

It states, "We recently added a way for you to indicate that the file you are uploading is using a readable text format,".

The excerpt indicates that this method is meant to be used as the files are being uploaded.

My question is whether it's possible to set the indexableText attribute to 'true' on existing files or after the files have already been uploaded?

My goal is to have a script that is either triggered by the creation of a new file or that runs at regularly scheduled intervals to make sure that all files in a specified directory are being indexed by Google Drive.

If there are already apps, scripts or services that provide this functionality, I would welcome your recommendations.


问:
How should I set up the auth flow when handling drive files of a user server side?
The gist of it all is that I'm trying to fetch audio metadata from a user's google drive files to store them into firebase.

At first I intended to do this locally, entirely client-sided, because my front-facing web/iOS/Android app is in flutter;

but as it turns out, there's almost no library handling audio metadata properly, and after dabbling with it, I realized I could probably get some formats (say, .wav & most RIFF-type audio files) to work, but doing an entire library to handle all kinds of audio metadata was a task significantly bigger than my original plans. Another option would be to create interfaces between C++ code and/or JS code into my Flutter application, but I'd have almost no control over that, it's not the easiest of process, and there would be possible inconsistencies between platforms.

I might make that library eventually, but in order to facilitate my work, I decided to use a server as a middleman that'd run with node and handle the file requests and metadata treatment, & also facilitate the interactions with firebase for me by making them handled by a service account.

Now, this makes me run into one issue : how to handle the google Auth.

When my user logs into my app, I get all the required auth scopes (google drive files access and write, contacts, email, etc) for my app; it goes through the consent screen and I get authenticated.

I'm still a little confused with the recommendations from google and best practices in this case, since my app, in itself, did not require an auth system outside of getting access to the google drive files through google identification, and I therefore do not have Firebase/Firestore users; I can simply store them in my (firestore) database for identification purposes (or maybe tie in the frontend flow to my firestore app to also create a user when logging in through google if that is possible. I'm currently using the google sign in
flutter package.)

To come back to my actual problem now that the situation is laid out :

Should I just transfer the auth tokens (and maybe reverify them in some ways to avoid impersonation) from my frontend app to the server through a HTTPS post request or through headers, and use them to directly query the Google Drive API (I wouldn't even need to store them outside of memory, which would be relatively safe against any attacks on the server itself), handle the files and the possibly expired token ?

Should I modify my frontend workflow so it directly grants access to my server who would handle the session rather than getting the tokens locally ?

In the first case, I would most likely simply use the users UID as identifiers for the firestore data (none of it is sensitive anyway, it would simply be playlists and some metadata). In the second case, I could probably implement a stronger security on firestore using the firestore rules,but it'd require a significant amount of refactoring and logic changes in my frontend.

In case that wasn't clear, I wish my server to make all the Drive related requests (after getting the proper authorizations from the user of course) and handle these without having to request the files locally in frontend. Both solutions (and others if available) should work, but I'm wondering what the best practice would be in the context of the Oauth2 system used by google and the fact that the authorization is transitioning between client and server and could be subject to security issues.

I'll add code/visual representations if this isn't clear enough. It is to me, but I obviously designed the mess.


问:
MS Sentinel KQL - Unable to perform string match on decoded base 64 data
Unable to perform string matching on decoded base64 data in MS Sentinel SIEM using KQL search. I am running a MS Sentinel KQL search published at the link below.

For example, when modifying the original query by adding the the statement

*"| where DecodedCommand contains "some text present in DecodedCommand data" *

I would expect a match but no results are returned. I've confirmed that the statement is valid by performing a string match on data in another column. The problem is only for the decoded base 64 data.

Original query (link below):

```<code>DeviceProcessEvents
| where ProcessCommandLine contains "powershell" or InitiatingProcessCommandLine contains "powershell"
| where ProcessCommandLine contains "-enc"
    or ProcessCommandLine contains "-encodedcommand"
    or InitiatingProcessCommandLine contains "-enc"
    or InitiatingProcessCommandLine contains "-encodedcommand"
//Extract encoded command using regex
//This query will only return results when the command can be matched via regex and decoded, if you run only the above lines it will return all encoded commands without attempting to match and decode
| extend EncodedCommand = extract(@'\s+([A-Za-z0-9+/]{20}\S+$)', 1, ProcessCommandLine)
| where EncodedCommand != ""
| extend DecodedCommand = base64_decode_tostring(EncodedCommand)
| where DecodedCommand != ""
| project
    TimeGenerated,
    DeviceName,
    InitiatingProcessAccountName,
    InitiatingProcessCommandLine,
    ProcessCommandLine,
    EncodedCommand,
    DecodedCommand
</code>```

Modified query:

```<code>DeviceProcessEvents
| where ProcessCommandLine contains "powershell" or InitiatingProcessCommandLine contains "powershell"
| where ProcessCommandLine contains "-enc"
    or ProcessCommandLine contains "-encodedcommand"
    or InitiatingProcessCommandLine contains "-enc"
    or InitiatingProcessCommandLine contains "-encodedcommand"
//Extract encoded command using regex
//This query will only return results when the command can be matched via regex and decoded, if you run only the above lines it will return all encoded commands without attempting to match and decode
| extend EncodedCommand = extract(@'\s+([A-Za-z0-9+/]{20}\S+$)', 1, ProcessCommandLine)
| where EncodedCommand != ""
| extend DecodedCommand = base64_decode_tostring(EncodedCommand)
| where DecodedCommand != ""
| where DecodedCommand contains "add some text here"
| project
    TimeGenerated,
    DeviceName,
    InitiatingProcessAccountName,
    InitiatingProcessCommandLine,
    ProcessCommandLine,
    EncodedCommand,
    DecodedCommand
</code>```

Link:
https://github.com/reprise99/Sentinel-Queries/blob/main/Defender%20for%20Endpoint/Device-DetectEncodedPowershellandDecode.kql

I have tried various string matching techniques on the DecodedCommand values such as using regex and queries to a lookup list (e.g., adding statements "| let str_to_match=dynamic(['some string to match']) and | where DecodedCommand has_any(str_to_match) to the original query).

Body:
Unable to perform string matching on decoded base64 data in MS Sentinel SIEM using KQL search. I am running a MS Sentinel KQL search published at the link below.

For example, when modifying the original query by adding the the statement

*"| where DecodedCommand contains "some text present in DecodedCommand data" *

I would expect a match but no results are returned. I've confirmed that the statement is valid by performing a string match on data in another column. The problem is only for the decoded base 64 data.

Original query (link below):

DeviceProcessEvents
| where ProcessCommandLine contains "powershell" or InitiatingProcessCommandLine contains "powershell"
| where ProcessCommandLine contains "-enc"
    or ProcessCommandLine contains "-encodedcommand"
    or InitiatingProcessCommandLine contains "-enc"
    or InitiatingProcessCommandLine contains "-encodedcommand"
//Extract encoded command using regex
//This query will only return results when the command can be matched via regex and decoded, if you run only the above lines it will return all encoded commands without attempting to match and decode
| extend EncodedCommand = extract(@'\s+([A-Za-z0-9+/]{20}\S+$)', 1, ProcessCommandLine)
| where EncodedCommand != ""
| extend DecodedCommand = base64_decode_tostring(EncodedCommand)
| where DecodedCommand != ""
| project
    TimeGenerated,
    DeviceName,
    InitiatingProcessAccountName,
    InitiatingProcessCommandLine,
    ProcessCommandLine,
    EncodedCommand,
    DecodedCommand

Modified query:

DeviceProcessEvents
| where ProcessCommandLine contains "powershell" or InitiatingProcessCommandLine contains "powershell"
| where ProcessCommandLine contains "-enc"
    or ProcessCommandLine contains "-encodedcommand"
    or InitiatingProcessCommandLine contains "-enc"
    or InitiatingProcessCommandLine contains "-encodedcommand"
//Extract encoded command using regex
//This query will only return results when the command can be matched via regex and decoded, if you run only the above lines it will return all encoded commands without attempting to match and decode
| extend EncodedCommand = extract(@'\s+([A-Za-z0-9+/]{20}\S+$)', 1, ProcessCommandLine)
| where EncodedCommand != ""
| extend DecodedCommand = base64_decode_tostring(EncodedCommand)
| where DecodedCommand != ""
| where DecodedCommand contains "add some text here"
| project
    TimeGenerated,
    DeviceName,
    InitiatingProcessAccountName,
    InitiatingProcessCommandLine,
    ProcessCommandLine,
    EncodedCommand,
    DecodedCommand

Link:
https://github.com/reprise99/Sentinel-Queries/blob/main/Defender%20for%20Endpoint/Device-DetectEncodedPowershellandDecode.kql

I have tried various string matching techniques on the DecodedCommand values such as using regex and queries to a lookup list (e.g., adding statements "| let str_to_match=dynamic(['some string to match']) and | where DecodedCommand has_any(str_to_match) to the original query).


问:
Angular/Typescript Export Table to Excel with Pagination (Multiple Pages)
I have a table with 15 rows per page as per my PaginationConfig. When I try to export to excel using the XLSX npm package, the file that gets generated only shows the first 15 rows (1 page) instead of all pages that are located in the table.

```<code>public paginationConfig: PaginationInstance = {
    id: 'table-pagination',
    itemsPerPage: 15,
    currentPage: 0,
  };
</code>```
```<code>@ViewChild('table') table!: ElementRef;
  title = 'Excel';
  exportTableData() {

    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.table.nativeElement);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'ScrapData');
    XLSX.writeFile(wb, 'ScrapData.xlsx');
 }
</code>```

These are the functions I use for my paginationConfig and the export to an excel sheet. This generates and exports an excel spreadsheet with 15 rows/ 1 page

UPDATE: Upon further research, the only way I was able to get this working was to have 2 tables in my html component. A 2nd hidden tabled held every row without pagination and exporting that table to excel gave me the results I wanted.

Body:
I have a table with 15 rows per page as per my PaginationConfig. When I try to export to excel using the XLSX npm package, the file that gets generated only shows the first 15 rows (1 page) instead of all pages that are located in the table.

public paginationConfig: PaginationInstance = {
    id: 'table-pagination',
    itemsPerPage: 15,
    currentPage: 0,
  };

@ViewChild('table') table!: ElementRef;
  title = 'Excel';
  exportTableData() {

    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.table.nativeElement);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'ScrapData');
    XLSX.writeFile(wb, 'ScrapData.xlsx');
 }

These are the functions I use for my paginationConfig and the export to an excel sheet. This generates and exports an excel spreadsheet with 15 rows/ 1 page

UPDATE: Upon further research, the only way I was able to get this working was to have 2 tables in my html component. A 2nd hidden tabled held every row without pagination and exporting that table to excel gave me the results I wanted.


问:
Angular component not showing template
I downloaded angular form https://angular.io/quick-start and then added a file to the app folder "tutoriel.component.ts" and wrote the following code

```<code>import { Component } from "@angular/core";
@Component({
    selector: 'tutoriel',
    template: '<h2>Tutoriel</h2>'
})
export class TutorielComp{

}
</code>```

and then changed this in the app.module

```<code>@NgModule({
  declarations: [
    AppComponent,
    TutorielComp
  ],
</code>```

and the class got imported import { TutorielComp } from './tutoriel.component'; The problem is when I deleted all the code in the app.component.html and wrote

```<code><tutoriel></tutoriel>
</code>```

It did not show.

Title: Angular component not showing template

Body:
I downloaded angular form https://angular.io/quick-start and then added a file to the app folder "tutoriel.component.ts" and wrote the following code

import { Component } from "@angular/core";
@Component({
    selector: 'tutoriel',
    template: '
Tutoriel
'
})
export class TutorielComp{

}

and then changed this in the app.module

@NgModule({
  declarations: [
    AppComponent,
    TutorielComp
  ],

and the class got imported import { TutorielComp } from './tutoriel.component'; The problem is when I deleted all the code in the app.component.html and wrote

<tutoriel></tutoriel>

It did not show.


问:
How to know which resources I am using in Oracle Cloud, after I deleted the instance?
I had created one instance in Oracle cloud with AMPERE CPU, 4 cores & 24 GB RAM. It aloowed me to do so as it is within Always Free Tier. I had to delete that as it was not working OK. While deleting, I have also chosen "Delete boot volume". Now when I want to make another instance with same cpu, after three cores it is giving message of "Service Limits reached". Why this is happenning and how do I overcome it?

I waited for 48 hours so that all resources are released. On my dashboard it shows that "No resources found. Create a resource, or try another compartment." However, it does not allow me beyong 3 cores.

Regards.
Dutta


问:
Check to see if coordinates fall inside/outside of a shapefile polygon in Python
I am working with shapefiles and DataFrames that contain longitude and latitude coordinates. What I want to do is see if the coordinates within the DataFrames fall outside of the shapefile polygons and select those to a new DataFrame. I converted the DataFrame latitude and longitude column values into Point values using shapely first and then converted the shapefile latitude and longitude values into a Polygon using shapely (I had earlier in my code had to convert the shapely file coordinates into separate DataFrame columns for latitude and longitude). Here's some of the code I'm working with:

```<code>point_coords['geometry'] = [Point(xy) for xy in zip(point_coords.lon, point_coords.lat)] #converting the latitude and longitude coordinates into points
point_geom = point_coords['geometry']
point_geom = pd.DataFrame(point_geom)

shape_coords = coords[['lat','lon']]
shape_coords = shape_coords.values.tolist()
poly = Polygon(shape_coords)

coord_contain = poly.contains(point_geom)
</code>```

I tried using the contians method from shapely but that didn't work, giving the following error: AttributeError: 'DataFrame' object has no attribute '_geom'.

What is the best possible method to determine which point_geom coordinates fall inside/outside of the poly?

Body:
I am working with shapefiles and DataFrames that contain longitude and latitude coordinates. What I want to do is see if the coordinates within the DataFrames fall outside of the shapefile polygons and select those to a new DataFrame. I converted the DataFrame latitude and longitude column values into Point values using shapely first and then converted the shapefile latitude and longitude values into a Polygon using shapely (I had earlier in my code had to convert the shapely file coordinates into separate DataFrame columns for latitude and longitude). Here's some of the code I'm working with:

point_coords['geometry'] = [Point(xy) for xy in zip(point_coords.lon, point_coords.lat)] #converting the latitude and longitude coordinates into points
point_geom = point_coords['geometry']
point_geom = pd.DataFrame(point_geom)

shape_coords = coords[['lat','lon']]
shape_coords = shape_coords.values.tolist()
poly = Polygon(shape_coords)

coord_contain = poly.contains(point_geom)

I tried using the contians method from shapely but that didn't work, giving the following error: AttributeError: 'DataFrame' object has no attribute '_geom'.

What is the best possible method to determine which point_geom coordinates fall inside/outside of the poly?


问:
How to cut/sampling by csv filesize on pyspark
I am df is pyspark dataframe, I need to cut by size on production environment data, for example 100 MB

Here's the script I usualy use (for not cutting scenario)

df.coalesce(1).write.csv(output_path+"/folder_name", header=True, mode='overwrite')

How to cut some initial row (for example 100 MB)

I use .limit(10000) when I create df when I want to minimize file, what I need is to investigate how big file my infra can save, because cutting dataframe is still sampling and I want as much as sample possible