satoshi-2000/llms-suitable huggingface dataset:
Question: Azure Diagnostic Logs saved to another location

I'm looking to create using Bicep, diagnostic settings on a firewall in one location and save to an Event Hub in another location. The two vnets are peered, but I am wondering if it is possibe based on this error message:
Resource '/subscriptions/123/resourceGroups/ukw-rg/providers/Microsoft.Network/azureFirewalls/ukw-fw' is in region 'ukwest' and resource '/subscriptions/123/resourcegroups/uks-rg/providers/microsoft.eventhub/namespaces/uks-evhns' is in region 'uksouth'



Answer:
You are correct. It isn't possible. https://learn.microsoft.com/en-us/azure/azure-monitor/essentials/diagnostic-settings?tabs=portal#destination-limitations
"The event hub namespace needs to be in the same region as the resource being monitored if the resource is regional."
kind regards
Alistair
Question: How do I get my embed tag to display videos instead of downloading them?

My embed tag keeps downloading the video instead of displaying it.
I have tried changing the file type of the tag, but it just downloads it in a different format. I want the tag to display the video. Here's my code below.


<embed type="video/mp4" src="videos/ymcaHome.mp4" width="400" height="300">





Answer:
You can do so by specifying the video url or the path as the src attribute value. Like this:


<embed src="your_video_file_url.mp4" type="video/mp4" with="640" height="360">
Question: What causes the different NaN behavior when compiling `_mm_ucomilt_ss` intrinsic?

Can someone explain me why the following code fails for GCC 8.5 with NaNs?
bool isfinite_sse42(float num)
{    
    return _mm_ucomilt_ss(_mm_set_ss(std::abs(num)),
                          _mm_set_ss(std::numeric_limits<float>::infinity())) == 1;
}

My expectation for GCC 8.5 would be to return false.
The Intel Intrinsics guide for _mm_ucomilt_ss says
RETURN ( a[31:0] != NaN AND b[31:0] != NaN AND a[31:0] == b[31:0] ) ? 1 : 0

i.e., if either a or b is NaN it returns 0. On assembly level (Godbolt) one can see a ucomiss abs(x), Infinity followed by a setb.
# GCC8.5 -O2  doesn't match documented intrinsic behaviour for NaN
        ucomiss xmm0, DWORD PTR .LC2[rip]
        setb    al

Interestingly newer GCCs and Clang swap the comparison from a < b to b > a and therefore use seta. But why does the code with setb returns true for NaN and why seta returns false for NaN?


Answer:
GCC is buggy before GCC13, not implementing the documented semantics of the intrinsic for the NaN case which require either checking PF separately, or doing it as ucomiss Inf, abs so the unordered case sets CF the same way as abs < Inf.
See https://www.felixcloutier.com/x86/ucomiss#operation or the nicer table in https://www.felixcloutier.com/x86/fcomi:fcomip:fucomi:fucomip .  (All x86 scalar FP compares that set EFLAGS do it the same way, matching historical fcom / fstsw / sahf.)




Comparison Results
ZF
PF
CF




left > right
0
0
0


left < right
0
0
1


left = right
1
0
0


Unordered
1
1
1




