satoshi-2000/llms-suitable huggingface dataset:
Question: Error encountered when trying to plot individual trees from cforest() forest using the partykit package in R

I am doing conditional inference tree analysis using the partykit package in R. I want to plot any tree that is extracted from the forest grown by cforest(). But I got an error message when I am trying with the plot function. The following is a chunk of codes that may produce the like error message with the iris data.
Code:
library(partykit)

cf <- cforest(Species ~., data=iris)
tr <- gettree(cf, tree=1)
plot(tr)

Errors in console:

Error in Summary.factor(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, :
‘min’ not meaningful for factors

I am expecting plots for individual trees in the cforest() result.


Answer:
I have got an answer after researching into it.
Since plot works well with ctree() objects, I compared the extracted tree from cforest and the tree generated by ctree() and found the following difference in their data structure.
For ctree object, which can be plotted:
$ fitted:'data.frame':  150 obs. of  3 variables:
  ..$ (fitted)  : int [1:150] 2 2 2 2 2 2 2 2 2 2 ...
  ..$ (weights) : num [1:150] 1 1 1 1 1 1 1 1 1 1 ...
  ..$ (response): Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

but for a tree from cforest() result, which cannot be plotted:
$ fitted:'data.frame':  150 obs. of  4 variables:
  ..$ idx       : int [1:150] 1 2 3 4 5 6 7 8 9 10 ...
  ..$ (response): Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ (weights) : int [1:150] 0 1 1 1 1 1 1 1 0 0 ...
  ..$ (fitted)  : int [1:150] 2 2 2 2 2 2 2 2 2 2 ...

Please note that the variables (response), (weights) and (fitted) are in different columns in the data structure of "fitted" dataframe in these two trees.
Therefore, I use the following manipulation to adjust the "fitted" dataframe structure in the cforest tree object, and plotting is successful:
library(partykit)
cf <- cforest(Species ~., data=iris)
tr <- gettree(cf, tree=1)
nfitted <- data.frame(tr$fitted$`(fitted)`,tr$fitted$`(weights)`,tr$fitted$`(response)`)
colnames(nfitted) <- c('(fitted)', '(weights)', '(response)')
tr$fitted <- nfitted
plot(tr)

Hope this will help those who encounter the same problem with the plotting of trees from cforest() in the partykit package.
Question: SQL ORDER BY next

Please tell me how to sort in PostgreSQL (15+) such a table:
id |  name  | next_id
1  | Test01 |  2
2  | Test02 |  3
3  | Test03 |  6
4  | Test04 |  5
5  | Test05 |  null
6  | Test06 |  4
7  | Test07 |  null

It takes an SQL query to order by the next_id column - it's a pointer to the next row. The result I expect is:
id |  name  | next_id
1  | Test01 |  2
2  | Test02 |  3
3  | Test03 |  6
6  | Test06 |  4
4  | Test04 |  5
5  | Test05 |  null
7  | Test07 |  null

It is necessary to read the next_id field for each record, find this record and display it after the existing one. After all, this field can change, so sorting in ascending order will not work and other tricks.
So far, there are no ideas how to do it gracefully. Except for loops and temporary tables.


Answer:
The following demonstrates an approach to sorting as requested:
WITH RECURSIVE t(id, name, next_id) AS (
  VALUES (1  , 'Test01',   2),
         (2  , 'Test02',   3),
         (3  , 'Test03',   6),
         (4  , 'Test04',   5),
         (5  , 'Test05',   NULL),
         (6  , 'Test06',   4),
         (7  , 'Test07',   NULL)),
cte AS (
  SELECT t.id, t.name, t.next_id, t.id AS root_id, 1 AS depth
    FROM t
   WHERE NOT EXISTS (SELECT * FROM t t2 WHERE t.id = t2.next_id)
  UNION ALL
  SELECT t.id, t.name, t.next_id, cte.root_id, cte.depth + 1 AS depth
    FROM t
    JOIN cte ON (t.id = cte.next_id))
SELECT cte.id, cte.name, cte.next_id
  FROM cte
 ORDER BY cte.root_id, cte.depth, cte.id;

This query assumes that there are no cycles in the path defined by next_id.
The query first initializes the recursive CTE by identifying the rows that are not referenced by any next_id, memoizing the root id, and initializing depth. The recursive portion of the CTE finds the rows referenced by these root rows and incrementing depth. The recursive part repeats using the rows discovered by the prior iteration until no rows are found.
The final step sorts by root_id, depth, and id. Including id in the sort is done to create a deterministic order for the case of ids with multiple next_ids (a tree structure instead of linear paths): it can be left out if only linear paths are allowed.
Question: Creating AWS Security Group for a range of ports in Terraform

I want to create the following AWS security group in Terraform, using Hashi Corp Language. In this configuration the second ingress rule contains the range of ports, but such a syntax is not supported by Terraform.
In current implementation Terraform treats port's range as the math expression and computes the difference which gives the negative value. If I close the port range in parenthesis it fails because it requires number format.
What is the appropriate way to create ingress rule for a large range of ports?
  resource "aws_security_group" "sg_nx" {
  name   = "sg_nx"
  vpc_id = aws_vpc.vpc.id
  ingress {
    from_port   = 4000
    to_port     = 4000
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 4011-4999
    to_port     = 4011-4999
    protocol    = "udp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Using list does not work either. I know Terraform allows dynamicly generated resources, how to implement it in this case?


Answer:
If you look at AWS docs https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules.html they support port range. The way to do it with terraform is:
from_port = 4011 and to_port = 4999
See also the terraform docs:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group#from_port
Question: Happend multiple .csv file from Drive Folder to Unique Sheet in Google

Hello to everyone guys!
I've got a problem with the code below; my purpose is to retrieve all the .csv file in a google drive folder and put them all in sequence in a specific sheet in Google.
The error code that it get is: "Exception: Cannot convert 'function () { [native code] }1' to int."
Could you please help me solving that issue?
Many thanks in advance
function happendCSV() {
  const folder = DriveApp.getFolderById("ID_Folder");
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet_Name");
  const files = folder.getFiles();
  while (files.hasNext()) {
    let file = files.next();
    //let fn = file.getName();
    let fileID = file.getId();
    let fileType = file.getMimeType();
    if (fileType === "text/csv") {
      let csvData = Utilities.parseCsv(file.getBlob().getDataAsString(), ",");
      sheet.getRange(sheet.getLastRow +1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
  }
}



Answer:
Modification points:

In your script, sheet.getLastRow  of sheet.getRange(sheet.getLastRow +1, 1, csvData.length, csvData[0].length).setValues(csvData); should be sheet.getLastRow(). I thought that this might be the reason for your current issue of Exception: Cannot convert 'function () { [native code] }1' to int..
In your situation, I thought that getFilesByType might be useful.
When setValues is used outside of the loop, the process cost becomes low a little.

When these points are reflected in your script, it becomes as follows.
Modified script:
function happendCSV() {
  const folder = DriveApp.getFolderById("ID_Folder");
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet_Name");
  const files = folder.getFilesByType(MimeType.CSV);
  let values = [];
  while (files.hasNext()) {
    let file = files.next();
    let csvData = Utilities.parseCsv(file.getBlob().getDataAsString(), ",");
    values = [...values, ...csvData];
    console.log(`Now: ${file.getName()}`); // For confirming the current processing file.
  }
  sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}

Note:

If your CSV data is large, Sheets API might be suitable instead of Spreadsheet service (SpreadsheetApp).

References:

getFilesByType(mimeType)
getLastRow()
Question: Get all appointments for the month (including recurring appointments that are scheduled in previous months)

I am having some issues getting all the appointments from specific month. Problem is with appointments that has been scheduled with recurring setting. Is there some way to get all appointments present in outlook calendar recurring and not recurring?
The best so far I was able to achieve is to check for is appointment.IsRecurring and if true I can get some parameters from recurrencePattern. However it seems to work only for appointments that has been set in this specific month with recurring parameter. If appointment with recurrence has been set earlier, then current code does not seem to work.
Is there some way to get just all the appointments from specific month?
private void GetAllItems(DateTime startDate, DateTime endDate)
{
  Outlook.Application outlookApp = new Outlook.Application();
  Outlook.NameSpace outlookNamespace = outlookApp.GetNamespace("MAPI");
  Outlook.MAPIFolder calendarFolder = outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
  Outlook.Items calendarItems = calendarFolder.Items;

  string restriction = $"[Start] >= '{startDate.ToShortDateString()}' AND [Start] <= '{endDate.ToShortDateString()}'";
  Outlook.Items filteredItems = calendarItems.Restrict(restriction);

  foreach (Outlook.AppointmentItem appointment in filteredItems)
  {
    DataModel dataModel = new DataModel
    {
      Subject = appointment.Subject,
    };
    this.Data.Add(dataModel);

    if (appointment.IsRecurring)
    {
      Outlook.RecurrencePattern recurrencePattern = appointment.GetRecurrencePattern();

      DataModel recurringDataModel = new DataModel
      {
        Subject = appointment.Subject,
      };
      this.Data.Add(recurringDataModel);
    }
  }
}



Answer:
You are almost there - you need to set the Items.IncludeRecurrences property to true and call Items.Sort on the Start property to tell Items.Restrict to expand the recurrences. See https://learn.microsoft.com/en-us/office/vba/api/outlook.items.includerecurrences for more details and an example
  Outlook.Items calendarItems = calendarFolder.Items;
  calendarItems.Sort("[Start]");
  calendarItems.IncludeRecurrences = true;
  string restriction = $"[Start] >= '{startDate.ToShortDateString()}' AND [Start] <= '{endDate.ToShortDateString()}'";
  Outlook.Items filteredItems = calendarItems.Restrict(restriction);
Question: React Router DOM: Custom Route component not working

My application in total has 5 routes, out of these 5 for four of them I need a condition to be true first to let user access those routes. So I wanted to create checks for said routes.
I made PublicRoute and PrivateRoute Components
import { Route } from 'react-router-dom';


const PublicRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props) => <Component {...props} />} />
);  

export default PublicRoute

import { Route, Redirect } from 'react-router-dom';

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to="/" />
      )
    }
  />
);

