Want to move like Rubik’s Cube

`function rotateFace(axis, layer, direction) {
if (isAnimating) return;
isAnimating = true;

const angle = Math.PI / 2 * direction;  // 90도 회전
const rotationMatrix = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(...axis), angle);

// 회전할 블록들을 그룹화
const cubesToRotate = cubes.filter(cube => {
    return Math.round(cube.userData.originalPosition[layer]) === Math.round(selectedFace.object.position[layer]);
});

// 그룹 생성
const group = new THREE.Group();
cubesToRotate.forEach(cube => group.add(cube));
scene.add(group);

const animationDuration = 300; // milliseconds
const startTime = performance.now();

function animate(time) {
    const elapsedTime = time - startTime;
    const progress = Math.min(elapsedTime / animationDuration, 1);
    const currentAngle = angle * progress;

    // 그룹 회전
    group.rotation[axis[0] === 1 ? 'x' : axis[1] === 1 ? 'y' : 'z'] = currentAngle;

    if (progress < 1) {
        requestAnimationFrame(animate);
    } else {
        // 최종 회전 및 위치 조정
        group.rotation[axis[0] === 1 ? 'x' : axis[1] === 1 ? 'y' : 'z'] = angle;
        group.updateMatrixWorld(true);

        // 그룹에서 큐브를 씬으로 옮기기 전, 각 큐브의 최종 회전 및 위치 설정
        while (group.children.length > 0) {
            const cube = group.children[0];
            
            // 그룹의 변환을 적용하여 최종 위치와 회전을 큐브에 설정
            cube.applyMatrix4(group.matrixWorld);
            
            // 큐브의 회전 행렬을 정렬하여 회전이 180도 되는 문제 방지
            cube.rotation.setFromRotationMatrix(cube.matrix);

            // 원래 위치 정보 업데이트
            cube.userData.originalPosition.copy(cube.position);

            // 그룹에서 큐브를 씬으로 다시 옮김
            scene.attach(cube);
        }

        scene.remove(group); // 빈 그룹을 씬에서 제거
        isAnimating = false;
    }

    renderer.render(scene, camera);
}

requestAnimationFrame(animate);

}`

The rotation is 90 degrees, but the color is changing as if it were 180 degrees, and the block disappears when it is rotated

Want to move like Rubik’s Cube

Troubleshooting Checks and Changing Multiple Values

how to fix google sheet webapp returning undefined value in html page?

I am making a web app using google sheets and google app script. My web app have an index page and an input page. There is no problem with inputting the data, however when i try to populate the data from google sheet it displayed undefined value for cells that are empty in the google sheet.

My script is quite long so i attached it here:
https://drive.google.com/drive/folders/1Zl-8UsntRUTlJcnaBuYIgXP2PvD4mIyN?usp=sharing

What i want is, when i click the edit button the form will be populated with the right data and if the data in google sheet is empty then it will just display the placeholder.
Thank you in advance.

Screenshot of undefined

Embedding a codepen in a (MDSVEX) markdown page in Sveltekit

