satoshi-2000/llms-suitable huggingface dataset:
Question: Narrow down literal unions based on previously used values

The scenario is the following:
type Option = 'a' | 'b' | 'c' | 'd'

type Question = {
  message: string;
  options: Option[];
  default: Option // here's the issue
}

I want the default prop to be the one of the options used inside question.options. For example:
const q1: Question = {
  message: 'first question',
  options: ['a', 'b'],
  default: 'a'
}

const q2: Question = {
  message: 'second question',
  options: ['c', 'd'],
  default: 'a' // I want this to give an error because 'a' is not in 'c' | 'd'
}

How can I achieve this?


Answer:
It can be done just by using Question; however, it will be a complex type that will cause a horrible time for the compiler since it grows at the speed of power of two, and if you have more options (more than 10), the compiler will reach its limits and won't compile.
Instead, I would suggest adjusting Question to accept the Option[] as a generic parameter and assign the type of the elements of that generic parameter to default:
type Question<T extends Option[]> = {
  message: string;
  options: T;
  default: T[number];
};

Lastly, we will need a generic function that would create a question for us:
const createQuestion = <T extends Option[]>(question: Question<T>) => question;

Usage:
const q1 = createQuestion({
  message: "first question",
  options: ["a", "b"],
  default: "a",
});

const q2 = createQuestion({
  message: "second question",
  options: ["c", "d"],
  default: "a", // Expected error
});

playground
Question: How to create a transparent Material 3 NavigationBar in Flutter?

I want to make my NavigationBar transparent. I have tried extendBody: true on Scafold with surfaceTintColor=Colors.transparent to the NavigationBar widget, but nothing changed.


Answer:
According to the document, SurfaceTintColor is the color of the surface tint overlay applied to the app bar's background color to indicate elevation.
If you want to make the AppBar transparent, just use the property backgroundColor instead.
Scaffold(
      extendBody: true,
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.transparent, // To make appBar transparent
        
        /// This is not necessary. You can play around 
        /// to see surfaceTintColor when the AppBar is transaprent
        surfaceTintColor: Colors.redAccent,
        elevation: 3,
        title: Text(widget.title),
      ),
),

It is also applied to NavigationBar
bottomNavigationBar: NavigationBar(
        surfaceTintColor: Colors.amber, // not neccessary
        backgroundColor: Colors.transparent,
        destinations: [
          Icon(Icons.book, color: Colors.blue,),
          Icon(Icons.map, color: Colors.blue,),
        ],
      ),
Question: Altair: showing the value of the current point in the tooltip

In the code below, we have a dataset that can be read as: "two cooks cook1, cook2 are doing a competition. They have to make four dishes, each time with two given ingredients ingredient1, ingredient2. A jury has scored the dishes and the grades are stored in _score.
I want to use Altair to show a graph where the x-axis is each dish (1, 2, 3, 4) and the y-axis contains the scores of the two cooks separately. This currently works but the main issue is that on hover, the tooltip does not include the score of the current point that is being hovered.
import altair as alt
import pandas as pd


df = pd.DataFrame({
    "ingredient1": ["potato", "onion", "carrot", "beet"],
    "ingredient2": ["tomato", "pepper", "zucchini", "lettuce"],
    "dish": [1, 2, 3, 4],
    "cook1": ["cook1 dish1", "cook1 dish2", "cook1 dish3", "cook1 dish4"],
    "cook1_score": [0.4, 0.3, 0.7, 0.9],
    "cook2": ["cook2 dish1", "cook2 dish2", "cook2 dish3", "cook2 dish4"],
    "cook2_score": [0.6, 0.2, 0.5, 0.6],
})


value_vars = [c for c in df.columns if c.endswith("_score")]
cook_names = [c.replace("_score", "") for c in value_vars]
id_vars = ["dish", "ingredient1", "ingredient2",] + cook_names
df_melt = df.melt(id_vars=id_vars, value_vars=value_vars,
                  var_name="cook", value_name="score")

chart = alt.Chart(df_melt).mark_circle().encode(
    x=alt.X("dish:O", title="Dish number"),
    y=alt.Y("score:Q", title="Score"),
    color="cook:N",
    tooltip=id_vars
)