Notice that CF is set for both the left < right and unordered cases, but not for the other two cases.
If you can arrange things such that you can check for > or >=, you don't need to setnp cl / and al, cl to rule out Unordered.  This is what clang 16 and GCC 13 do to get correct results from ucomiss inf, abs / seta.
GCC8.5 does the right thing if you write abs(x) < infinity, it's only the scalar intrinsic that it doesn't implement properly.  (With plain scalar code, it uses comiss instead of ucomiss, the only difference being that it will update the FP environment with a #I FP-exception on QNaN as well as SNaN.)
This requires a separate movss load instead of a memory source.  But this does let GCC avoid the useless SSE4.1 insertps instruction that zeros the high 3 elements of XMM0, which ucomiss doesn't read anyway.  Clang sees that and optimizes away that part of _mm_set_ss(num) but GCC doesn't. The lack of an efficient way to go from a scalar float to a __m128 with don't-care upper elements is a persistent problem in Intel's intrinsics API that only some compilers manage to optimize around.  (How to merge a scalar into a vector without the compiler wasting an instruction zeroing upper elements? Design limitation in Intel's intrinsics?)  A float is just the low element of a __m128.
Question: Why won't Binary search find an element in Java?

Why won't Binary Search find an element?
I have one array with elements: BBBB, BBBB, CCCC. I want to find elements BBBB and BBBB. I want binary search to find two elements and it finds one. The output is "1" and it should be "2".
import java.util.*;

public class Test{
    public static void main(String[] args) {
        ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB","BBBB","CCCC"));
        ArrayList<String> bricksNeeded = new ArrayList<String>(List.of("BBBB","BBBB"));
        int nFound = 0;
        int index;
        for(String brickNeeded:bricksNeeded){
            index = Collections.binarySearch(bricks, brickNeeded);
            if(index >= 0){
                bricks.remove(bricks.get(index));
                nFound ++;
                break;
            }
        }
        System.out.println(nFound);
    }
}

Output:
1
Expected output:
2


Answer:
You have statement break - loop will be stopped after first removing.
So, nFound will be incremented only once
Question: How to select multiple DIVs by mousedown>mousemove>mouseup (pure JS)

I'm trying to make a selection of elements when I click on empty point and move pointer.
In this example I'm expecting to get selection of two elements:

I've tried range and selection, but not with the proper result.


const mainDiv = document.createElement("div");
mainDiv.style.width = "500px";
mainDiv.style.height = "500px";
document.body.appendChild(mainDiv);

const div1 = document.createElement("div");
div1.style.position = "absolute";
div1.style.top = `${50}px`;
div1.style.left = `${50}px`;
div1.style.width = "100px";
div1.style.height = "100px";
div1.style.background = "red";
mainDiv.appendChild(div1);

const div2 = document.createElement("div");
div2.style.top = `${250}px`;
div2.style.left = `${250}px`;
div2.style.width = "100px";
div2.style.height = "100px";
div2.style.background = "green";
div2.style.position = "absolute";
mainDiv.appendChild(div2);

mainDiv.onmousedown = function(event) {
  function onMouseMove(event) {
    //add divs to selection
  }
  mainDiv.addEventListener('mousemove', onMouseMove);

  mainDiv.onmouseup = function() {
    console.log("selected divs")
  }
}





Answer:
You can solve this by keeping an array of selected items and pushing items to it when the mouse moves over the items if the mouse is depressed.


const mainDiv = document.createElement("div");
mainDiv.style.width = "500px";
mainDiv.style.height = "500px";
document.body.appendChild(mainDiv);

const div1 = document.createElement("div");
div1.style.position = "absolute";
div1.style.top = `${50}px`;
div1.style.left = `${50}px`;
div1.style.width = "100px";
div1.style.height = "100px";
div1.style.background = "red";
mainDiv.appendChild(div1);

const div2 = document.createElement("div");
div2.style.top = `${250}px`;
div2.style.left = `${250}px`;
div2.style.width = "100px";
div2.style.height = "100px";
div2.style.background = "green";
div2.style.position = "absolute";
mainDiv.appendChild(div2);


!(() => {
  let selection = [];
  let selecting = false;
  function beginSelection(e) {
    selection = [];
    selecting = true;
    checkSelection(e);
  }
  function mouseMove(e) {
    checkSelection(e);
  }
  function mouseUp(e) {
    selecting = false;
    if (selection.length) {
      console.log("selection: ", selection); // access selection before reset
      selection = [];
    } else {
      // no selection
    }
  }
  function checkSelection(e) {
    if (!selecting) {
      return; // ignore
    }
    const selected = e.target.parentNode === mainDiv && e.target;
    if (selected && !selection.includes(selected)) {
      selection.push(selected);
    }
  }
  mainDiv.addEventListener("mousedown", beginSelection);
  mainDiv.addEventListener("mousemove", mouseMove);
  window.addEventListener("mouseup", mouseUp);
  
})();
Question: Delete all the lines including and after nth occurance of pattern

Basically what the title says, I have some large tsv file (approx. 20k lines) and I want to delete the rest of the files after a specific column matches a string a second time (including said line)


Answer:
awk '{print $0} $1=="yourstring"{if(++found==2)exit}' test.tsv

Where $1 is the "specific column" and yourstring is the string you are searching for.
This prints each line and then checks for the occurrence of yourstring in the first column. If it finds it, it tests a variable found which we increment, to see if it hits 2. If so awk exits.
Edit: If instead you want to delete the second occurrence (as well as everything after), flipping the two blocks around will accomplish this:
 awk ' $1=="yourstring"{if(++found==2)exit}{print $0}' test.tsv
Question: Is it possible to merge two tables in Power Query Editor (Power BI) with Python fuzzy matching?

Merge two tables in power query editor (Power BI) based on string similarity with Python
Consider the tables bellow:
Table1
Table1




Name
...




Apple Fruit A11
...


Banana Fruit B12
...


...
...




Table2
Table2




Name
Value




Apple A11R/T
40


B4n4n4 Fruit B12_T
50


Berry A11
60


...
...




I want to get the Value from Table2 into Table1. But for some reason when I use the built-in power query editor merge with fuzzy matching. It will match Apple Fruit A11 with Berry A11 instead of Apple A11 R/T. I've read the documentation, and it says that the built-in function works best with single words. I tried to remove spaces both from Table1[Name] and Table2[Name] but it didn't improve results.
I looked around trying to find a solution, but wasn't able to figure out yet. Is there a way to do this using python? Or is there a simpler solution?
The results that I am expecting:
Table1
Expected Result




Name
...
Table2.Name
Table2.Value




Apple Fruit A11
...
Apple A11R/T
40


Banana Fruit B12
...
B4n4n4 Fruit B12_T
50


...
...
...
...




--- For some reason the tables are not showing up like the preview, that's why there are also images for each table. Disclaimer: The data present in the tables above is just an example of the pattern of the data that I am working with. And fuzzy matching will probably give the right results for the example data.


Answer:
Fuzzy matching in Power Query works fine for me.

Set your options to the following:
Question: How can I modify my C code to replace words in a file without user input?

/**
 * C program to find and replace all occurrences of a word in file.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1000

/* Function declaration */
void replaceAll(char *str, const char *oldWord, const char *newWord);


int main()
{
/* File pointer to hold reference of input file */
FILE * fPtr;
FILE * fTemp;
char path[100];

char buffer[BUFFER_SIZE];
char oldWord[100], newWord[100];


printf("Enter path of source file: ");
scanf("%s", path);

printf("Enter word to replace: ");
scanf("%s", oldWord);

printf("Replace '%s' with: ");
scanf("%s", newWord);


/*  Open all required files */
fPtr  = fopen(path, "r");
fTemp = fopen("replace.tmp", "w"); 

/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
    /* Unable to open file hence exit */
    printf("\nUnable to open file.\n");
    printf("Please check whether file exists and you have read/write privilege.\n");
    exit(EXIT_SUCCESS);
}


/*
 * Read line from source file and write to destination 
 * file after replacing given word.
 */
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
    // Replace all occurrence of word from current line
    replaceAll(buffer, oldWord, newWord);

    // After replacing write it to temp file.
    fputs(buffer, fTemp);
}


/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);


