satoshi-2000/llms-suitable huggingface dataset:
Question: Extract href from string and again bind the updated data to the element in Angular

I am getting one string like this in innerHtml
<div class="wrapper" [innerHTML]="data.testString">

data.testString contains data like below,
data.testString="<p>some info, email <a href="mailto:test@test.com">test@test.com</a>  info </p>";

I want to add aria-label for the anchor tag.
<a aria-label="test@test.com" href="mailto:test@test.com">test@test.com</a>

so I have added below code in .ts file
ngAfterViewInit(): void {

    var myData = this.data.testString;
    var element = myData!.match!(/href="([^"]*)/)![1];
    
   
    var ariaLabel = "EmailId " + element;
    
    this.data.testString=
    this.data.testString!.replace('<a', '<a aria-label = "' + ariaLabel + '" ');
      
  }
}


But I am getting below error
global-error-handler.ts:26 TypeError: Cannot assign to read only property 'testString' of object '[object Object]'

How to resolve this?


Answer:
I'm not sure to understand all but below might help you :

String character escaping


var testString="<p>some info, email <a href="mailto:test@test.com">test@test.com</a>  info </p>";

There is a quote issue : a double-quoted string cannot contain double-quotes unless escaped by the \ character (cf. https://www.w3schools.com/js/js_strings.asp -> Escape Character section)
You may fix this issue by replacing some double quotes by simple quotes :
"<p>some info, email <a href='mailto:test@test.com'>test@test.com</a>  info </p>"

Regular expression


var href = datar!.match!(/href="([^"]*)/)![1];

Not sure this is the pattern you need. Try instead :
var href = datar!.match!(/href=\'mailto:([a-z@.]+)'/)![1];

DOM element manipulation