I have a site that uses Sveltekit and MDSVEX to convert markdown documents (+page.md) into web pages and embed them in a section’s template. In my “Lab” section, I list all of my experiments via frontmatter in the markdown docs and when a user goes to the experiment page, I would like to show a codepen. I have tried both HTML and iFrame embeds in the markdown. This generally renders nothing but a border and the problem (at least with HTML embed appears to be the <script async> call that the embed requires. I have also tried to include both in a component (CodePen.svelte) and include that in the markdown file as you would typically include a component in a markdown file (with a <script> import Component... line and then the component <CodePen> in the body somewhere. Neither of these methods work either. Is there a technique that I am missing or is this just not possible?

Extract SQL Server results in JavaScript, store it in a variable, access in HTML

I am trying to extract database data in JavaScript using SQL Server. The problem now is that, after the connection close it seems that the data is not storing in the variable? I am not sure how it works.

const pool = new sql.ConnectionPool(config)
const poolConnect = pool.connect()

let workid = []

function connectStart(){
  poolConnect.then(() => {
    const request = new sql.Request(pool)
  
    // 查询用户表格中的所有数据
    request.query("select  *  from  dbo.xxAIO_det where xxAIO__ch01 like '%172.168.1.70;%' order by xxAIO_NO", (err, result) => {
      if (err) {
        console.error("ERROR", err)
      } else {
        console.log("Results:")
        result.recordset.forEach((row) => {
          workid.push(row.xxAIO_NO);
        })
      }
      console.log(workid)
  
      pool.close()
      
    })
})
}
connectStart()
console.log(workid)

the code seems to execute the final console log line and then start the connection, what is the problem or is this just how it behave?

[]
Results:
[ '10', '15', '20', '50' ]

I am not sure if this is the right way to get data from SQL Server, as I found this method online. The final goal is to extract the data and I need to display it in a HTML table.

How to get requested page (node.js)

I am working with Node.js servers. When I log on to the server, the code,
res.write("What ever text you choose")
will run and I will only get the “What ever text you choose” no matter what path I type. I know you can “write” a file so every time you log on to the server, it will give you that page. The problem I am having is that the server will only give me the one file. How can I request a different file based on the URL?

For example, When I type in localhost:9090, I’ll get the file I requested.
But if I type in localhost:9090/index.html or localhost:9090/funnyFile/Jokes.html or localhost:9090/myProjects/poj1/index.html, I’ll just get the same file, how can I access funnyFile and myProjects?

Here is my node server’s code.

const http = require('express')
const port = 9090

// Create a server object:
const server = http.createServer(function (req, res) {

    // Write a response to the client
    res.write("I choose this text");
    

    // End the response 
    res.end()
})

// Set up our server so it will listen on the port
server.listen(port, function (error) {

    // Checking any error occur while listening on port
    if (error) {
        console.log('Something went wrong', error);
    }
    // Else sent message of listening
    else {
        console.log('Server is listening on port' + port);
    }
})

swiper returns to previous slide when rendering component data

Assume two swiper slides. Slide1 and Slide2. In slide 1 I show a button that generates data, that data should be shown in slide2 but when that series of data is generated, when printed on slide2 it immediately returns to slide1
.ts file

dispatchPayment(info: any, dn: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.store.dispatch(new GenerateAcion({ info, dn }));
      this.store.select(PaymentState.paymentStatus).subscribe(state => {
        if (state.paymentSuccess) {
          const result = {}
          resolve(result);
        } else if (state.paymentError) {
          reject(state.paymentError);
        }
      });
    });
  }

 async generarCupon() {
    const payload = ...
    const dn = ...
    try {
      const result = await this.dispatchPayment(payload, dn);
      this.cdr.detectChanges();
      if(result){
    console.log("result", result);
        this.swiper.slideTo(3, 1000);
      }
    } catch (error) {
      console.error('failed:', error);
    }
  }

.html file

<div class="modal-outer">
    <swiper-container
      (afterinit)="swiperReady()"
      #slider
      allow-touch-move="false"
      [stopOnLastSlide]="true"
      [loop]="false"
    >

     <swiper-slide style="min-height: 500px;">
            <div class="modal-wrap">
            <ion-button fill="solid" shape="round" color="success" (click)="generarCupon()">
                Generate
            </ion-button>
        </div>
    </swiper-slide>
     <swiper-slide>
            <div class="modal-wrap">
                    <div class="refrece-input">
                        <ion-label>Reference</ion-label>
                        <ion-input type="number" value="{{finalResult?.referencia}}" readonly style="font-size: 18px"></ion-input>
                    </div>
            <div class="price-detail">
                            <span>Monto</span>
                            <h2>$ {{finalResult?.costo}} <span>MXN</span></h2>
                    </div>
        </div>
    </swiper-slide>
    </swiper-container>
</div>

Current behavior: When you press the first slide button, it goes to the next slide and immediately returns to the previous one.

Expected behavior: When the button is pressed, it shows the data obtained normally

nested array returns as undefined

I use axios to fetch the data and pass the data as a prop to WatchHeader

export const WatchProfile = () => {
    const [watch, setWatch] = useState([]);

    let {id} = useParams();

    let config = {
        headers: {
            'Content-Type': 'application/json',
        }
    }

    useEffect(() => {
        axios.get(`http://localhost:8000/api/stock/${id}`, config)
        .then(response => {
            setWatch(response.data)
        })
        .catch(error => {
            console.log(error);
        })
    }, [])

    return (
        <Box>
            <WatchHeader watch={watch} />
            <LineChart/>
        </Box>
    )
}

I then use the data in my WatchHeader