/* Delete original source file */
remove(path);

/* Rename temp file as original file */
rename("replace.tmp", path);

printf("\nSuccessfully replaced all occurrences of '%s' with '%s'.", oldWord, newWord);

return 0;
}



/**
 * Replace all occurrences of a given a word in string.
 */
void replaceAll(char *str, const char *oldWord, const char *newWord)
{
char *pos, temp[BUFFER_SIZE];
int index = 0;
int owlen;

owlen = strlen(oldWord);

// Fix: If oldWord and newWord are same it goes to infinite loop
if (!strcmp(oldWord, newWord)) {
    return;
}


/*
 * Repeat till all occurrences are replaced. 
 */
while ((pos = strstr(str, oldWord)) != NULL)
{
    // Backup current line
    strcpy(temp, str);

    // Index of current found word
    index = pos - str;

    // Terminate str after word found index
    str[index] = '\0';

    // Concatenate str with new word 
    strcat(str, newWord);
    
    // Concatenate str with remaining words after 
    // oldword found index.
    strcat(str, temp + index + owlen);
}
}

I have that code in C which can change all "oldWords" into "newWords". Works fine, but everytime I want to change the code to change the words on its own I'm completely stupid. I want that I don't have to put the words that have to change into the console, but I want to have them in the code. I just want to tell the console the path of the source file and that's it.
Would be nice if you could help me with some examples like Hello to Bye and Morning to Night.