About adding the aria-label attribute to the , you would better go with Angular nativeElement.setAttribute(key, value) native javascript querySelector
(cf. https://indepth.dev/posts/1336/how-to-do-dom-manipulation-properly-in-angular and https://angular.io/guide/property-binding)
Finally I would highly recommend the use of RegExr to test your regular expressions https://regexr.com/7ep0u
as well as jsfiddle.net to test your javascript in a safe environment : https://jsfiddle.net/nkarfgx3/
Question: intersection across date ranges from multiple rows in oracle

Intersection of date ranges across rows in oracle.
I have a table which contains following records




Item_no
item_type
active_from
active_to
rule_id




10001
SAR
2020-01-01
2023-01-01
rule1


10001
SAR.
2024-01-01
9999-12-31
rule1


10001
SAR
2020-05-01
2021-06-01
rule2


10001
SAR
2021-01-01
2021-02-01
rule2




We need to find common dates between rule ids
Output will be




Item_no
item_type
active_from
active_to




10001
SAR
2020-05-01
2021-06-01




I tried with connect by level to generate dates and then take intersection, but it is running for long time due to 9999-12-31


Answer:
From Oracle 12, you can UNPIVOT the dates and then use analytic functions and MATCH_RECOGNIZE to process the result set row-by-row to find the consecutive rows where both rules are active:
SELECT *
FROM   (
  SELECT item_no,
         item_type,
         rule_id,
         dt,
         SUM(CASE rule_id WHEN 'rule1' THEN active END) OVER (
           PARTITION BY item_no, item_type ORDER BY dt, ACTIVE DESC
         ) AS rule1,
         SUM(CASE rule_id WHEN 'rule2' THEN active END) OVER (
           PARTITION BY item_no, item_type ORDER BY dt, ACTIVE DESC
         ) AS rule2
  FROM   table_name
         UNPIVOT (
           dt FOR active IN ( active_from AS 1, active_to AS -1 )
         )
)
MATCH_RECOGNIZE(
  PARTITION BY item_no, item_type
  ORDER BY dt, rule1 DESC, rule2 DESC
  MEASURES
    FIRST(dt) AS active_from,
    NEXT(dt) AS active_to
  PATTERN ( active_rules+ )
  DEFINE active_rules AS rule1 > 0 AND rule2 > 0
)

Which, for the sample data:
CREATE TABLE table_name (Item_no, item_type, active_from, active_to, rule_id) AS
SELECT 10001, 'SAR', DATE '2020-01-01', DATE '2023-01-01', 'rule1' FROM DUAL UNION ALL
SELECT 10001, 'SAR', DATE '2024-01-01', DATE '9999-12-31', 'rule1' FROM DUAL UNION ALL
SELECT 10001, 'SAR', DATE '2020-05-01', DATE '2021-06-01', 'rule2' FROM DUAL UNION ALL
SELECT 10001, 'SAR', DATE '2021-01-01', DATE '2021-02-01', 'rule2' FROM DUAL;

Outputs:




ITEM_NO
ITEM_TYPE
ACTIVE_FROM
ACTIVE_TO




10001
SAR
2020-05-01 00:00:00
2021-06-01 00:00:00




and for:
CREATE TABLE table_name (Item_no, item_type, active_from, active_to, rule_id) AS
SELECT 10001, 'SPR', DATE '2023-01-01', DATE '2023-01-31', 'rule1' FROM DUAL UNION ALL
SELECT 10001, 'SPR', DATE '2023-01-31', DATE '2023-02-27', 'rule2' FROM DUAL;

The output is:




ITEM_NO
ITEM_TYPE
ACTIVE_FROM
ACTIVE_TO




10001
SPR
2023-01-31 00:00:00
2023-01-31 00:00:00




fiddle
Question: How to make an Array of images getting by input field and display the Array image as slider

My problem is to make array of image by input field and display array images as slider in JavaScript
anyone can solve it please answer me
Please give code of JavaScript
    document.querySelector("#a").addEventListener("change", function(){
           const reader = new FileReader();
              reader.addEventListener("load", ()=>{
                   localStorage.setItem("recent-image", reader.result)
              });
           reader.readAsDataURL(this.files[0]);
    });
    document.addEventListener("DOMContentLoaded()", ()=> {
        
        const imageurl = localStorage.getItem("recent-image");

        if(imageurl){
            document.querySelector("#b").setAttribute("src", imageurl);
        }
    });

can you do this in array please answer me
it take only one image image but, I want to store multiple image in local storage by array
please answer me


Answer:
The problem that I see is to define your localstorage and make sure that the images are stored in it to later go through each one of them, I leave an example of how to solve it
var images = localStorage.getItem('images') || [];

function saveImages() {
    localStorage.setItem('images', JSON.stringify(images));
}

function drawImages() {
    var slider = document.getElementById('slider');
    slider.innerHTML = '';
    for (var i = 0; i < images.length; i++) {
        const img = images[i];
        const html_img = document.createElement('img');
        html_img.src = img;
        html_img.alt = 'Alt img';
        html_img.width = 200;
        html_img.height = 150;
        slider.appendChild(html_img);
    }
}

document.querySelector("#a").addEventListener("change", function(){
    const reader = new FileReader();
    reader.addEventListener("load", ()=>{
        images.push(reader.result);
        drawImages();
    });
    reader.readAsDataURL(this.files[0]);
});

document.addEventListener("DOMContentLoaded()", drawImages);
Question: Passing a prop/variable to react router 6 loader function

My routes are working and accessing components and loader functions. I'm trying now to pass variable filmsPerPage (which is defined once) to both Home component and the loader function in
App.js:
const App = () => { 
  const filmsPerPage = 12
    
  const router = createBrowserRouter([
    {
      path: '/',
      children: [
        {
          index: true,
          element: <Home {...{filmsPerPage}} />,
          loader: () => { loaderHome(filmsPerPage) }
        },
        .................

Home.js:
const Home = (props) => {
  const { loaderData } = useLoaderData() // get loader data --> null
  console.log(props.filmsPerPage) // printing out correctly: 12
  .......
}
    
export default Home;
    
export function loaderHome(filmsPerPage) {
  console.log(filmsPerPage) --> printing out 12
  return defer({
    loaderData: loadPosts(null, 1, 12, null)
  })
}

The prop filmsPerPage is passing correctly to Home.js component and while it's passing to the loader function, the useLoaderData() in Home.js is returning null which means that although the code in the loader function is working properly, it's not returning a loader object to the component. If I do this in App.js, the useLoaderData() function (in Home.js) will get the data but now the loader function doesn't have the prop:
children: [
  {
    index: true,
    element: <Home {...{filmsPerPage}} />,
    loader: loaderHome
  },

How could I pass the filmsPerPage prop to the loader function which will then return loader data to Home.js?


Answer:
The loader function isn't returning anything. Perhaps reformatted to a more readable format will make this more apparent:
{
  index: true,
  element: <Home {...{filmsPerPage}} />,
  loader: () => {
    loaderHome(filmsPerPage); // <-- not returned!!
  },
}

The loader should still return the result of calling loaderHome.
Examples:
{
  index: true,
  element: <Home {...{filmsPerPage}} />,
  loader: () => {
    return loaderHome(filmsPerPage); // <-- explicit return in function block
  },
}

{
  index: true,
  element: <Home {...{filmsPerPage}} />,
  loader: () => loaderHome(filmsPerPage), // <-- implicit arrow function return
}

You could even rewrite loaderHome to curry, e.g. close over in function scope, the filmsPerPage argument.
export function loaderHome(filmsPerPage) {
  console.log(filmsPerPage); --> printing out 12

  // Return loader function
  return (loaderArgs) => {
    return defer({
      loaderData:  loadPosts(null, 1, filmsPerPage, null);
    });
  };
}

{
  index: true,
  element: <Home {...{filmsPerPage}} />,
  loader: loaderHome(filmsPerPage),
}
Question: Adding new column for different rows based on the values present in the same row for a different column

I have a dataframe with different combination of factors. each factor is presented in its column (see below)
F1   F2   F3   F4
1     1
1          1  
1                1

I want to add a new column at the end like below
F1   F2   F3   F4  trt
1    1             F1_F2
1          1       F1_F3
1               1  F1_F4

How do I create this column with conditional merging in R. Any advice would be appreciated!


Answer:
aggregate(ind~row, na.omit(cbind(row = c(row(df)), stack(df))), paste, collapse = "_")
  row   ind
1   1 F1_F2
2   2 F1_F3
3   3 F1_F4


df <- structure(list(F1 = c(1L, 1L, 1L), F2 = c(1L, NA, NA), F3 = c(NA, 
1L, NA), F4 = c(NA, NA, 1L)), class = "data.frame", row.names = c(NA, 
-3L))
Question: why my basic terraform fails to run terraform plan?

I have this very basic terraform file: main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
    profile = "default"
}

resource "aws_s3_bucket" "test-bucket-terraform-regergjegreg" {
  bucket = "test-bucket-terraform-regergjegreg"

  tags = {
    Name        = "My bucket"
    Environment = "Dev"
  }
}

when doing terraform validate, I have no error:
Success! The configuration is valid.
Now when I do terraform plan, I got this error:
Planning failed. Terraform encountered an error while generating this plan.

╷
│ Error: configuring Terraform AWS Provider: credential type source_profile requires role_arn, profile default
│ 
│   with provider["registry.terraform.io/hashicorp/aws"],
│   on main.tf line 12, in provider "aws":
│   12: provider "aws" {
│ 
╵

Here is my terraform version:
Terraform v1.4.6
on darwin_amd64
+ provider registry.terraform.io/hashicorp/aws v3.76.1

the default profile exists in my /.aws/credentials and /.aws/config
Not sure what could be wrong really. Any help is appreciated. thanks


Answer:
Ok, I resolved the issue.
My problem was not in credentials file but in config.
For some reason I had this:
[default]
output = json
region = eu-west-1
source_profile = default

removing source_profile makes it work.
Question: How to visualize formatted text without removing empty space?

I want to visualize a pre-formatted text (with YAML format and indent). It seems that the <|{text}|> markdown pattern and the state representation removes intents from the text, i.e. all becomes a long mashed text. Here is an example output.
version: '3.1' stories: - story: 06a6e2c5e8bd4058b304b4f23d57aa80 steps: - intent: bot_capabilities user: What can you do

Correct is this:
version: '3.1'
stories:
-   story: 06a6e2c5e8bd4058b304b4f23d57aa80
    steps:
    -   intent: bot_capabilities
        user: What can you do

Is there a way to keep preformatted text especially with indents?
I could not yet find a fitting property for the "text" control. Raw does not seem to solve the issue. If I print the string before assigning it to a state variable, the output format is correct. Therefore, I assume the stripping of empty space happens automatically afterwards.


Answer:
The most straightforward way is to use an input visual element with multiline property turned on.
main.py:
from taipy.gui import Gui 

#with open("file.yaml", "r") as f:
#    yaml_text = f.read()

yaml_text = """
version: '3.1'
stories:
-   story: loferum ipsi
    steps:
    -   intent: bot_capabilities
        user: What can you do
"""

page = """
<|{yaml_text}|input|multiline|label=Input|>

<|{yaml_text}|input|multiline|not active|label=Inactive input|>

<|{yaml_text}|input|multiline|not active|label=Inactive white input|id=yaml|>
"""

Gui(page).run()

Here is the result:

The first input is editable
The second is not editable and grey
The third is not editable and white


For the last element, I added a bit of CSS to make the inactive input white:
main.css:
#yaml.Mui-disabled{
    color: white !important;
    -webkit-text-fill-color: white !important;
}

An issue has been created on GitHub to improve text visual elements directly.
Question: How can I limit os.walk results for a single file?

I am trying to search a given directory for a specific file, and if that file does not exist I would want the code to say "File does not exist". Currently with os.walk I can get this to work, however this will hit on every single file that isn't the specified file and print "File dos not exist". I know that this is how os.walk functions, but I was not sure if there is a way to make it only print out once if it is found or not found.
Folder structure:
root folder|
|Project Folder
|file.xml
|other files/subfolders
How I would want the code to work is to go inside of "Project Folder", do a recursive search for "file.xml", and once it is found print out once "Found", otherwise prints out once "Not found".
The code is:
def check_file(x): #x = root folder dir
   for d in next(os.walk(x))[1]: #if I understand correctly, [1] will be Project Folder
        for root, directories, files in os.walk(x):
            for name in files:
                if "file.xml" not in name:
                    print("found")
                else:
                    print("File Missing")

If I change the code to
            for name in files:
                if "file.xml" in name:
                    print("found")
                else:
                    pass

The code technically works as intended, but it doesn't really do much to help point out if it isn't there, so this isn't a good solution. It would be easier if I was able to give the code a specific path to look in, however as the user is able to place the 'root folder' anywhere on their machine as well as the 'project folder' would have different names depending on the project, I don't think I would be able to give the code a specific location.
Is there a way to get this to work with os.walk, or would another method work best?


Answer:
The glob module is very convenient for this kind of wildcard-based recursive search. Particularly, the ** wildcard matches a directory tree of arbitrary depth, so you can find a file anywhere in the descendants of your root directory.
For example:
import glob

def check_file(x):  # where x is the root directory for the search
    files = glob.glob('**/file.xml', root_dir=x, recursive=True)
    if files:
        print(f"Found {len(files)} matching files")
    else:
        print("Did not find a matching file")
Question: ABAP ODATA Service implement custom GET or POST request

How can I implement a custom method to check if the user is exists by the given parameter in the url? So I want to make a GET request.


Answer:
Assumption: you are talking about ABAP implmentation of OData v2 with SEGW approach.
You are looking for a so called Function Import.
This allows you to define custom functions next to the predefined CRUDQ (Create, Read, Update, Delete, Query) functions. This custom function can have custom input parameters and return values as simple types or Complex Types (=Structures/Entities)
As stated also in SAP Help this should be only used if it does not fit into the CRUDQ methods for your entities.
Find an example implementation in this SAP Blog
For other approaches, e.g. RESTful ABAP Programming Model (RAP), it would be Actions and Validations but cannot generally be answered without details of the scenario.
Question: Why by calling new File(".").getAbsolutePath() I get completely different path from my project's location?

My project is located here:
D:/WorkSpace/PuzzleApp

but when I am calling
new File(".").getAbsolutePath();

I get:
D:\!Documents\Desktop\.

Why? And how to fix this?
I'm using Eclipse.


Answer:
When you open File with relative path "." this path is relative to the current process' working directory.
Usually, the process working directory is inherited from the parent process (e.g. if you run your app with Terminal - the current terminal's working directory will be your process' working dir).
Using a relative path inside your application is considered a bad idea because you can not control this process' working directory.
But using an absolute hardcoded path also goes with some problems and can't be called a good practice.
There are several ways to solve the issue:

Use a path relative to some NOT hardcoded absolute path. This absolute path should be externalized to environment variables, properties files, etc.

//Getting the directory path from the external system variable
String myAbsoultePath = System.getenv("LOCAL_STORAGE_DIR");


Use a path relative to your application root. It allows you to READ files even located inside .jar or .war archives.

//This path looks absolute, but the path's root is your project's root
InputStream stream = MyClass.class.getResourceAsStream("/dir/another/file.txt");

But you should understand, that your application won't run inside your IDE project folder. It will be deployed in a production server/user's desktop/android device environment and usually, it is packed in a jar/war/ear/... archive. It means that you won't have access to your src folder or something like this.
Question: How can I create a frequency plot/histogram in R using ggplot2 while normalizing to the total of a factor?

My problem is the following: I can make a figure in which the data is weighed relative to the entire population, but not relative to their own subpopulation. To illustrate with an example:
Suppose I have a dataset DS, with two columns: X and type.
X is a continues value ranging from -5 to 5, and type is either A, B or C.
How would I create a frequency plot of X in which each tuple is weighed by the total of its type, not the total of all tuples in the dataset?
This is my closest attempt, yet it weighs to the total population:
figure1 <- ggplot(data = DS, aes(x = X))+ geom_freqpoly(aes(colour = type, y= after_stat(count / sum(count)))) + ...
Its not surprising that this normalizes to the entire dataset, but I wouldnt know how to get it such that it only normalizes to a subset.
Using dput(), I generate the following example dataframe:
DS <- structure(list(X = c(0, -0.01, 0.042944432215413, 0.0431301011419889, 0.042944432215413, 0.0424042102083902, 0.2100000012 , 0.13513333335333), TimePoint = c("early", "early", "late", "mid", "mid", "early", "late", "early")), row.names = c(NA,8L), class = "data.frame")

In which 'X' is the continous value and 'TimePoint' is the factor which can be either 'early', 'mid' or late.


Answer:
One option would be to use e.g. ave() to compute the count per group or Timepoint:
library(ggplot2)

ggplot(data = DS, aes(x = X)) +
  geom_freqpoly(
    aes(
      colour = TimePoint,
      y = after_stat(count / ave(count, group, FUN = sum))
    )
  )
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Question: Powershell/CMD issue

So I was trying to write a quick Batch file but it only did half the code, so I switched it to PowerShell because I remembered a while back I was able to get it to work and turns out this did work.
My issue is essentially I have a handful of users I want to have access to this "it just closes a program and reopens". They're familiar with Batch files (which I couldn't get to reopen the program) but would not be used to using a PowerShell script and having to right click to run as PowerShell which I'm expecting will cause issues and many of the users to not use the script in the first place.
Is there either something I did wrong on the batch file for it not to reopen or is there a way to change the left click option on the PowerShell(currently left click opens the script in notepad; ideally it would just run as PowerShell on left click)
The code is the same for both PowerShell and CMD copied and pasted directly to.
taskkill /IM ADM.TrayApp.exe /F
Start-Process  "C:\Program Files (x86)\athenahealth, Inc\aNetDeviceManager\3.1.4.0\TrayApp\CoreModule\ADM.TrayApp.EXE"



Answer:

You cannot use PowerShell's Start-Process directly in a batch file - you'd have to call via powershell.exe, the Windows PowerShell CLI or pwsh, the PowerShell (Core) CLI).

However, as Stephan points out, cmd.exe's internal start command provides similar functionality, so its use should be sufficient in your case (as Stephan notes, some window title enclosed in "..." is needed as the first argument if the executable to launch is enclosed in "..." too; "" will do):
start "" "C:\Program Files (x86)\athenahealth, Inc\aNetDeviceManager\3.1.4.0\TrayApp\CoreModule\ADM.TrayApp.EXE"


It is possible to make PowerShell scripts execute by default when (double-)left-clicked from File Explorer or the desktop, but requires nontrivial setup on each machine:

See this answer.
The linked answer also describes an alternative technique of providing simple companion batch files whose sole purpose is to execute an associated PowerShell script.
Question: What is the best way to find text content under relatively indistinguishable tags by Selenium-webdriver?

As newbie I prefer use Abs XPath to get find WebElemnts where text is positioned.
I tried:
List<WebElement> elements = web.findElements(By.xpath("/html[1]/body[1]/div[2]/div[2]/dl[1]/dd[2]/div[2]/div/div[1]/ol[5]/li[1]/div[2]/div/p"));

But i failed to catch text under tags with minor changes
Target xpaths:
/html[1]/body[1]/div[2]/div[2]/dl[1]/dd[2]/div[2]/div[6]/div[1]/ol[5]/li[1]/div[2]/div[4]/div[1]/div[1]/p[1]
/html[1]/body[1]/div[2]/div[2]/dl[1]/dd[2]/div[2]/div[6]/div[1]/ol[5]/li[1]/div[2]/div[8]/p
/html[1]/body[1]/div[2]/div[2]/dl[1]/dd[2]/div[2]/div[2]/div[1]/ol[5]/li[1]/div[2]/div[3]/h3[1]
/html[1]/body[1]/div[2]/div[2]/dl[1]/dd[2]/div[2]/div[2]/div[1]/ol[5]/li[1]/div[2]/div[2]/div[1]/p
/html[1]/body[1]/div[2]/div[2]/dl[1]/dd[2]/div[2]/div[5]/div[1]/ol[5]/li[1]/div[2]/div[1]/div[1]/p[1]/strong[1]

What is correct formula or way to get all text content in the above mentioned xpaths ?


Answer:
Not very clear what you want: If you want all elements that contain direct text you could use:
/html/body[1]//*[text()[normalize-space()]]

this will return all elements with direct text()-nodes that after filtering unnecessary whitespace, have character-data.
meaning XPath-parts:
// = any descendant; see this info on axes
* = any element
[some filter] = predicate to filter on direct previous node.
[#number] = the position within its siblings. body[1] maybe seems redundant, but can help the XPath-engine not to look any further for other body elements
text() = node of type text
normalize-space() = strips white-space according this rules