export default PrivateRoute

And my app.js
import { Routes } from "react-router-dom"
import PublicRoute from "./components/PublicRoute"

const App = () => {
  return (
    <>
      <Routes>

        <PublicRoute
          exact
          path="/"
          component={Com}
        />

      </Routes>
    </>
  )
}

export default App

const Com=()=>(
  <>
  <h1>Hi</h1>
  </>
)

And currently I am getting this error
 not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
    at invariant (history.ts:48

Given I am returning a Route Component I can't quite understand why this error pops up. Eventually I want a way to perform checks and keep code clean, If there's another efficient way please let me know!


Answer:
The Routes component needs a literal Route component as the child.
This worked for me -
PublicRoute
import { Route } from "react-router-dom";

const PublicRoute = ({ component: Component, ...rest }) => (
  <Component {...rest} />
);

export default PublicRoute;


App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import PublicRoute from "./PublicRoute";

const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          exact
          path="/"
          element={
            <PublicRoute component={Com} msg={"there"} person={"sandy"} />
          }
        />
      </Routes>
    </BrowserRouter>
  );
};

export default App;

const Com = ({ msg, person }) => (
  <>
    <h1>
      Hi {msg} {person}
    </h1>
  </>
);
Question: Cypress - How to check if a checkbox is checked or not?