Answer:
If you don't want to take oldWord and newWord from user input, you can define them as constants in the code:
const char* oldWord = "Hello";
const char* newWord = "Bye";
Question: I want to set new object in local storage

function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');
    
    let notesObj = []

    let myObj = {
        title: givenTitle.value,
        note: givenNote.value,
    }

    notesObj.push(myObj)

    localStorage.setItem('userNote',JSON.stringify(notesObj));
}

This code is everyTime changing the older value I want to get a new object in local storage


Answer:
Probably you want to add note into your existing localStorage data so here you can check if there is userNote is already set before then take it or set an empty array,
let notesObj = JSON.parse(localStorage.getItem("userNote")) || []

Your whole function would be like this,
function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');
    
    let notesObj = JSON.parse(localStorage.getItem("userNote")) || []

    let myObj = {
        title: givenTitle.value,
        note: givenNote.value,
    }

    notesObj.push(myObj)

    localStorage.setItem('userNote',JSON.stringify(notesObj));
}
Question: Trying to assign a response.data value to a variable in react and the value doesnt pass well

Im building an AuthContext in react to handle login, i connect it to a django backend where i validate the user and then i get an authorization token
import React, { createContext, useState, useEffect} from 'react';
import axios from 'axios';

export const AuthContext = createContext();


  export const AuthProvider = ({ children }) => {
    const [token, setToken] = useState(null);
  
    const login = async (username, password) => {
      try {
        const response = await axios.post('http://127.0.0.1:8000/token/', {
          username,
          password
        });
        console.log('Response data:', response.data);
        const { token: responseToken } = response.data;
        setToken(responseToken);
    
        console.log('Token loaded:', responseToken);
      } catch (error) {
        console.error('Error en el inicio de sesión:', error);
      }
    };    
  
    useEffect(() => {
      console.log('Token actual value:', token); 
    }, [token]);
  
    return (
      <AuthContext.Provider value={{ token, login }}>
        {children}
      </AuthContext.Provider>
    );
  };


From my backend i get the expected answer, an status 200 with the token that i expect, but after assign the response.data to responseToken, in the next log it shows that is undefined. Here is the output in the navigator console:
console logs
Tried to change the variable names to check if there is a conflict between those declared there, but the problem persists.


