satoshi-2000/llms-suitable huggingface dataset:
Question: Authentication between Azure Web PubSub and server

There is a simple ASP.NET app as an event handler Server:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddWebPubSub(options => options.ServiceEndpoint = new ServiceEndpoint(WebPubSubConnectionString))
    .AddWebPubSubServiceClient<WebPubSubHub>();

WebApplication app = builder.Build();

app.MapWebPubSubHub<WebPubSubHub>("/eventhandler");
app.Run();

The Azure Web PubSub has the following configuration of Webhook URL:

I need to protect this endpoint somehow /eventhandler because it's public and anyone can call it. One of the options that Azure suggests is using a simple authentication code.

Help me to understand where I should verify that code in my ASP.NET app?
Let's say I configured the URL template in WPS like
https://a9e5-92-253-212-316.ngrok-free.app/eventhandler?code=RRRRR

then in the server code
app.MapWebPubSubHub<WebPubSubHub>("/eventhandler?code=RRRRR")

result is exception

Microsoft.AspNetCore.Routing.Patterns.RoutePatternException: 'The
literal section 'eventhandler?code=RRRRR' is invalid. Literal sections
cannot contain the '?' character.'



Answer:
One possible way is to use AddEndpointFilter
app.MapWebPubSubHub<WebPubSubHub>("/eventhandler").AddEndpointFilter(new ApiKeyFilter(builder.Configuration));

the implementation could look like this:
public class ApiKeyFilter : IEndpointFilter
{
    private readonly string _apiKey;

    public ApiKeyFilter(IConfiguration configuration)
    {
        _apiKey = configuration.GetValue<string>("ApiKey");
    }

    public async ValueTask<object> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        if (!context.HttpContext.Request.Query.TryGetValue("code", out var extractedApiKey))
        {
            return Results.Unauthorized();
        }

        if (!_apiKey.Equals(extractedApiKey))
        {
            return Results.Unauthorized();
        }

        return await next(context);
    }
}