chart.show()


I tried explicitly adding the score columns to the tooltip:
    tooltip=id_vars+value_vars

But that yields the following error:

ValueError: cook1_score encoding field is specified without a type; the type cannot be inferred because it does not match any column in the data.

So how can I get altair to also show the score of (only) the currently hovered element?


Answer:
cook1_score is not a column in df_melt, which is why you see the error. Setting tooltip=id_vars+['score'] will work.
Question: Flutter: Inconsistent column padding on Buttons between Android and Windows

I have created a simple material app in flutter with:
flutter create --platforms=android,windows columntest
When I run the program on Android and Windows, I get some kind of padding between the ElevatedButtons on Android, but not on Windows. Do you know where this comes from and how I can make the design consistent?
The behavior seems to occur only with buttons (TextButton, OutlinedButton, ElevatedButton).
I have also tested this with container (with border), there it does not occur.
Here the code from the small app:
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(child: const Text("Foobar1"), onPressed: () {}),
              ElevatedButton(child: const Text("Foobar2"), onPressed: () {}),
            ],
          ),
        ),
      ),
    );
  }
}


Here is a screenshot at runtime:

Here my flutter version:
$ flutter --version
Flutter 3.10.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 84a1e904f4 (3 weeks ago) • 2023-05-09 07:41:44 -0700
Engine • revision d44b5a94c9
Tools • Dart 3.0.0 • DevTools 2.23.1

My Android Emulator is an: Pixel_3a_API_33_x86_64
But the behaviour also occurs on my physical Pixel 6 (with android UpsideDownCake)
I look forward to your responses.
best regards
Michael


Answer:
So, this implementation is done by flutter.
This is behaviour is because of the ThemeData.materialTapTargetSize parameter for the MaterialApp.
This feature decides what should be touchable dimensions of Material Button, in your case ElevatedButton.
You have 2 potential solutions

Change padding from ElevatedButton like below

    ElevatedButton(
              onPressed: () {},
              style: const ButtonStyle(padding: MaterialStatePropertyAll(EdgeInsets.zero)),
              child: const Icon(Icons.abc),
            ),


Change value from material app

    MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
      home: CupertinoPickerExample(),
    )

Reference :  https://stackoverflow.com/a/67580951
Question: Perl Mojolicious: Passing arguments to a code ref

In my Mojolicious Controller, I have:
my @promise;
foreach my $code (\&doit1, \&doit2,) {
    my $prom = Mojo::Promise->new;
    Mojo::IOLoop->subprocess(
    sub {
        my $r = $code->("Hello");
        return $r;
    },
    sub {
        my ($subprocess, $err, @res) = @_;
        return $prom->reject($err) if $err;
        $prom->resolve(@res);
    },
    );
    push @promise, $prom;
}

Mojo::Promise
    ->all(@promise)
    ->then(
    sub {
    my ($result1, $result2) = map {$_->[0]} @_;
    });

This works, and I can pass arguments (e.g. Hello) to my sub.
Now I converted doti1() and doit2() as helpers. So the code looks like:
foreach my $code (sub {$self->myhelper->doit1("Goodbye")},
                  sub {$self->myhelper->doit2("Good night")},
    ) {
    my $prom = Mojo::Promise->new;
    Mojo::IOLoop->subprocess(
    sub {
        my $r = $code->("Hello"); # this is ignored?
        return $r;
    },
    sub {
        my ($subprocess, $err, @res) = @_;
        return $prom->reject($err) if $err;
        $prom->resolve(@res);
    },
    );
    push @promise, $prom;
}

How can I continue to pass the same set of arguments inside the loop (e.g. Hello), without having to specify them in each code ref (i.e. avoid Goodbye & Good night)? I like the idea of passing the same arguments for each code ref: $code->("Hello")


Answer:

Now I converted doti1() and doit2() as helpers. So the code looks like:

foreach my $code (sub {$self->myhelper->doit1("Goodbye")},
                  sub {$self->myhelper->doit2("Good night")},
    ) {
    #....
}

Yes but you are calling the helpers from another anonymous sub,

How can I continue to pass the same set of arguments inside the loop (e.g. Hello), without having to specify them in each code ref