Answer:
Your console log shows that response data has two properties refresh & access. But you are trying to get a property called token, which does not exist (or at least it's not visible in your screenshot).
const { access: responseToken } = response.data;

This should help. (if access is the one you actually need)
Question: ReactJs why do i get two console logs in a simple component?

i have this simple nav component, but it drives me crazy because it makes every console log i make in the app two times.
Im new to React btw.
export const NavBar = () => {
  const [showNav, setShowNav] = useState(false);

  const handleNavClick = () => {
    setShowNav(!showNav);
  };

  console.log("hi");

  return (
    <>
      <nav className="flex items-center justify-between pl-8 pr-16 fixed w-full border h-20 top-0 bg-white/30 backdrop-blur-sm z-10">
        {/* Logo */}
        <img
          src="https://res.cloudinary.com/dv8nczwtj/image/upload/v1684896617/Logo_jivlnb.png"
          alt="Logo"
          className="logo"
        />
        {/* Nav WEB*/}
        <div className="md:flex flex-row space-x-5 hidden">
          <a href="#" className="brand">
            Apple
          </a>
          <a href="#" className="brand">
            Samsung
          </a>
          <a href="#" className="brand">
            Xiaomi
          </a>
          <a href="#" className="brand">
            Google
          </a>
        </div>
        {/* BTN Nav Mobil */}
        <button className="md:hidden" onClick={handleNavClick}>
          <img
            src="https://res.cloudinary.com/dv8nczwtj/image/upload/v1684859901/menu_wh8ccz.png"
            alt="Menu"
            className="w-6"
          />
        </button>
        {/* Cart */}
        <CartWidget />
      </nav>
      {/* Nav Mobil */}
      {showNav && (
        <div
          className="flex fixed w-full flex-col justify-center items-center space-y-4 pb-2 border-b-2 border-black md:hidden bg-white/30 top-20 pt-4 backdrop-blur-sm"
          style={{ animation: "fadeIn .5s linear" }}
        >
          <a href="#" className="brand">
            Apple
          </a>
          <a href="#" className="brand">
            Samsung
          </a>
          <a href="#" className="brand">
            Xiaomi
          </a>
          <a href="#" className="brand">
            Google
          </a>
        </div>
      )}
    </>
  );
};

double console.log
I have tried putting the handleClick function in a useEffect but then when i put it on the onClick it says that the function is never declared


Answer:
Is your app using React.StrictMode (https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-double-rendering-in-development) ?
Question: Bash if statement expression evaluates to FALSE but $? is 0, why?

The example below echoes 1, as expected:
test -f /usr/bin
echo "$?" #1

Why does the following example echo 0?
if [[ -f /usr/bin ]]; then
    echo "Inside if statement" # This line is never executed    
fi
echo "$?" #0

I know that the $?evaluates to the returned value of the last executed command. In my understanding, the last executed command is test, that is implicitly called by the if statement, since the condition evaluates to false it should return 1, but when I execute it, it returns 0. Can anybody explain why the behavior is different than when test is executed directly (like in the first example)?


Answer:
According to man bash:


if list; then list; [ elif list; then list; ] ... [ else list; ] fi
The if list is executed.  If its exit status is zero, the then list is  executed.   Otherwise,  each  elif list  is executed in turn, and if its exit status is zero, the corresponding then list is executed and the
command completes.  Otherwise, the else list is executed, if present.  The exit status is the exit  status
of the last command executed, or zero if no condition tested true.
Question: How can I convert a left table into a summary table?

How do I convert table left to summary table right?

I tried using get dummies function to convert values to 0 and 1.
I don't know how to proceed after that.


Answer:
Try this:
import pandas as pd
import numpy as np
col1 = ['']+['Hampshire']*8+['']+['Hampshire']+['']+['Hampshire']+['','']+['Hampshire']*4
col2 = ['Southhampton'] + ['']*12 + ['Southhampton']*2 + ['']*4
col3 = ['']*11 + ['Isle of wight'] + ['']*7
col4 = ['Met']*5 + [''] + ['Met']*13
col5 = ['']*5 + ['Partially met'] + ['']*13
col6 = ['']*19

df = pd.DataFrame(data = dict(zip(['Hampshire', 'Southhampton', 'Isle of wight', '5met', '5partially met', '5Not met'],[col1,col2,col3,col4,col5,col6])))
df = df.replace('', np.nan)
df['Hampshire'] = df['Hampshire'].fillna(df['Southhampton'])
df['Hampshire'] = df['Hampshire'].fillna(df['Isle of wight'])
df[['Hampshire','5met','5partially met', '5Not met']].groupby(by=['Hampshire']).count()

I had to generate the data for you (since you didn't post any besides the image), but I think this get's the job done. I hope this helps.
Question: Is there a way to use onSchedule and also set a custom 'timeoutSeconds' and 'memory' using Firebase functions V2?

I have had to revert back to using Firebase functions V1 in order to schedule the running of my functions and also specify the runtime options including timeoutSeconds and memory in my code (written in TypeScript):
const runtimeOpts = {
    timeoutSeconds: 540,
    memory: "1GB" as const,
};
exports.cleanupEvents = functions
    .runWith(runtimeOpts)
    .pubsub.schedule("0 0 * * *")
    .timeZone("Europe/Berlin")
    .onRun(async () => {
        await cleanupOldEvents(adminDb);
        logger.log("Event cleanup finished");
    });


Does anyone know if it is possible with Firebase functions V2 using the onSchedule syntax to also specify these runtimeOpts in code? Without needing to go into the google cloud console and manually setting it there.
I have tried chaining'onSchedule' and 'runWith' together and seeing what other possibilities Emmet suggests, so far but had no luck.


Answer:
The API documentation for onSchedule suggests that you can pass an object as the first parameter, which is a ScheduleOptions object, an extension of GlobalOptions:
onSchedule({
    schedule: "your-schedule-here",
    timeoutSeconds: your-timeout,
    memory: your-memory,
    // include other options here from SchedulerOptions or GlobalOptions
}, (event) => { ... })