another option is to use
app.MapWebPubSubHub<WebPubSubHub>`("/eventhandler").RequireAuthorization(builder => builder.AddRequirements(new ApiKeyRequirement))

where ApiKeyRequirement is your implementation of IAuthorizationRequirement
Question: How to convert milliseconds to seconds units and display them in textView?

How to convert milliseconds to seconds units?
For example the seekBar values are from 100 to 1000 and I want to display the units if they are under 1000(second) as 0.1 0.2 0.3....0.9 then 1
private var counter: Long = 0

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<TextView>(R.id.textView)
        val seek = findViewById<SeekBar>(R.id.seekBar)
        seek.min = 100
        seek.max = 1000
        seek.progress = 500
        counter = seek.progress.toLong()

        seek.setOnSeekBarChangeListener(
            object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    counter = progress.toLong()
                    textView.text = (counter/1000).toString()

The line:
textView.text = (counter/1000).toString()
make it that if the bar is on the right side it will display 1 but then to the left it will display only 0.
and I want that on the right end it will display 1 but then when moving it to the left it will display 0.9 then 0.8 then 0.7.....0.1
I tried:
textView.text = (counter/1000).toString()


Answer:
Change the data type of counter from Long to Float or Double. Long only allows integer values.
private var counter: Float = 0.0F
...
counter = seek.progress.toFloat()
Question: Unbound module Sqlite3

I am trying to learn some OCaml, I created a very simple example to open and then close a sqlite file.
let () =
  let db = Sqlite3.db_open "test.db" in
  Sqlite3.db_close db

I did an opam install sqlite3 and I see the .opam/default/lib/sqlite3 files in place. I would expect this means that the package is installed.
When I run ocaml sqltest.ml I would expect this to execute. Instead I get a Error: Unbound module Sqlite3
Even when I make it ocaml -I +sqlite3 sqltest.ml I get the same result. It's kind of hard to search for info on ocaml and most of the stuff I find is using dune or ocamlbuild or ocamlfind or something... I think that's fine, but in the interest of starting with the basics and building from there I would like to understand how all of the pieces are working. I'd imagine the basic ocaml or ocamlc should work in this simple case.
How do I make it understand where these libs are and use them? Why does it not understand it's own "default libs"?


Answer:
Using ocamlfind to compile a trivial demonstration program that opens the Sqlite3 module.
$ cat test.ml
open Sqlite3

let () = print_endline "hello"
$ ocamlc test.ml
File "test.ml", line 1, characters 5-12:
1 | open Sqlite3
         ^^^^^^^
Error: Unbound module Sqlite3
$ ocamlfind ocamlc test.ml -package sqlite3 -linkpkg
$ ./a.out
hello

Alternative use of ocamlfind:
$ ocamlc -I `ocamlfind query sqlite3` sqlite3.cma test.ml
$ ./a.out
hello

As a side note, your code will not compile even with proper use of the compiler and ocamlfind because Sqlite3.db_close returns a boolean, you're trying to bind that expression to (). This is a type mismatch.
And you've opened Sqlite3 so you don't need to use the fully qualified names. You might want to use let& to avoid the db_close.
open Sqlite3

let () =
  let& db = db_open "test.db" in
  print_endline "hello"
Question: ggplot - reorder_within - Order month

I am plotting a bar graph. However, the axes x show in different month order. Using the command reoder_within, doesn't work for the purpose.
Follow below the ME.
ggplot(de, aes(fill=Cidade, y = Leitura  , x = Mes ))+geom_bar(position='dodge', stat='identity')

Generate the follow plot:
Plot
My purpose is modify the axes x to: Jan, Fev, March .....
The set of data is:
  Cidade    Mes       Leitura
  <chr>     <chr>       <dbl>
1 Petrolina Janeiro     74.2 
2 Petrolina Fevereiro   73.2 
3 Petrolina Março       68.7 
4 Petrolina Abril       42.9 
5 Petrolina Maio         9.84
6 Petrolina Junho        8.02



Answer:
We can use fct_inorder here:
ggplot will order x axis alphapetically. To get the order in your table use fct_inorder:
library(ggplot2)
library(forcats)
library(dplyr)

de %>% 
  mutate(Mes = fct_inorder(Mes)) %>% 
  ggplot(aes(fill = Cidade, y = Leitura, x = Mes)) +
  geom_bar(position = 'dodge', stat = 'identity')
Question: How to define a command alias in PowerShell for filtering output?

I need to define an alias for this:
Select-String -NotMatch -Pattern "^[\t ]+\d"
so that I can use the alias instead of writing that long string each time.
After googling for 5 minutes and doing some experiments I came up with this:
filter foo {
    $_ | Select-String -NotMatch -Pattern "^[\t ]+\d"
}

So now my script looks like this:
command1 | foo
command2 | foo
command3 | foo
command4 | foo

This is apparently working as expected, but I'm concerned about the efficiency implications of doing this.
Is the foo filter acting as a transparent alias of the longer command line, or is it creating an entire new pipe or buffer or something?


Answer:

Is the foo filter acting as a transparent alias of the longer command line, or is it creating an entire new pipe or buffer or something?

The latter, your current implementation is invoking Select-String per pipeline input object instead of invoking it once and processing all input. If you care about performance you should change your implementation for a steppable pipeline:
function steppablefoo {
    param([Parameter(ValueFromPipeline)] $InputObject)

    begin {
        $pipe = { Select-String -NotMatch -Pattern '^[\t ]+\d' }.GetSteppablePipeline()
        $pipe.Begin($PSCmdlet)
    }
    process {
        $pipe.Process($InputObject)
    }
    end {
        $pipe.End()
    }
}

You can test it for yourself with this performance comparison:
$tests = @{
    Filter = {
        0..300kb | foo
    }
    SteppablePipeline = {
        0..300kb | steppablefoo
    }
}

$tests.GetEnumerator() | ForEach-Object {
    [pscustomobject]@{
        Test              = $_.Key
        TotalMilliseconds = (Measure-Command { & $_.Value }).TotalMilliseconds
    }
}
Question: Remove whitespace from an array of string

Remove whitespace from an array of string.
While creating an array of string from a sentence, I'm encountering multiple spaces and need to remove them in order to create a new reverse sentence from the given sentence. How do I remove extra spaces in the middle of two words?
Example: a good   example
How do I remove two spaces in between good and example ?
Here is the code I'm using:
public class reverseString {
    public static void main(String[] args) {
        String s = "a good   example";
        String ans = revString(s);
        System.out.println(ans);
    }
    static String revString(String s) {
        String[] arr = s.split(" ");
        List<String> list = new ArrayList<String>();
        StringBuilder ans = new StringBuilder();
        for (int i = arr.length - 1; i >= 0; i--) {
            if (arr[i] == null) {
                continue;
            } else {
                ans.append(arr[i].trim());
                // ans.append(" ");
            }
        }
        String is = ans.toString();
        return is.trim();
    }
}

The expected output was: example good a
The output I'm getting is: example   good a
Comparing the string at the I-th index with " " should result in continuation of the loop. Instead it jumps to the else condition.


Answer:
The parameter to method split (of class java.lang.String) is a regular expression. Just add a + (i.e. "plus" symbol – which means one or more) to the value of the parameter.
import java.util.ArrayList;
import java.util.List;

public class ReverseString {

    public static void main(String[] args) {
        String s = "a good   example";
        String ans = revString(s);
        System.out.println(ans);

    }

    static String revString(String s) {
        String[] arr = s.split(" +"); // CHANGE HERE - added '+'
        List<String> list = new ArrayList<String>();
        StringBuilder ans = new StringBuilder();
        for (int i = arr.length - 1; i >= 0; i--) {
            if (arr[i] == null) {
                continue;
            }
            else {
                ans.append(arr[i].trim());
                ans.append(" ");
            }
        }
        String is = ans.toString();
        return is.trim();
    }
}

Running the above code produces the following output:
example good a
Question: Is there a way to listen for changes in p-columnFilter match options and call a function in Angular and PrimeNG?

Is it possible to bind a function that gets called every time user chooses between matchOption of p-columnFilter.
<p-columnFilter type="date">
...
</p-columnFilter>


example: https://stackblitz.com/edit/owuvzd?file=src%2Fapp%2Fdemo%2Ftable-filter-menu-demo.html


Answer:
I was able to find a workaround to this, by creating my own matchModeOptions and their filter functions.
To do this I made use of FilterService
public dateIsFilter: string = "is-date";

public matchModeOptions: any[] = [
  { label: "Date is", value: this.dateIsFilter }
]

constructor(private filterService: FilterService){
}

ngOnInit(): void {
  this.filterService.register(this.dateIsFilter, (value: any, filter: any) => {
  // code here
  return this.filterService.filters.dateIs(value, filter)
});
}

Then I changed p-columnFilter to use custom matchModeOptions.
<p-columnFilter type="date" [matchModeOptions]="this.matchModeOptions">
...
</p-columnFilter>
Question: How can I convert an array with key-value pairs to an array with separate sub-arrays for the keys and values in PHP?

Converting an array [fields => values] to one [fields, values]
If I have an array like this:
[
field1 => value1,
field2 => value2,
field3 => value3
];

and I want to convert it to an array like this:
[
[field1, field2, field3],
[value1, value2, value3]
];

now I just took the keys and values and put them in another array:
[
array_keys($array),
array_values($array)
];

Is there a more elegant way to do this?


Answer:
Before considering "elegant", first consider output consistency.  If you always want to create an array with two first level elements, your approach is suitable.
However, if you want an empty output array when your input array is empty, you'll need a different approach where the result array is only deepened when necessary such as...
Code: (Demo)
$result = [];
foreach ($array as $k => $v) {
    $result[0][] = $k;
    $result[1][] = $v;
}
var_export($result);


If you always want a two-element result, a body-less loop can avoid making any function calls in a concise way. (Demo)
$result = [[], []];
foreach ($array as $result[0][] => $result[1][]);
var_export($result);


Functional programming with array_reduce() can become ugly/verbose for this task. (Demo)
var_export(
    array_reduce(
        array_keys($array),
        function ($result, $k) use ($array) {
            $result[0][] = $k;
            $result[1][] = $array[$k];
            return $result;
        },
        []
    )
);

And if you are considering array_walk(), that is just going to work like a foreach() anyhow because it doesn't deliver its result payload as a returned value.

If you consider functional programming to be elegant, bear in mind that double-transposing with array-map() calls will not work when there is one element or less in your input array. Proof
Question: How to have child div not trigger hover effect of parent div?

I am trying to find out how to have a child element that has position: absolute that is positioned outside of its parent element that does not trigger the parent's :hover effect.
Since the parent has a hover effect, the child elements will  trigger the parent element, even though that child is outside of the parent element's boundary.
Is there an attribute I am missing, or is this just the way inheritance in HTML works?
Picture Example:

In this image, my mouse cursor is inside the child div, but outside of the parent div.


body {
  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  background-color: black;
  width: 800px;
  aspect-ratio: 1 / 1;
}

.container:hover {
  background-color: darkorange;
}

.child {
  position: absolute;
  background-color: red;
  width: 100px;
  height: 100px;
  transform: translate(-50px, 0px);
}
<div class="container">
  <div class="child"></div>
</div>





Answer:
You can use following solutions for this.

You can use pointer-events: none on the child element. But remember that this will block all types of pointer events on that, and not just hover event. So any sort of click events will also not work on that child element.

Another option is to use :has() method in the css. :has() allows you to target an element that meets the conditions passed to it. You can do it like this -


  .container:not(:has(.child:hover)):hover {
    background-color: darkorange;
  }
        

This will prevent the hover effect on container when hovered over its child element, which is specified in the :has() method.
Here is the JSFiddle example demonstrating this method.
Read more about :has() in here
Question: Executing RXJS Functions in Sequence Defined By Array

I am attempting to execute multiple functions consecutively by defining them in an array (specifically for an Angular APP_INITIALIZER function).
I have this array:
const obsArray = [
    myService1.init(),
    myService2.init(),
    ...
    myServiceN.init()
]

Each of these init() methods returns Observable<void>. Here's an example:
    init() : Observable<void> {
         return this.http.get(this.apiUrl)
             .pipe(
                 // do something with the response
                 switchMap(() => EMPTY)
             );
    }

The ``switchMapstatement ensures that the return type isObservable```.
I've tried this:
    const init$ : Observable<void> = forkJoin(obsArray);