function WatchHeader({watch}) {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);
    const navigate = useNavigate();

    const navigateHome = () => {
        navigate('/')
    }

    const model = watch && watch.model || '';
    const brand = watch && watch.brand || '';
    const model_number = watch && watch.model_number || '';
    const last_price = watch && watch.data[0] && watch.data[0].price || '';
    console.log(last_price);

    return (
        <Box>
            <Box display="flex" flexDirection="row" justifyContent="space-between" sx={{pl: 2, pt: 2, pr: 2}}>
                <Box display="flex" flexDirection="column">
                    <Box display="flex" flexDirection="row" textAlign="left">
                        <Typography variant="h6" fontWeight="600"
                                    sx={{color: colors.label[100]}}>{model}</Typography>
                        <Typography fontWeight="200"
                                    sx={{color: colors.label[200], pl: 2, pt: 0.7}}>{brand}</Typography>
                    </Box>
                    <Box>
                        <Typography fontWeight="200" textAlign="left"
                                    sx={{color: colors.gray[100], pl: 0, pt: 0.7}}>{model_number}</Typography>
                    </Box>
                </Box>
                <Box>
                    <MoreHorizIcon
                        aria-controls={open ? 'account-menu' : undefined}
                        aria-haspopup="true"
                        aria-expanded={open ? 'true' : undefined}
                        sx={{fill: '#65abe0', backgroundColor: colors.gray[500], borderRadius: '50%', p: 0.1, mr: 2}}/>
                    <CloseIcon onClick={navigateHome}
                               sx={{fill: '#636266', backgroundColor: colors.gray[500], borderRadius: '50%', p: 0.4}}/>
                </Box>
            </Box>
            <Divider variant="middle" flexItem sx={{backgroundColor: colors.seperator[100], mt: 0.7}}/>
            <Box>
                <Box display="flex" flexDirection="column" textAlign="left" sx={{pl: 2, pt: 0.7}}>
                    <Box display="flex" flexDirection="row">
                        <Typography fontWeight="500" sx={{color: colors.red[100], pl: 2, mt: 0.7}}>{last_price}</Typography>
                    </Box>
                    <Typography fontWeight="200" sx={{color: colors.label[200]}}>Past Year</Typography>
                    <Typography fontWeight="200" sx={{color: colors.label[200]}}>USD</Typography>
                </Box>
            </Box>
            <Divider variant="middle" flexItem sx={{backgroundColor: colors.seperator[100], mt: 0.7}}/>
            <Box display="flex" flexDirection="row" textAlign="left" sx={{pl: 2, pt: 1.5}}>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>1D</Typography>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>1W</Typography>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>1M</Typography>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>3M</Typography>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>6M</Typography>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>YTD</Typography>
                <Typography fontWeight="200" sx={{color: colors.label[100], pr: 3}}>1Y</Typography>
            </Box>
        </Box>
    )

}

export default WatchHeader

All of the data returns except for the nested data. See the data structure below:

{
    "id": 290,
    "brand": "Rolex",
    "model": "Submariner",
    "model_number": "16610",
    "msrp": 6600,
    "data": [
        {
            "price": 10911.2,
            "date": "2024-08-14"
        },
        {
            "price": 10911.2,
            "date": "2024-08-13"
        }
    ]
}

The error that occurs is

TypeError: Cannot read properties of undefined (reading '0')

And the error is resulting from this line in my WatchHeader

const last_price = watch && watch.data[0] && watch.data[0].price || '';

Of note, if I delete the line of code above and save it will refresh the page with no errors and when I paste it back in it displays properly.

React Syntax Issue for Functional Component (Why 4th syntax doesn’t work – Like to know reason) [duplicate]

While creating a functional component I can write this:

A.

function App() { return <h1>Hello</h1> }
export default App; 

B.

export default function App() {return <h1>Hello</h1>}

C.

const App = () => {return <h1>hello</h1>}
export default App; 

D.

export default const App = () => {return <h1>hello</h1>}

While A, B, C — work fine;
Why there is an issue while writing like ‘D’. Any particular reason? Or What’s the issue? Or was it just decision of ‘React Syntax Developers’. Confused, pls help.

is there a way to refresh one specific part/paragraph of a website without refreshing the entire website? [duplicate]