so to recover the argument and pass it on the the helper, you just do:
foreach my $code (sub {my $arg = shift; $self->myhelper->doit1($arg)},
                  sub {my $arg = shift; $self->myhelper->doit2($arg)},
) {...}

or more generally as @Dada pointed out in the comments:
foreach my $code (sub {$self->myhelper->doit1(@_)},
                  sub {$self->myhelper->doit2(@_)},
) {...}
Question: How can I parse the certificate information output from the security command in Mac?

I need to retrieve the attributes of a certificate that is stored in the keychain on my Mac from the command line. I can collect them manually from the Keychain Access app, but I want to do that with a script.

I used the security command to get a certificate and "grep" to inspect the "subject" section:
security find-certificate -c "Apple Development" login.keychain | grep "subj"

and then got the following output (some omitted by "...").
"subj"<blob>=0x3081943...553  "0\201\2241\0320\03...02US"

In the output above, what format is the data following "subj"<blob>= and how can I parse it? I found that decoding the first half of the hexadecimal sequence(0x30...) with UTF-8 yields the second half of the string (0\201...), but I don't know what 0\201\2241\... means. I have tried other character codes, but they just give me garbled characters.


Answer:
As for the format, the certificates are stored in DER/PEM format, which is a representation of ASN.1 encoded data. What you see in the output is the hexadecimal representation of the ASN.1 binary data. The blob indicates that the value or attribute is stored as binary data.
As for exporting (for certificates), I would highly recommend combining security with openssl as follows:
security find certificate -p -c "Apple Development" login.keychain | openssl x509 -noout -subject

The -p option in the security command exports the found certificate in PEM format, which is something openssl can use. You can then pipe the PEM data into the openssl command, where one can easily extract the subject using the -subject option.
You can check out both the man page of security and the man page of openssl x509.
Question: Function call as a parameter inside insert values statement

I'm trying to insert the data inside a forall loop. For this case, I cannot use a temporary variable and set result of the function beforehand.
The function just maps a number to a string:
create or replace function GetInvoiceStatus(status number)
    return nvarchar2
as
begin
    case status
        when 0 then return 'New';
        when 200 then return 'Sent';
        when 300 then return 'Accepted';
        end case;

    return '';
end; 

when I call this function like:
select GetInvoiceStatus(200) from dual;