But at best it executes the function but not the HTTP call inside. There is no subscribe() call since this is inside an Angular factory function assigned to the APP_INITIALIZER token.
I've also tried concatMap() with no luck.
Is there an rxjs function that will execute each of these consecutively, while waiting for the previous to complete?
I have followed this up with this question.


Answer:
You can also put all the observables from the array into an observable, essentially converting Array<Observable<T>> to Observable<Observable<T>> and then use the higher order function concatAll:
from(obsArray).pipe(concatAll())

Here's a live demo.
Question: Cubic-bezier fixes exiting animation but breaks entering animation

I'm trying to animate a collapsing list with React/Joy-UI
Here is my Transition element
     <Transition nodeRef={nodeRef} in={browseOpen} timeout={1000}>
      {(state: string) => (<List
        aria-labelledby="nav-list-browse"
        sx={{
          '& .JoyListItemButton-root': { p: '8px' },
          transition: '1000ms',
          transitionProperty: 'max-height',
          overflow: 'hidden',
          ...{
            exiting: { maxHeight: '0px'},
            exited: { maxHeight: '0px'},
            entering: { maxHeight: '500px'},
            entered: { maxHeight: '500px'},
          }[state],
        }}
      >

With this the list expands fine, but there appears to be a delay on collapsing.
I then added "cubic-bezier(0, 1, 0, 1)" to the "transition" property, which fixes the collapsing animation, but the expand animation then seems to break entirely.
How can I get both the entering and exiting working?
Before adding cubic bezier (sorry for the loss-y gifs):

After adding cubic bezier:



Answer:
Found the answer:
The transition needed to be set like this:
transition: `1000ms ${state === "exiting" ? "cubic-bezier(0, 1, 0, 1)" : "ease-out"}`

For any other novices out there, note the backticks `` around the string rather than ''
Question: Can I publish client ID?

I've coded beyond my ability and managed to get MSAL authentication working for my Browser Extension. I'm ready to push code to GitHub.
Is it ok to push code with the Client ID in it? Can someone else use my Client ID? If I can't safely push this to a public GitHub, how do I handle it?
// Microsoft Authentication Library (MSAL) instance
// Client ID is the Application (client) ID GUID from the Azure portal
const msalInstance = new msal.PublicClientApplication({
    auth: {
        authority: "https://login.microsoftonline.com/common/",
        clientId: "ffffffff-ffff-ffff-ffff-ffffffffffff",
        redirectUri: redirectUri,
        postLogoutRedirectUri: redirectUri
    },
    cache: {
        cacheLocation: "localStorage"
    }
});



Answer:
Technically, it should be okay.

Is it ok to push code with the Client ID in it?

The question you should ask yourself is, what information does the client ID give away? According to the Microsoft identity platform and the OAuth 2.0 client credentials flow a client_id is,

The Application (client) ID that the Azure portal – App registrations experience assigned to your app.

It is essentially like your name. It won't be end of the world if you give it away but you probably should not where there is no reason to.
Quoting, Should the OAuth client_id be kept confidential?

Your client_id is like your username or e-mail address you use to authenticate your application/service to OAuth. It's not exactly top-secret, but putting it out in the public domain might also be undesirable.

Further,

Can someone else use my Client ID?

Yes, but even in the confidential client apps, "The client ID is exposed through the web browser."
Note that we can actually see the Thunderbird's client id exposed in their source code. It isn't really meant to be private information.

If I can't safely push this to a public GitHub, how do I handle it?

You can use a password manager if you are the only user of your extension.
Question: Mixing grid auto layout with a fixed row-column position

I have the following HTML with a CSS grid
<div id="grid">
    <div class="main-item">Main</div>
</div>

#grid {
    display: grid;
    grid-template-columns: repeat(5, auto);
    text-align: center;
}

#grid > * {
    border: 1px solid blue;
    padding: 20px;
}