i have a website im working on that uses flask to run the website and mongodb to store data. on mongodb, i have a simple json collection with one value, which i increment (using python) whenever the user does something. i then use jinja2 to inject the data onto the website. while this does work, and the data shows on the website, you are forced to refresh the page in order to see the data count change.

this is how i inject the data into the website with jinja2:

<p>
<strong>amount: {{count['count_example']}}</strong>
</p>

the solution that i tried was refreshing the page automatically every 3 seconds using javascript:

setTimeout(function(){
    location.reload();
}, 3000);

while this does show the data changing, it produces a flickery effect and isnt the best solution. im wondering if there is a way to ONLY change/refresh the data count, which is located in a paragraph (i.e. <p>), without reloading the entire page. any help is appreciated.

Custom props not being passed through a react component with extended styles

I have this Button.jsx file which exports a <Button /> component, that wraps a <StyledButton /> component, I need this wrap due to the optional args like loading and spinner, I mean, I don’t want to type { loading ? spinner : null } everytime I need a loading spinner icon or another some props.

The <StyledButton /> component checks for a $hasIcon prop to fix the width based on an existing icon in the button.

// Button.jsx

import styled from 'styled-components';

const StyledButton = styled.button`
    width: ${ ({ $hasIcon }) => $hasIcon ? 'fit-content' : '100%' };
    background-color: red;
`;

export const Button = ({ loading, spinner, children, ...props }) => (
    <StyledButton { ...props }>
        { children }
        { loading ? spinner : null }
    </StyledButton>
);

Then, I use the <Button /> component from Button.jsx in my whole project without problems, but things start to getting weird when I extend its styles to overwrite some of them.

// SomeComponent.jsx

import styled from 'styled-components';
import Button from '@components/Button';
import { SomeIcon } from '@icons';

const ExtendedStyleButton = styled(Button)`
    background-color: green;
`;

export const SomeComponent = () => (
    <ExtendedStyleButton $hasIcon>
        <SomeIcon />
    </ExtendedStyleButton>
);

Expected Behavior

$hasIcon prop specified in <ExtendedStyleButton /> should reach <StyledButton /> through the extended style of <Button /> in order to fix the width.

Desired path:

      $hasIcon
          |
          ▼
          
<ExtendedStyleButton /> 

          |  $hasIcon
          ▼

      <Button />

          |  $hasIcon
          ▼

   <StyledButton /> // fixed width to fit-content due to $hasIcon prop correctly passed

Actual Behavior

Due to the fact that I’ve been debugging everything with console.log, I believe the $hasIcon prop goes up to <ExtendedStyleButton /> and nothing else, which causes the width not being fixed for an icon and taking a 100% value.

Current path:

      $hasIcon
          |
          ▼
          
<ExtendedStyleButton /> 

          |
          ▼

      <Button />

          | 
          ▼

   <StyledButton /> // fixed width to 100% because $hasIcon prop has not been received

CORS issue, Cross origin error in spring boot. How do I allow CORS

I have a very pertinent issue. I built this java script based on a python script that tests my server which works fine. My issue is that when I click on subscribe in the front end, I’m met with a Cors error which I never had before. look at the image. Any help is greatly welcomed and appreciated. I have to use CORS because I’m running two servers and one calls and seeks information from the other.

The image shows the error

