vendredi 26 février 2021

Merging two dateframes based on condition

I have 2 dataframes data1 and data2 that I want to join. I want to keep 3 columns from data2

The condition that I need is that if the column 'col1' in data2 has nan values then the key for joining the datasets would be col1, col2 and col3. Else the key for joining would be col1 and col3 only.

I tried writing a function based on if-else statements but it does not seem to work

Any help would be appreciated

jeudi 25 février 2021

if ternario does not work, function has value but never used says

I am new with programing and I want to use if ternario, but it doesn't work. I have two functions and I create a third function to show one of them or the other. It is an application in ReactJS. Below is the code:

import { Table } from "react-bootstrap";
import { Link } from "react-router-dom";
import { useCartContext } from "../../Context/CartContext";
   
const emptyCart = () => {
  return(
  <>
    <div>
      <h3>The Cart is empty</h3>
      <p>
        Return to home to see our products
      </p>
      <Link to='/' ><button className="btn btn-info"> Home </button></Link>
    </div>
  </>
  );
};

const CartFunction = () => {
  const { list, totalPrice } = useCartContext();
    return (
        <Table striped hover>
          <thead>
            <tr>
              <th>Product</th>
              <th>Title</th>
              <th>Quantity</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
            {list.map((varietal) => (
              <tr key={varietal.id}>
                <td>
                  <img
                    src={varietal.pictureUrl}
                    alt='img'
                    style=
                  />
                </td>
                <td>{varietal.title}</td>                    
                <td>{varietal.count}</td>
                <td>${varietal.price}</td>
              </tr>
            ))}
          </tbody>
          <thead>
            <tr>
              <td colSpan="3">Total</td>
              <td>${totalPrice()}</td>
            </tr>
          </thead>
        </Table>
    );
  };

const CartComponent = () => {
    const { list } = useCartContext();
    
    return (
      <>
      {list.length !== 0 ? <CartFunction /> : <emptyCart />}
      </>
    );
  };

export default CartComponent;

Visual Code it says that emptyCard has a value but it is never used. If there is someone that could help me I would appreciate it. Cheers

i am using for loop in object in javascript, but one condition is creating issue

i have this validator function

 import validator from "validator";
 import isEmpty from "is-empty";

export default function validate(data) {
  const errors = {};

  for (const property in data) {
    console.log(property); //<---This is executed

    //exclude optional properties from validation
    if (!property == "address2") {
      console.log("i got called"); //<---but this is not
      //return error if any of the compulsory fields is empty
      if (isEmpty(data[property])) errors[property] = `${property} is required`;

      //phone number validation
      if (property === "number")
        if (validator.isMobilePhone(data[property], "any"))
          errors[property] = "please enter valid phone number";

      //return error if country is not Pakistan
      if (!property === "country")
        if (
          data[property].charAt[0].toUpperCase() + //convert first letter to uppercase
            data[property].slice(1).toLowerCase() !== //remaining to lowercase
          "Pakistan"
        )
          errors[
            property
          ] = `we care currently taking orders from only within Pakistan`;
    }
  }

  return {
    errors,
    isValid: isEmpty(errors),
  };
}

This is how i am calling the function in react from onClick event of button:

          <Button
          onClick={(event) => {
            //check validation
            const { errors, isValid } = validate(details);
            //if valid submit form else show errors
            isValid ? handleSubmit(event) : setErrors(errors);
          }}
          variant="contained"
          name="shipping"
        >
          Continue
        </Button>

This is the state object that is passed

const [details, setDetails] = useState({
      name: "",
      number: "",
      address1: "",
      address2: "",
      city: "",
      postalCode: "",
      country: "",
    });

all fields are empty but still empty errors object is being returned. Any help here is appreciated. thanks

Why is this code returning the else statement not the if statement? [closed]

l_name = input("Enter last name: ")  ***User input was carl***


if  l_name.lower() <= "c":

    print ("Welcome to the a, b, c line")

else:

    print ("Sorry, this is the a, b, c line")

Why is "carl" as input returning the else statement when carl is equal to c?

How can I convert this IF statement to use in VBA

I have the following IF statement =IF(LEN(F2)>LEN(H2),F2,H2)

This just checks which is longer between F2 and H2 and populates I2 with the longest. When I put this in VBA it comes out as =IF(LEN(G1048558)>LEN(I1048558),G1048558,I1048558)in my spreadsheet

How could I fix this?

Sub PopulateI()

Range("I2").Select
ActiveCell.FormulaR1C1 = _
"=IF(LEN(R[-20]C[-2])>LEN(R[-20]C),R[-20]C[-2],R[-20]C)"
Selection.AutoFill Destination:=Range("I2:I" & Range("F" & Rows.Count).End(xlUp).Row)

End Sub

can the JS decision making with 2 variables be reduced in any elegant way not with IF statement?

I am a newbie JS developer and although the below code works perfectly fine with 2 variables and with IF statement but I want to know is there any elegant way of doing it WITHOUT IF statement.

The working code is below:

let animation;
    if(!detectScroll && !detectHover){
      animation = loadAnimation(reverseAnimationData)
    }
    else if(detectScroll && !detectHover){
      animation = loadAnimation(cyanAnimationData)
    }
    else if(!detectScroll && detectHover){
      animation = loadAnimation(cyanAnimationData)
    }
    else {
      animation = loadAnimation(cyanAnimationData)
    }

I want to know that can I reduce code into less lines of code with any other way without IF statement.

How to create a dummy variable based on other columns values in R?

I am cleaning a scraped dataset from duplicates. I want to create a dummy variable indicating whether I have two or more observations that are identical in all conditions or all conditions but one.

Here's an example of my dataset:

Postcode nrooms price sqm
76 1 259 30
75 5 380 120
75 5 400 120
75 2 450 80
76 1 259 30

Here's the dummy I want:

Postcode nrooms price sqm dummy
76 1 259 30 1
75 5 380 120 1
75 5 400 120 1
75 2 450 80 0
76 1 259 30 1

Where first and last rows have same values over all characteristics, the second and the third have same values in all characteristics but one (the price).

Could someone help me with this?

Thanks!