I have some code below to check if a checkbox is checked or not. Even if the checkbox is checked, it says that its not. Why does the code fail and how to fix it?
function isChecked(locator : string) : boolean {
 let checked : boolean = false;
 cy.get(locator).then(el){
  if(el.val() === "on"){
   checked = true;//Is actually true when element is checked.
  }
 }
 return checked;//Is actually false when element is checked.
}



Answer:
function isChecked(locator) : Promise<boolean>{
  return new Cypress.Promise((resolve) => {
    cy.get(locator).then((el) => {
      resolve(el.prop('checked'));
    });
  });
}

isChecked('#myCheckbox').then((checked) => {
  if (checked) {
    // Checkbox is checked
  } else {
    // Checkbox is not checked
  }
});
Question: Query to find difference between today and yesterday's data along with a pseudo column

There is a table that stores account data for everyday. I want to find out the difference in data between today and yesterday. The query for table creation and insert statements are below :
CREATE TABLE daily_account_data (id varchar(6), Name varchar (20), DS_DW_Id varchar(4), flag_1 varchar(5), flag_2 varchar(5), Insert_date date );

INSERT INTO daily_account_data VALUES('A01R11', 'Gene Graham',      'PT12', 'TRUE', 'FALSE', '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R16', 'Molly Ringwald',   'PT15', 'TRUE', 'TRUE',  '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R19', 'John Doe',         'PT24', 'FALSE','TRUE',  '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R34', 'Jane Doe',         'PT26', 'TRUE', 'FALSE', '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R11', 'Gene Wilder',      'PT12', 'TRUE', 'FALSE', '2023-06-02');
INSERT INTO daily_account_data VALUES('A01R16', 'Molly Ringwald',   'PT15', 'TRUE', 'TRUE',  '2023-06-02');
INSERT INTO daily_account_data VALUES('A01R19', 'John Doe',         'PT24', 'TRUE', 'TRUE',  '2023-06-02');
INSERT INTO daily_account_data VALUES('A01R34', 'Jane Doe',         'PT26', 'TRUE', 'FALSE', '2023-06-02');