I get the appropriate result.
However, when I try to insert the data I get errors.
The forall insert:
forall i in 1.. INVOICE_DATA.COUNT
insert into "InvoiceAudit"
("PropertyName", "OldValue", "NewValue" (
            VALUES ('Status', (GetInvoiceStatus(invoice_data(i).status)),
                    ((GetInvoiceStatus((select "Status" from "Invoice" where "InvoiceId" = invoice_data(i).invoiceId)))));

However, I get the following error:

[2023-06-01 15:02:57] [65000][6592] [2023-06-01 15:02:57]     ORA-06592:
CASE not found while executing CASE statement [2023-06-01 15:02:57]
ORA-06512: at "PUBLIC.GETINVOICESTATUS", line 9 [2023-06-01 15:02:57]
ORA-06512: at "PUBLIC.INVOICESSP", line 63 [2023-06-01 15:02:57]
Position: 5

I have double checked, and the results from invoice_data(i).Status and the other select value are both valid parameters (and have their cases covered) and return appropriate string when called outside the stored procedure.
Is the syntax somewhere wrong?
I would like to remain using forall if at all possible because it is much faster than a regular for loop.


Answer:
This error means that the parameter value (status) is not one of the cases in the case expression (which are 0, 200, 300).
If you executed this code select GetInvoiceStatus(555) as dd from dual you will get the same error. So, add ELSE clause like this:
create or replace function GetInvoiceStatus(status number)
    return nvarchar2
as
begin
    case status
        when 0 then return 'New';
        when 200 then return 'Sent';
        when 300 then return 'Accepted';
        else return '';
    end case;
end;
Question: pivot returning blank instead of 0 google sheet

I have a spreadsheet where I have an importrange and vlookup to another file where its looking up to a pivot table. Some data is blank in the pivot table and when I lookup in the formula, I have a result of blank even though I have set it to return to 0 by iferror.
Here's my formula:
=iferror(VLOOKUP(A5,importrange("12PaJfEC7Q7gOcCx2zlMHG3YybQuk1TSsNjZDw26qFRg","Converted Pivot!A:E"),3,false),0)


Answer:
You may try:
=let(Σ,ifna(vlookup(A5,importrange("12PaJfEC7Q7gOcCx2zlMHG3YybQuk1TSsNjZDw26qFRg","Converted Pivot!A:E"),3,),"no_match_found"),
       if(Σ="",0,Σ))


blank_value will now be shown as 0 & a non-match output error will be prompted with no_match_found
Question: Make an element not scroll horizontally

I am trying to  make a layout with:

A header (gray block in the snippet)
A body (lime borrder)
Main body content ( blocks with red border)

If you scroll horizontally, then the header should not scroll, it should be full width and stay in view. If you scroll vertically, then the header should scroll off the page as usual. The height of the header is dynamic, and fits the content within it (this SO answer works with a fixed height)..
The <main> element is allowed to be wider than the viewport, but the header is always the viewport width.
The reason I dont add max-width: 100%; overflow-x: auto on the <main> element (like this SO answer, is because then the horizontal scroll appears at the bottom of the element, and then say one is reading the first block, and you wish to scroll horizontally, you have to scroll to the bottom of the main element to see the horizontal scroll bar, scroll to the side, then scroll back up. I wish to have the horizontal scroll bar always present if main is wider than the view port.
I have tried position: sticky/fixed on the header but could not get it to work.
I would prefer not to use JavaScript if possible.


header {
  padding: 32px;
  background: gray;
  width: 100%;
}
main {
  border: 2px solid lime;
  min-width: 100%;
}
div {
  height: 200px;
  width: 120%; /* make it overflow horizontally */
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid red;
}
<header>The Header should not scroll horizntally<br>(is dynamic height)</header>
<main>
  <div>content 1</div>
  <div>content 2</div>
  <div>content 3</div>
  <div>content 4</div>
  <div>content 5</div>
  <div>content 6</div>
</main>





Answer:
What I have done here is make header sticky to the left part of the screen. Its parent element must be aware of size of your content to allow header to move. So I set body min-width to min-content and same with main so it can transfer its children's size to body.
You also may notice I used box-sizing: border-box; in the header, its so padding size is taken into account when element size is calculated(100vw in this case). You don´t want to use % on header width because it won´t have room to slide.
Also div sizes must not be dependent on parent size, so you can´t use % here either.


body{
  min-width: min-content;
}

header {
  box-sizing: border-box;
  position: sticky;
  left: 0;
  padding: 32px;
  background: gray;
  width: 100vw;
}
main {
  min-width: min-content;
  border: 2px solid lime;
}
div {
  height: 200px;
  width: 120vw; /* make it overflow horizontally */
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid red;
}
<body>

<header>The Header should not scroll horizntally<br>(is dynamic height)</header>
<main>
  <div>content 1</div>
  <div>content 2</div>
  <div>content 3</div>
  <div>content 4</div>
  <div>content 5</div>
  <div>content 6</div>
</main>
</body>
Question: "Unused CSS selector" when using a SASS themify mixin with Svelte and Vite:

I'm trying to create a small web application using Svelte.
One of the requirements is to be able to change the application "theme" on demand, for example - dark theme, light theme, high contrast, and so on.
I've been using an online mixin snippet to help me with that -
https://medium.com/@dmitriy.borodiy/easy-color-theming-with-scss-bc38fd5734d1
However, this doesn't work consistently, and I often get errors like:
[vite-plugin-svelte] /path/to/svelte/component.svelte:61:0 Unused CSS selector "main.default-theme div.some.element.identification"
even tho the selector is used and is receiving it's non-themed attributes.
Inside a themes.scss file:
@mixin themify($themes) {

    @each $theme,
    $map in $themes {
        main.#{$theme}-theme & {
            $theme-map: () !global;

            @each $key,
            $submap in $map {
                $value: map-get(map-get($themes, $theme), '#{$key}');
                $theme-map: map-merge($theme-map, ($key: $value)) !global;
            }

            @content;
            $theme-map: null !global;
        }
    }
}

@function themed($key) {
    @return map-get($theme-map, $key);
}

$themes: (
    default: (
        strokeColor: green,
        fillColor: red,
    ),
);

and inside another scss file that is importing themes.scss:
div.some.element.identification {
    some-non-themed-attribute: some-value;

    @include themify($themes) {
        stroke: themed('strokeColor');
        fill: themed('fillColor');
    }
}

now the punchline - when using this methodology, some elements are receiving their appropriate themed attributes, and others dont.
I am also seeing the following error:
[vite-plugin-svelte] /path/to/svelte/component.svelte:61:0 Unused CSS selector "main.default-theme div.some.element.identification"
the issue doesn't seem to be in the css selectors - since the elements that dont receive the themed attributes, still receive the other non-themed attributes in the same css clause.
Two final observations -

When I'm building the project (using vite build), I can see that the css asset file being created doesn't include the css selectors that are missing their themed attributes.
When i'm using the devtools to locate the supposedly unused selectors (whose themed attributes are not present), they can be found - despite the error message.

I've been trying different way to solve this issue and nothing works consistently.
Thank you in advance for your help!


Answer:
You could try checking these different items:

If you use svelte-preprocess, try to add scss: { prependData: `@import 'src/styles/theme.scss';` } or whatever the path to your theme is, to the config object.
If it still does not work, maybe try to swap svelte-preprocess with vite-preprocess
Disable any potential css purge plugin
Question: Is it faster to use push_back(x) or using an index (capacity)?

I learned 2 ways of inserting elements into a vector.
And I've been wondering which way is faster since I'm working with time limits.
Method 1:
int n;
cin>>n;
vector<int> v(n);
for(int i = 0;i<n;i++){
  cin>>v[i];
}

Method 2:
int n;
cin>>n;
vector<int> v;
for(int i = 0;i<n;i++){
  int x;
  cin>>x;
  v.push_back(x);
}

If you have a better method to suggest, it'd be appreciated!


Answer:
Both have issues:
You should be using reserve(n)
int n;
cin >>  n;
vector<int> v;
v.reserve(n);
for(int i = 0; i < n; ++i){
    int x;
    cin >> x;
    v.emplace_back(x);
}

In the first version: Setting size.
Here you have the issue that you are constructing all the elements in the array. Now for integers this may be insignificant. But if we extend this to non integer types that have a constructor that needs to be called for each element and then you are using the assignment operator to copy over them.
The second option: push_back
Here you run into the risk of the underlying storage being reallocated (potentially multiple times). Each time you re-allocate you need to copy the data from the old storage to the new storage.
Again this hurts for integers but really hurts for types with constructors and destructors.
Prefer: emplace_back()
Rather than pushing where you need a fully constructed object. You can use emplace_back and pass in the objects used to construct the object. This allows the vector to construct the object in place. If you have simple integers or classes with effecient move semantics then not an issue but worth it as a general habit.
Question: Background video in Node.js 13

I am trying to set up a gif as a background,I get does it not work:
In the code Import GridMatrix and extract the src from it, then I use the video tag to try to render it on fullscreen.
import React from 'react';
import GridMatrix from '../assets/gridMatrix.gif';

function Home() {

    return (
        <div>
            <video
                className="matrix-bg fixed top-0 left-0 w-full h-full z-[-1] object-cover"
                autoPlay
                loop
                muted
            >
                <source
                    src={GridMatrix.src}
                    type="video/gif"
                />
            </video>
            <main className="container mx-auto py-10 px-4 flex flex-col items-center justify-center">
                <h1 className="text-4xl font-bold mb-8 text-white text-center">
                    UNS Demo
                </h1>
                <button className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
                    Login
                </button>

            </main>
        </div>
    );
}

export default Home;




Answer:
GIF files are not video files and the MIME type for them is image/gif. The <video> tag will not render them.
You can embed images using <img src={GridMatrix.src} /> or set it as a background-image with CSS on an element.
Nowadays, websites often embed what they call 'GIFs' that are actually video files, but notice that those are often .webm or .mp4 files, both being video formats, thus compatible with <video>.