#grid > .main-item {
    grid-row: 3;
    grid-column: 3 / 5;
    background: rgba(0, 0, 0, 0.2);
}

The important part is .main-item has a fixed position in the grid.
I now add 25 cells to the grid.
const grid = document.querySelector("#grid");

for (let i = 0; i < 25; i++) {
    const item = document.createElement("div");
    item.innerText = i.toString();
    grid.append(item);
}

The problem is that I want these elements to ignore the position of the .main-item (treat it as if it wasn't there). However the CSS currently corrects for this and flows the elements around .main-item. I want the secondary behaviour below:

I can correct by setting style.gridRow and style.gridColumn in the JavaScript
item.style.gridRow = (Math.floor(i / 5) + 1).toString();
item.style.gridColumn = ((i % 5) + 1).toString();

Is there a way to do this without setting every other element in JS? Is there a CSS to prevent fixed element affecting the flow correction?
Codepen Link


Answer:
You can give the grid a relative position and position that specific grid item absolutely.


const grid = document.querySelector("#grid");
for (let i = 0; i < 25; i++) {
    const item = document.createElement("div");
    item.innerText = i;
    grid.append(item);
}
#grid {
    display: grid;
    grid-template-columns: repeat(5, auto);
    text-align: center;
    position: relative;
}