document.getElementById('payment-form').addEventListener('submit', async function(event) {
  event.preventDefault(); // Prevent default form submission

  // Base URL for the server running on port 4242
  const baseUrl = "http://localhost:4242";

  try {
    // Step 1: Get config data
    const configResponse = await fetch(`${baseUrl}/config`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json' // Ensure correct content type
      }
    });

    if (!configResponse.ok) {
      throw new Error(`Failed to fetch config: ${configResponse.statusText}`);
    }

    const configData = await configResponse.json();

    // Step 2: Create a checkout session
    const checkoutSessionResponse = await fetch(`${baseUrl}/create-checkout-session`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        priceId: configData.proPrice
      })
    });

    if (!checkoutSessionResponse.ok) {
      throw new Error(`Failed to create checkout session: ${checkoutSessionResponse.statusText}`);
    }

    // Step 3: Handle the checkout session response
    const checkoutSessionUrl = checkoutSessionResponse.headers.get('Location');

    if (checkoutSessionUrl) {
      const sessionIdPattern = /cs_test_w+/;
      const match = checkoutSessionUrl.match(sessionIdPattern);

      if (match) {
        const checkoutSessionId = match[0];
        console.log("Checkout Session ID:", checkoutSessionId);

        // Step 4: Redirect the user to the Stripe checkout
        window.location.href = checkoutSessionUrl;
      } else {
        throw new Error("Failed to extract Checkout Session ID from the URL");
      }
    } else {
      throw new Error("No Location header found in the response");
    }
  } catch (error) {
    // Error handling: log error and notify the user
    console.error("Error:", error);
    alert(`An error occurred: ${error.message}`);
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Checkout</title>
  <link rel="stylesheet" href="/css/checkout.css">
</head>

<body>
  <div class="container">
    <div class="features">

      <h3>Try Columbaria</h3>
      <h1>3 days free Then $2.00/month</h1>
      <p>Features include Mobile device touchpad, Tablet/iPad touchpad, hand gesture tracking, up to 5 people viewing, Weekend support</p>
      <div class="icon">
        <img src="/images/icon.png" alt="Wi-Fi Icon">
      </div>
    </div>
    <div class="payment">
      <h2>Payment</h2>
      <form id="payment-form" class="payment-form" action="/create-checkout-session">
        <div class="form-group">
          <label for="card-number">Card Number</label>
          <input type="text" id="card-number" placeholder="1234-1234-1234-1234" required>
        </div>
        <div class="form-group">
          <label for="expiry-date">Expiration Date (MM/YY)</label>
          <input type="text" id="expiry-date" placeholder="MM/YY" required>
        </div>
        <div class="form-group">
          <label for="cvc">CVC</label>
          <input type="text" id="cvc" placeholder="CVC" required>
        </div>
        <div class="form-group">
          <label for="cardholder-name">Cardholder Name</label>
          <input type="text" id="cardholder-name" placeholder="Full name on card" required>
        </div>
        <div class="form-group">
          <label for="country">Country</label>
          <select id="country" required>
          </select>
          <script>
            const countries = [{
                code: "US",
                name: "United States"
              },
              {
                code: "CA",
                name: "Canada"
              },
              {
                code: "GB",
                name: "United Kingdom"
              },
              {
                code: "AU",
                name: "Australia"
              },
              {
                code: "DE",
                name: "Germany"
              },
              {
                code: "FR",
                name: "France"
              },
              {
                code: "IN",
                name: "India"
              },
              {
                code: "CN",
                name: "China"
              },
              {
                code: "JP",
                name: "Japan"
              },
            ];

            const countrySelect = document.getElementById('country');

            countries.forEach(country => {
              const option = document.createElement('option');
              option.value = country.code;
              option.textContent = country.name;
              countrySelect.appendChild(option);
            });
          </script>
        </div>
        <div class="form-group">
          <label for="zip-code">Zip Code</label>
          <input type="text" id="zip-code" placeholder="Zip Code" required>
        </div>
        <div class="form-group">
          <input type="checkbox" id="save-info">
          <label for="save-info">Save my info for 1-click checkout</label>
        </div>
        <button id="payment-form-sub" class="payment-form-sub" type="submit">Subscribe</button>
      </form>
    </div>
  </div>
  <script src="/scripts/checkout.js"></script>
</body>

</html>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("https://mywebsite.com", "https://localhost:8443") // Combine origins
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("https://mywebsite.com");
        config.addAllowedOrigin("https://localhost:8443");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}

How to add “…” in the middle when text more than 2 line in ReactJS

I want to display when text <=2 lines, then display 2 lines without “…”.
However, if the text is > 2 lines, then add “…” in the middle.
In my code, i can add “…” in the middle, but when the text is less than or equal to 2 lines it still displays “…”. I want is that when text <= 2 lines it still displays full text, and if text > 2 then displays “…” in the middle.
this is my code:

const Main=()=>{
return(
 <div>
   <p>{truncateMiddle(textDummy)}</p>
 </div>
)

const truncateMiddle=(text)=>{
  const offset = 50;
  const ellipsis = '...'
  const len = text.length;
  const tail = text.slice(len - offset, len);
  let head = ""

  let end = len - offset;
  let start = 50;

  while (start < end - 1) {
    const curr = Math.floor((end - start) / 2 + start);
    head = text.slice(0, curr);
    end = curr;
  }
  head = text.slice(0, start || 1);
  return head + ellipsis + tail;
}

thanks for help