I have the query to find the difference in the data of the 2 days.
SELECT id, name, DS_DW_Id, flag_1, flag_2 FROM daily_account_data WHERE Insert_date = '2023-06-02'
EXCEPT
SELECT id, name, DS_DW_Id, flag_1, flag_2 FROM daily_account_data WHERE Insert_date = '2023-06-01';

But I can't figure out to get the data in the pseudo column. The last column is changed data. On 1st June data the name of the id A01R11 is Gene Graham and on 2nd it is Gene Wilder. The pseudo column should display "Name change".
Similarly for id A01R19 (John Doe) the value for flag_1 has changed to TRUE. The pseudo column should display "flag_1 change".
The output should look like :




id
Name
DS_DW_Id
flag_1
flag_2
Data Change




A01R11
Gene Wilder
PT12
TRUE
FALSE
Name Change


A01R19
John Doe
PT24
TRUE
TRUE
flag_1 Change





Answer:
You can join the table and subtract the date.
If the order of the record is correct (the previous day must be the previous record, you can use the window function(LEAD ))
select 
         a.id
        ,a.Name
        ,a.DS_DW_Id
        ,a.flag_1
        ,a.flag_2

        ,iif(a.Name=b.Name ,'',' Name Change') 
        +iif(a.DS_DW_Id=b.DS_DW_Id ,'',' DS_DW_Id Change')
        +iif(a.flag_1=b.flag_1 ,'',' flag_1 Change')
        +iif(a.flag_2=b.flag_2 ,'',' flag_2 Change') AS [Data Change]

from daily_account_data a
inner join(
            select *
            from daily_account_data b
)b on   a.id=b.id 
and DATEADD(day,-1, b.Insert_date)=a.Insert_date
where a.Name<>b.Name 
        or  a.DS_DW_Id<>b.DS_DW_Id   
        or    a.flag_1<>b.flag_1
        or    a.flag_2<>b.flag_2
Question: Why is my .LockAspectRatio=msoTrue showing as an error

I want to load data including an image from a Userform onto an excel worksheet.  I want to specify the image width and to maintain the aspect ratio.
The line .LockASpectRatio = MsoTrue shows as an error.  Can anyone help with the syntax?
'Save image to Cell

    Dim FileNAme As Variant
    Dim Img As Picture

If FileNAme <> "" Then
    
     FileNAme = Me.TextBox_5
    
With ws
     Set Img = .Pictures.Insert(FileNAme)

With Img
    .Placement = xlMove
    .Width = 150
    .LockAspectRatio = msoTrue
    .Left = ws.Cells(lr, "D").Left
    .Top = ws.Cells(lr, "D").Top
           
End With

End With

End If



Answer:
I'm sure it should be
.ShapeRange.LockAspectRatio = msoTrue
Another observation,
If FileNAme <> "" Then    
 FileNAme = Me.TextBox_5

You are checking if Textbox is not empty before you set the text box variable. Therefore FileNAme  would always empty.
Question: How to use 'if' and 'else' function to distinguish answer 'yes' from 'no' in python3

I`ve just started to learn my first coding language, python.
And I want to give to print() informations in my program, depending from user choice.
I am very fresh so pls be forgiving.
the code:
answer = input("Do You like it?" + " Yes/No")
    if answer = (yes)
    print("That`s great!\nThank You" + name + ".")
    else answer == (no)
print("Sorry to hear that\nPerhaps we could use other names?")

I want to give to print() informations in my program, depending from user choice.
I am very fresh so pls be forgiving.