#grid > * {
    border: 1px solid blue;
    padding: 20px;
}

#grid > .main-item {
    position: absolute;
    left: 0;
    right: 0;
    grid-row: 3;
    grid-column: 3 / 5;
    background: rgba(0, 0, 0, 0.2);
}
<div id="grid">
    <div class="main-item">Main</div>
</div>
Question: How to pass curly bracket ({) as a string in f-string python?

due to these bracket { and } in Hourly Status','{',''),'}','') causing the syntax error in query .How to pass these bracket as string in a f-string format?
query = f"""Select fd.serial_number,txidkey,cast(replace(replace(data->>'Hourly Status','{',''),'}','') as text) as description,TO_TIMESTAMP(TIME/1000+19800) as date_time,time,total_min from filter_data fd , total_sum ts
where fd.serial_number = ts.serial_number
and time between {yesterday10PM*1000} and {today6AM*1000}'''



Answer:
just use double curly braces {{:
query = f"""\
Select fd.serial_number, txidkey, cast(\
replace(replace(data->>'Hourly Status','{{',''),'}}','') as text) \
as description,TO_TIMESTAMP(TIME/1000+19800) as date_time,time,total_min \
from filter_data fd , total_sum ts \
where fd.serial_number = ts.serial_number \
and time between {yesterday10PM*1000} and {today6AM*1000}
'''

You can also read about formatted strings here:
https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals