satoshi-2000/llms-suitable huggingface dataset:
Question: Google.Apis.Oauth2.v2 + UWP: Access to path c:\users is denied

After updating Google.Apis.Oauth2.v2 NuGet package to v. 1.60.0.1869, I start getting exception Access to the path C:\Users is denied when trying login with Google in my UWP app. Here's my code:
string fname = @"Assets\User\Auth\google_client_secrets.json";
StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var stream = await InstallationFolder.OpenStreamForReadAsync(fname);
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
    stream,
    new[] { "profile", "email" },
    "me",
    CancellationToken.None);

The exception occurs in GoogleWebAuthorizationBroker.AuthorizeAsync call.
This code (with some light changes) worked well before with Google.Apis.Oauth2.v2 package v. 1.25.0.859, but now this package is obsolete and doesn't work anymore.
How to login with Google in my UWP app?
NOTE: I understand that UWP app doesn't have access to c:\Users, but my code never request anything in the folder. google_client_secrets.json exists and I can read it in the app from the stream, so this file is unrelated to the issue.
UPDATE
After I set the 5th parameter of AuthorizeAsync like this:
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
    stream,
    new[] { "profile", "email" },
    "me",
    CancellationToken.None
    new FileDataStore(ApplicationData.Current.LocalCacheFolder.Path, true));

the exception is gone. Now the execution thread just dies inside the AuthorizeAsync and I start getting the following error popup:



Answer:
After some tried, I failed to make Google.Apis.Oauth2.v2 NuGet package v. 1.60.0.1869 to work with UWP. I made Google Login works by removing the NuGet and implementing OAuth flow myself as described in my answer here.
Question: mat-select panel still shows overlapped like version 14 and below even after upgrade to angular material 15

we have used mat-select in our project, the panel shows overlapping on the trigger text like version 14 and before (material version 12 was used in our project)

after finding few hacks, the panel showed below the trigger text, but it was not consistent with different screen sizes, specially the mobile view.
We found that from material version 15, the select panel showed below the trigger text - 
so we upgraded to material version 15, and also upgraded the angular version to 15. But even after the upgrade the mat-select is still showing in the previous style.
Can someone please suggest what could be going wrong here and what needs to be done to get working like material version 15 mat-select


Answer:
Based on the comments, you have only updated to Angular material 15, but is running in legacy mode.
To fully migrate you need to run.
schematic: ng generate @angular/material:mdc-migration
however due to class name changes to the mdc- prefix etc and structual changes in some of the componets. you should follow their migration guide.
https://rc.material.angular.io/guide/mdc-migration
Question: ASP.NET Core 7.0 container: Failed to create CoreCLR, HRESULT: 0x8007000E

That's a result when I receive after trying to run ASP.NET Core 7.0 runtime image in Amazon ECS container (AWS Fargate service).
My project in on ASP.NET Core 7.0 Web API.
Here is a docker file for image which built on Jenkins and sent to Amazon ECS
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["src/MetaGame/MyMetaGame.API/MyMetaGame.API.csproj", "src/MetaGame/MyMetaGame.API/"]
RUN dotnet restore "src/MetaGame/MyMetaGame.API/MyMetaGame.API.csproj"
COPY . .
WORKDIR "/src/src/MetaGame/MyMetaGame.API"
RUN dotnet build "MyMetaGame.API.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyMetaGame.API.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyMetaGame.API.dll"] 

After some googling I've found a decision to increase GC Heap limit by environment parameter. I set it to 512Mb
DOTNET_GCHeapHardLimit=20000000

But it hasn't fixed my problem.
No idea what's the problem
Here is the configuration of csproj file
<PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>



Answer:
So, the problem is fixed by adding
ENV COMPlus_EnableDiagnostics=0

in the final stage of Dockerfile.
So, it should looks like
FROM base AS final
ENV COMPlus_EnableDiagnostics=0
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyMetaGame.API.dll"]

Found the solution here
Question: How to make sure that my virtual machine does not change its IP address when connecting to different networks?

I have two virtual machines. First has apache server, and wordpress on virtualhost. Second has mysql server for my wordpress in first vm. Mysql configuration use ip adress of first vm. But when i leave my home and in result leave my home wi-fi, ip adress of first vm is changing when i connect to internet from my phone and my web-site crashes.


Answer:
It is said that by default IP addresses are assigned dynamically, so the IP changes if you are in different network (that is, when you access the Internet through mobile data instead of home wifi). You may assign static IP address to your VM. This is done from inside of your VM.
Question: How can I change the size of the text in TextComponent using Flutter Flame?

How do you change the size of the text in the TextComponent in Flame?  I want to make the text larger
I used the Flame documentation to get this, but I don't know how to modify it for a larger text size (like 20pt vs 14pt).  Also, what is the anchor?
final style = TextStyle(color: BasicPalette.darkBlue.color);
final regular = TextPaint(style: style);

TextComponent startText = TextComponent(text: 'test text', textRenderer: regular)
  ..anchor = Anchor.topCenter
  ..x = (width * 0.2)
  ..y = (height - (height*0.5))
  ..priority = 300;



Answer:
final style = TextStyle(
  color: BasicPalette.darkBlue.color,
  fontSize: 20.0, // Change the font size here
);
final regular = TextPaint(style: style);

TextComponent startText = TextComponent(
  text: 'test text',
  textRenderer: regular,
)
  ..anchor = Anchor.topCenter
  ..x = (width * 0.2)
  ..y = (height - (height * 0.5))
  ..priority = 300;

What's anchor?
The anchor in Flame's TextComponent determines where the text is positioned relative to its given coordinates (x and y). You can choose from options like top-left, top-center, top-right, center-left, center, center-right, bottom-left, bottom-center, and bottom-right to align the text as you want. Adjust the anchor and position values to position the text as needed.
Question: How to clear cache for a route with the 'apicache' package

I'm using NPM install API cache for my MERN application. I want one of my requests to be cached and then when a request is made to another route it refreshes the cache (it fetches the new data). I've managed to get one of my requests to be cached but I can't manage to clear it.
This is my code
const apicache = require("apicache")

let cache = apicache.middleware

app.get("/api/users/checkJWT",cache("2 minutes"), async (req,res) => {
  const token = req.headers.authorization?.split(" ")[1]

  const decoded = jwt.verify(token,SECRET_KEY)

  if(decoded != null && await User.findById(decoded.id) != null) {
    return res.status(200).json({valid: true, user: await User.findById(decoded.id)})
  }
  else {
    return res.status(400).json({valid: false})
  }
})