Answer:
you can try and modify this code. hope this helps
def ifelse():
    entername = input() #first user input
    print('Do you like it?') #first prompt 
    answer = input()
    
    if answer == 'yes': 
        print("That`s great!") 
        print("Thank You name" )
    else:  # you can also use 'elif answer == 'no'
        #but since you only have two choices consider this a shortcut
        print("Sorry to hear that")  
        print("Perhaps we could use other names?")
        
ifelse()

ps. you can format the print statement so that the user input 'entername' can be printed along side it [ you can also do this w/o using def fcns]
Question: I have a trouble in counting amount of "items" in binary file. C

I want to count the amount of "items" in binary file using feof and fseek functions.
I have a binary file with names of people in chars and their salaries in floats.
before each name there is an int that represents the amount of chars in the name.
for example my file could look like this (but without spaces and without \0's):
5danny5000.00 4lena2500.50
one item is "4lena2500.50" for example.
in my code, the while loop does not stops.
what can I do to repair the problem?
thanks!
int count_items(FILE* file)
{
    int count=0;
    int curr_name_len;
    while (!feof(file))
    {
        fread(&curr_name_len, sizeof(int), 1, file);
        fseek(file, (curr_name_len * sizeof(char)) + sizeof(float), SEEK_CUR);
        count++;
    }
    rewind(file);
    return count;
}



Answer:
feof doesn't check whether the file is at the EOF, it checks whether the eof-indicator of the file was set on a previous operation. fseek allows to seek to an arbitrary position (if the operating system and the file system supports this) to allow for example to write with holes inside of the file, which is useful if you intend to write things inbetween.
Thus the eof-indicator is set after the fread-call, but is cleared after your fseek-call.
So this should work:
int count_items(FILE* file)
{
    int count=0;
    int curr_name_len;
    for (fread(&curr_name_len, sizeof(int), 1, file);
         !feof(file);
         fread(&curr_name_len, sizeof(int), 1, file))
    {
        fseek(file, (curr_name_len*sizeof(char))+sizeof(float), SEEK_CUR);
        count++;
    }
    rewind(file);
    return count;
}

or if you don't like that style:
int count_items(FILE* file)
{
    int count=0;
    int curr_name_len;

    fread(&curr_name_len, sizeof(int), 1, file);
    while (!feof(file))
    {
        fseek(file, (curr_name_len*sizeof(char))+sizeof(float), SEEK_CUR);
        count++;
        fread(&curr_name_len, sizeof(int), 1, file);
    }
    rewind(file);
    return count;
}

or less structured, but more clearly:
int count_items(FILE* file)
{
    int count=0;
    int curr_name_len;

    while (true);
    {
        if (sizeof(int) != fread(&curr_name_len, sizeof(int), 1, file)))
        {
            break;
        }

        fseek(file, (curr_name_len*sizeof(char))+sizeof(float), SEEK_CUR);
        count++;
    }

    if (feof(file))
    {
        rewind(file);
        return count;
    }

    if (ferror(file))
    {
        /* error handling */
    }
    else
    {
        /* fatal error handling */
    }
}
Question: draggable position:absolute div shrinking after hitting edge of position:relative div?

I have two draggable divs with position:absolute positioned inside of a position:relative div. My problem is that when I drag my divs to the edge of the position:relative parent they start to shrink. I need my draggable divs to stay the same size when they leave the parent's container, but I have no idea how to fix this issue.
Here's my codepen with the problem
    <div id="all">
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
    </div>
    <script src="move.js"></script>

* {
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.1;
    margin: 0;
}

#all {
    position: relative;
    margin: 0 auto;
    width: 50%;
    height: 100vh;
}

.move {
    cursor: move;
    position: absolute;
}

.txtbox, .topper {
    background-color: lightgrey;
}

.txtbox {
    min-height: 70px;
    max-width: 250px;
}

.topper {
    font-size: .625em;
    border-bottom: 1px solid black;
    padding: 2px;
}

const els = document.querySelectorAll(".move");
els.forEach((name) => {
  dragElement(name);
});

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = elmnt.offsetTop - pos2 + "px";
    elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
  }
  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}



Answer:
That's totally fine since an absolute positioned element wraps its content according its relative/absolute parent. Just set the width manually:
elmnt.style.width = elmnt.offsetWidth + 'px';

CODEPEN