app.patch("/api/users/user",authenticateJWTUser, async (req, res) => {
  apicache.clear('/api/users/checkJWT')
  const user = await User.findOne({ name: req.body.username });
  if (req.body.name != null) {
    user.name = req.body.name;
  }
  if (req.body.email != null) {
    user.email = req.body.email;
  }
  if (req.body.password != null) {
    user.password = await bcrypt.hash(req.body.password, 10);
  }
  if (req.body.tasks != null) {
    user.tasks = req.body.tasks;
  }
  try {
    const updatedUser = await user.save();
    res.json(updatedUser);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

Link to my Git repo: https://github.com/JesseOgunlaja/Task-Tracker-MERN/tree/ae1b0027bfa40f90ab7a3d6208c05a9eb41a4478


Answer:
I was able to get this work using the apicache-plus package.
const apicache = require("apicache-plus");

router.get(
  "/api/users/getName/1",
  apicache.middleware("10 minutes"),
  async (req, res, next) => {
    req.apicacheGroup = "toClear";
    const someData = { someName: "Amy" };
    res.json(someData);
  }
);

router.get("/api/users/user/1/2", async (req, res, next) => {
  console.log("something");
  apicache.clear("toClear");

  const user = { name: "Jeff" };
  res.json(user);
});
Question: Razor page redirect to another folder page

I'm facing an issue with razor page navigation. I'm in the https://localhost:7154/Application/setupAccount page and i have to redirect to https://localhost:7154/Loan/setupLoan page.
So I used RedirectToPage("setupLoan", new{id=123}. but the issue is that it's looking like a setupLoan page inside the Application folder. ( URL - https://localhost:7154/Application/setupLoan )
Then I'm getting an error like page not found
I can use redirect functionality. But the thing is, I can't send dynamic query parameters.
So let me know if anyone know a correct path to navigate razor page into another folder


Answer:
Try:
   return RedirectToPage("setupLoan", new { area = "Application",id=1 }); 

result:

You can read Areas with Razor Pages to know more.
Update
 return RedirectToPage("setupLoan", new { area = "Loan",id=1 }); 

Update 2
Loan is a page folder. not area folder ,
try:
  return RedirectToPage("/Loan/setupLoan", new { id = 1 });
Question: Is there a way to stop old observable and set new after event in Nest Gateways?

I'm developing a simple message server app, using WebSockets and NestJs gateways. Server receives an event to indentify a listener with name, and then sends websocket updates to that listener.
Right now I'm using subject/observable approach, server after listen-as event returns a new observable, which filters all upcoming messages:
export class ListenAsDto {
  name: string;
}

export interface PersonalisedMessage {
  from: string;
  title: string;
  content: string;
}

export class MessagesService {
  // ...
  listenAs(listener: ListenAsDto): Observable<WsResponse<PersonalisedMessage>> {
    return this.messageObservable.pipe(
      filter((item) => item.to === listener.name),
      map((item) => {
        const copy = { ...item };
        delete copy.to;
        return { event: INBOX_MESSAGE_NAME, data: copy };
      }),
    );
  }
}

But this only works for the first time, after another request client now receives both updates from 2 users at the time.
Is there a way to stop previous observable for current user an start new?
EDIT: I'm using ws platform


Answer:
Found a solution by using a native WebSocket instance. It passes the same object if request was made by same client. So, using a WeakMap, we can manually track all subscriptions objects, and unsubscribe them, if we get the same WebSocket client
export class MessagesService {
  private subs = new WeakMap<WebSocket, Subscription>();

  listenAs(ip: WebSocket, dto: ListenAsDto) {
    if (this.subs.has(ip)) this.subs.get(ip).unsubscribe();
    // 'createObservable' is basically question`s 'listenAs' function
    const obs = this.createObservable(dto);
    this.subs.set(
      ip,
      obs.subscribe({
        next(value) {
          ip.send(JSON.stringify(value));
        },
      }),
    );

    return dto;
  }
}
Question: How to start Jupyter Notebook on a GCP VM with predefined token automatically on VM start?

OK I have set up jupyter notebook on a gcp VM, I want it to start automatically every time VM is started with a predefined token. (OS in Centos)
Does any one have any idea how to solve this final issue so that we can get the jupyter notebook started under the user test1 , everytime the VM starts ?
Here is what I have done so far

Created a local test1 user and created a Virtual env for it, installed jupyter notebook inside the virtual env for isolation of python

pyton3 -m venv tvenv
source tvenv\bin\activate
pip install jupyter


Understood that I would need to generate config and update token / ip / port etc inside the config becuase dynamically generated token cannot be used

jupyter notebook --generate-config 


modified NotebookApp.token/NotebookApp.port/NotebookApp.ip etc attributes to get that to work.
based on an existing question created a shell script to be added to the start up to the gcp VM

sudo -u test1 bash -c 'cd ~/; nohup tvenv/bin/jupyter-notebook &'

When i run the command manually from root it works when I update in GCP startup it constantly fails saying
Account or password is expired, reset your password and try again

Note : Helpful debugging tip. You can get the startup script logs by running below command once inside the VM
sudo journalctl -u google-startup-scripts.service



Answer:
As John has already pointed out to you in the comment, sudo is not a good option, since the Startup scripts run as root, su can be used to switch to another profile.
Few other things that you should be aware of is that as you are using virtual enviornment, you have to set up similar enviornment variables as 'activate'
does.
one possible solution that you can try is below
 su -c 'PATH="/home/test1/tvenv/bin:$PATH";export PATH; cd ~/; nohup tvenv/bin/jupyter-notebook &' -s /bin/sh test1

What it does is sets the path to the virtual enviornment ( activity that is done via the activate among other tasks ) moves to home directory of the user and runs the notebook in background with test1 user profile.
I would also suggest that you use shutdown script in the gcp vm to shutdown notebook gracefully, make sure that you replace the port with the port that you are using in your config
jupyter notebook stop 8888

Similar to start up you can check the shutdown logs by using the command below
sudo journalctl -u google-shutdown-scripts.service

Let me know if you still face any issues.
Question: How do I remove deleted Python environments in PyCharm?

When I'm creating a new project in PyCharm, I can see some environments I created for old projects that have been deleted:

but I can't find a way to delete these entries. Where are they? How do I delete them?
I tried going to "Python Interpreters" following https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html#removing_interpreter but they are just not there:




Answer:
The Interpreters list from the New Project dialogue has a different entry point from the project specific list. Go to File > New Projects Setup > Settings for New Projects (instead of going to File > Settings as usual):

Going through the other entry point you can already notice the Python Interpreter item in the sidebar is slightly different visually from if you had gone the other route. From there on the renaming dialogues are the same as usual but the lists are different. Continue to Python Interpreter > Show All... at the bottom of the drop down list:
Question: How to remove 3 dots after end of line limit

In SwiftUI,
Text("a \n b \n c \n d \n e")
     .lineLimit(3)

In SwiftUI, the above code shows output including 3 dots in the end.
Output:
a
b
c...

But my target is to show the output without dots like this -
Target:
a
b
c



Answer:
implement the following way.
Text("1\n 2 \n 3 \n 4 \n 5".truncateToLineLimit(3))

extension String {
    func truncateToLineLimit(_ lineLimit: Int) -> String {
        var truncatedString = ""
        let lines = self.components(separatedBy: "\n").prefix(lineLimit)
        for line in lines {
            truncatedString += line.trimmingCharacters(in: .whitespacesAndNewlines)
            if line != lines.last {
                truncatedString += "\n"
            }
        }
        return truncatedString
    }
}
Question: How to remove gap between a frame and its scrollbar?

I have three frames; left_frame, middle_frame and right_frame. I would like to have no gap between left_frame and its scrollbar. How can I achieve it?
import tkinter as tk
from tkinter import ttk

def create_dummy_chart(frame, index):
    # Create a dummy chart
    label = tk.Label(frame, text=f"Chart {index}", width=10, height=2, relief="solid")
    label.pack(side="top", pady=5)

# Create the main window
window = tk.Tk()
window.title("Chart Display")
window.geometry("800x300")

# Create the left frame
left_frame = tk.Frame(window, width=200, height=300, relief="solid", bd=1)
left_frame.pack(side="left", fill="y")

# Create a canvas to hold the left_frame and the scrollbar
canvas = tk.Canvas(left_frame, width=200, height=300)
canvas.pack(side="left", fill="y")

# Create the scrollbar
scrollbar = ttk.Scrollbar(left_frame, orient="vertical", command=canvas.yview)
scrollbar.pack(side="right", fill="y")

# Configure the canvas to use the scrollbar
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

# Create a frame inside the canvas to hold the charts
chart_frame = tk.Frame(canvas)

# Add the frame to the canvas
canvas.create_window((0, 0), window=chart_frame, anchor="nw")

# Create dummy charts in the chart_frame
num_charts = 200
for i in range(num_charts):
    create_dummy_chart(chart_frame, i)

# Update the canvas scrollable area
chart_frame.update_idletasks()
canvas.configure(scrollregion=canvas.bbox("all"))

# Create the middle frame
middle_frame = tk.Frame(window, width=200, height=300, relief="solid", bd=1)
middle_frame.pack(side="left", fill="y")

# Create the right frame
right_frame = tk.Frame(window, width=400, height=300, relief="solid", bd=1)
right_frame.pack(side="left", fill="both", expand=True)

# Run the Tkinter event loop
window.mainloop()


I have left_frame and vertical scrollabr. But, I ended up having a gap between them. I expect to have no gap between them. How can I achieve this?
What I have:

What I expect:



Answer:
If you're referring to the one or two pixel space between the canvas and the scrollbar, you can set the highlightthickness attribute of the canvas to zero, or you can set the highlightcolor to the same color as the background of the canvas so that the highlight ring is not visible when the canvas has the keyboard focus.
You might also need to explicitly set the padx value to zero when packing the canvas and scrollbar. On some platforms it might default to 1.
If you're referring to the fact that the canvas is wider than the items in the canvas, then you can set up a binding to set the width of the canvas to always match the width of the items on the canvas.
You can do that like this:
chart_frame.bind("<Configure>", lambda event: canvas.configure(width=chart_frame.winfo_width()))
Question: What is the point of the ILoggingBuilder interface in ASP.NET Core?

I looked inside the the built in WebApplicationBuilder class and noticed the
public ILoggingBuilder Logging { get; }

property. Here is the entire ILoggingBuilder interface:
public interface ILoggingBuilder
{
    IServiceCollection Services { get; }
}

It just stores a single property so what is the point of this interface? Couldn't the WebApplicationBuilder just store an instance of IServiceCollection directly?


Answer:
It's about scoping and reducing intellisense hell. If everything was on IServiceCollection it would get cluttered quickly. Subsystems that are highly configurable and are themselves extensible need a "target" to extend. This is one of the patterns the platform employs to solve this problem.
Some of the patterns you'll see:
Simple options via a callback:
services.AddComponent((ComponentOptions options) => 
{
    options.SomeFlag = true;
});

This pattern works well when the number of options on component is small, self-contained and has limited extensibility.
Complex builder returned from the API:
IComponentBuilder builder = services.AddComponent();

builder.AddExtensibleThing1();
builder.AddExtensibleThing2();

Breaks the fluent API pattern but reduces nested lambdas.
OR
services.AddComponent((IComponentBuilder builder) =>
{
    builder.AddExtensibleThing1();
    builder.AddExtensibleThing2();
});

Similar to the above but nested instead of a return value. Keeps the fluent API working at the cost of more callbacks.
Question: How to seach text not translate in VSCode?

I'm added i18next React for old project. So many text not can be translate. How can I search all of them in VSCode?
Some case:
<Button className="w-full" onClick={onClick}>
  Save
<Button>

<Button
  type="primary"
  onClick={onCLick}
  className="ml-2"
>
  Save
</Button>

<Button>Save</Button>

<ContentWrapper title="Connection" headerAction={<Button size="small">Add</Button>}>
  <div>{`Connection`}</div>
</ContentWrapper>

<p className="mt-2 text-center">
  Drag and drop files here or <span className="text-blue-500">{t('browse')}</span>
</p>

<div>
  {mediaRecorder?.state === 'recording' ? (
    <Button onClick={handleStop}>{t('Stop')}</Button>
  ) : (
    <Button onClick={handleStart}>Start</Button>
  )}
</div>

Translated:
<Button>{t('Save')}</Button>

<ContentWrapper title="Connection" headerAction={<Button size="small">{t('Add')}</Button>}>
      <div>{t('Connection')}</div>
    </ContentWrapper>



Answer:
Find:
(<Button[\s\S\n]*?>[\n\s]*)(\w+)([\n\s]*</Button>)

Replace:
$1{t('$2')}$3