Python scraping not working on sastaticket.pk – Need guidance

I am begineer in web scraping i need gudiance regarding scraping a dynamic website. I have try multiple method selinum and beautful soup and these method work but not showing the reult of my desired

``
import requests
from bs4 import BeautifulSoup

url = 'https://www.sastaticket.pk/air/search?cabinClass={%22code%22:%22Y%22,%22label%22:%22Economy%22}&legs[]={%22departureDate%22:%222023-05-31%22,%22origin%22:%22KHI%22,%22destination%22:%22ISB%22}&routeType=ONEWAY&travelerCount={%22numAdult%22:1,%22numChild%22:0,%22numInfant%22:0}'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

all_text = [element.string for element in soup.find_all(string=True)]

desired_text = [text for text in all_text if "" in text]

for text in desired_text:
    print(text)
``

this print text but there not any desired info that i required so after that i create this for dynamic and unfortunallty this code doent work give bunch of an error

``
import requests

api_url = "https://www.sastaticket.pk/air/search?"

parameters = {
"cabinClass": '{"code":"Y","label":"Economy"}',
"legs": '[{"departureDate":"2023-06-31","origin":"KHI","destination":"ISB"}]',
"routeType": "ONEWAY",
"travelerCount": '{"numAdult":1,"numChild":0,"numInfant":0}'
}

response = requests.get(api_url, params=parameters)

if response.status_code == 200:

    data = response.json()
    
    
    calendar_fares = data.get('calendar_fares', [])
    
    print(calendar_fares)

else:
print("Error:", response.status_code)
``

Why does the keys are getting sorted in an object when we print if the key is a number?

I have an Object like this.

let code ={
    2: 'name',
    name: 'name',
    1: 'name',
    key: 'name',
    0: 'name'
}

When we try do console.log, we get a value as below.

{
   0: "name"​
   1: "name"
​   2: "name"
   key: "name"
   name: "name"
}

Basically the number keys are getting sorted and the remaining keys are getting printed in the same order that we added. Can i know the reason behind this action? And how does this is happening behind the scene. Please explain in detail.

Should I pursue the Post Grad Certificate in HRM from IIM Shillong & Edureka?

You have a valid point about expressing your concerns regarding the efficacy of executive development programs in the HR domain. As an experienced HR professional with 10+ years of work experience, it is understandable that you may question the value and relevance of such programs. Let us address your concerns and highlight the benefits of pursuing a program like the Post Graduate Certificate in Human Resource Management from IIM Shillong & Edureka.

  1. Stay Updated with Industry Trends: With business scenarios changing drastically, the HR landscape constantly evolves, leading to new trends, technologies, and best practices emerging regularly. Participating in an executive development program can ensure you remain up-to-date with your knowledge and skills in the dynamic HR field.
  2. Expand Your Knowledge and Skills: While you have accumulated significant experience in your HR career, an executive development program offers an opportunity to enhance your existing knowledge and skills. These programs often delve into advanced topics, strategic HR management, leadership development, and emerging HR areas, enabling you to broaden your expertise and excel in your role.
  3. Gain a Fresh Perspective: One of the key benefits of joining an executive development program is the exposure to diverse perspectives and experiences. Engaging with faculty members, industry experts, and fellow HR professionals from different backgrounds can provide you with valuable insights and alternative approaches to solving complex HR challenges.
  4. Networking and Collaboration: Executive development programs often bring together a cohort of experienced professionals from various industries. This networking opportunity allows you to connect with like-minded individuals, build relationships, and expand your professional network. Collaborating with peers can foster innovative thinking by exchanging new-age ideas, thought processes, and best practices.
  5. Enhance Your Career Opportunities: Pursuing an executive development program demonstrates your commitment to continuous learning and professional growth. It showcases your dedication to staying at the forefront of the HR field, making you a competitive candidate for leadership positions within your organization or when seeking new career opportunities.
    While you may have acquired substantial experience in the HR domain, investing in your professional development through an executive development program like the Post Graduate Certificate in Human Resource Management from IIM Shillong & Edureka can provide you with the tools, knowledge, and network necessary to take your career to new heights and remain relevant in a rapidly changing business environment.

As a Senior HR Executive with 10+ years of experience, my inbox is flooded with HR executive development programs. Should I pursue the Post Grad Certificate in HRM from IIM Shillong & Edureka? Will it benefit an experienced HR professional like me?

Function undefined when calling it from another function

I’m getting a secondary(...) is undefined when using this script :

function secondary() {
  //
}

function primary(e) {
  secondary()
}

function setupEventListeners() {
  window.addEventListener("click", (e) => primary(e));
}

setupEventListeners();

The script is called like this in the head section:

<script async src="myscript.js"></script>

  • Tried to call the function like this :
    window.addEventListener("click", primary);

  • Tried to call the script without async attribute

  • Tried change the function order in the code

Since the full code is a bit long, I’ve left it out for easier reading. Here’s the fiddle with the full code :
https://jsfiddle.net/qetyko8a/

This is really basic but i don’t get why the function seems to not exists. Any idea?

How to differentiate between two similar route parameters in React Router?

i am working on a project and i would like to know how to help react differentiate between 2 route parameters

i would have tried rearranging the routes but that won’t solve any problem, the problem will still be there as both routes are almost the same.

for example, a route path has its value as
“posts/:postId”
and another as
“posts/:userId”
you see that changing their positions doesn’t help solve the problem

How to save response from the sso login into async-storage ReactNative?

I have a screen in React Native named as Login. The Login screen is being fetched from webview. The architecture of application is :

  1. Application need to have native splash screen.
  2. It should open the login screen in webview.
  3. When a succesful login is done from the webview then the application need to save the token that is being fetched into the asyncstorage.
  4. If token is saved then application needs to be redirect to Dashboard screen.

How can i achieve this?
I have rendered the WebView URL successfully but and injected few Javascript also. But i am unable to save the token into async-storage. Have any one done it anywhere?

This is how my source code looks like

import React, { useEffect, useRef } from 'react';
import { Alert, UIManager, ActivityIndicator } from 'react-native';
import WebView, { WebViewNavigation } from 'react-native-webview';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';

UIManager.setLayoutAnimationEnabledExperimental &&
  UIManager.setLayoutAnimationEnabledExperimental(true);


const Login: React.FC = () => {
  const navigation = useNavigation<any>();
  const [visible, setVisible] = React.useState<boolean>(false);
  const [logMessages, setLogMessages] = React.useState<string[]>([]);
  const [shouldRedirect, setShouldRedirect] = React.useState<boolean>(false);
  const webViewRef = useRef<WebView>(null);

  useEffect(() => {
    console.log("Log messages =>", logMessages)
  }, [logMessages]);

  const handleWebViewMessage = (event: any) => {
    // Parse the message received from the WebView
    const data = JSON.parse(event.nativeEvent.data);
    console.log("Webview Data =>", data)
    setLogMessages((prev) => [...prev, data]);
  };


  const saveTokenToAsyncStorage = async (data: any) => {
    try {
      await AsyncStorage.setItem('userToken', JSON.stringify(data));
      console.log("Data saved to async storage")
    } catch (error) {
      console.log("Errror saviung the data to async storage =>", error)
    }
  }

  const handleShouldLoadWithRequest = (event: any) => {
    if (event.title === "Portal") {
      webViewRef.current?.stopLoading()
      navigation.replace("Dashboard")
      return false;
    }
    return true;
  }


  const handleNavigationStateChange = (navState: WebViewNavigation) => {
    if (navState.title === "Portal") {
      navigation.replace("Dashboard",)
      webViewRef.current?.injectJavaScript(`
        function (){
          var style = document.createElement('style');
          style.innerHTML = 'body { display: none !important;}';
          document.head.appendChild(style);
        } ()
      `)
      webViewRef.current?.injectJavaScript(`
        const data ={
          hasLoggedInOnce: true,
          accessToken : 'TOKEN',
          accessTokenExpirationDate: 'EXPIRATION_DATE',
          refreshToken: 'REFRESH_TOKEN'
        };
        window.ReactNativeWebView.postMessage(JSON.stringify(data));
      `)
    } else if (navState.title === "https://mbl-intranetsso.server247.info/Account/Login") {
      console.log("Login page")
      webViewRef.current?.injectJavaScript(`
        document.getElementByClassName('btn btn-danger form-btn btn-primary').addEventListener('click', function(){
            console.log("Button clicked")        
        })
      `)
    }

  }

  const webViewScript = `
    (function(){
      var originalConsolelog = console.log;
      console.log = function(){
        var logMessage = Array.prototype.slice.call(arguments).join(' ');
        window.ReactNativeWebView.postMessage(logMessage);
        originalConsolelog.apply(console, arguments);
      }
    })();
  `

  return (
    <>
      <WebView
        injectedJavaScript={webViewScript}
        ref={webViewRef}
        source={{ uri: 'https://mbl-intranetsso.server247.info/Account/Login' }}
        onError={(syntheticEvent) => {
          const { nativeEvent } = syntheticEvent;
          console.warn('WebView error: ', nativeEvent);
        }}
        style={{ backgroundColor: 'transparent' }}
        bounces={false}
        javaScriptEnabled={true}
        scrollEnabled={false}
        onNavigationStateChange={handleNavigationStateChange}
        onMessage={handleWebViewMessage}
        onLoadStart={() => setVisible(true)}
        onLoadEnd={() => setVisible(false)}
        onShouldStartLoadWithRequest={handleShouldLoadWithRequest}
      />
      {visible && (
        <ActivityIndicator
          style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}
          size="large"
          color="#0000ff"
        />
      )}
    </>
  );
};

export default Login;

This is my config file for sso login that has been provided to me for logging in. I dont know how to use it.

export const __RUNTIME_CONFIG__ = {
    "REACT_APP_BASE_URL": "https://mbl-intranet.server247.info/",
    "REACT_APP_SELF_UPDATE_URL": "https://mbl-intranet.server247.info/selfupdate/api",
    "REACT_APP_AUTHORITY": "https://mbl-intranetsso.server247.info",
    "REACT_APP_REDIRECT_URL": "http://localhost:3000",
    "REACT_APP_POST_LOGOUT_REDIRECT_URL": "https://mbl-intranet.server247.info/",
};


import { __RUNTIME_CONFIG__ } from "./config";

export const oidcSettings = {
    authority: __RUNTIME_CONFIG__.REACT_APP_AUTHORITY,
    client_id: "Intranet_App",
    redirect_uri: __RUNTIME_CONFIG__.REACT_APP_REDIRECT_URL,
    scope: "address email offline_access openid phone Portal profile role",
    response_type: "code",
    grant_type: "authorization_code",
    post_logout_redirect_uri:
        __RUNTIME_CONFIG__.REACT_APP_POST_LOGOUT_REDIRECT_URL,
    dummyClientSecret: "",
    showDebugInformation: true,
    oidc: true,
    requireHttps: false,
    autoLogin: true,
};

Python / Chrome Web Driver / MAMP connectivity issue

The Chrome WebDriver/MAMP local server locates the main.html file directly when the Sign in button is clicked, but it is unable to find the main.html file within the SurveySite Folder. I have tried redirecting the HTML button to the correct path using a JavaScript function, but it still cannot locate the correct path.

class WebDriverHandler:
def init(self):
self.driver = None

def open_browser(self):
    options = Options()
    self.driver = webdriver.Chrome('/Users/mini/Desktop/Python Projects/Chrome Driver/chromedriver_mac64/chromedriver', options=options)

def close_browser(self):
    if self.driver:
        self. driver.quit()
        self.driver = None

def login(self):
    self.driver.get('http://localhost:8888/SurveySite/index.html')
    time.sleep(1)
    self.driver.find_element(By.ID, 'sbLogInCta').click()

    try:
        WDW(self.driver, timeout=10).until(EC.url_matches('http://localhost:8888/SurveySite/login.html'))
    except:
        ConnectionError(self.login)
        print("Login failed: 404 Not found")
        errorMessage = QMessageBox(self)
        errorMessage.setWindowTitle("Information")
        errorMessage.setText("This is an information message.")
        errorMessage.setStandardButtons(QMessageBox.Ok)
        response = errorMessage.exec_()
        if response == QMessageBox.OK:
            print("User clicked Ok")
        else:
            self. driver.quit()
        
    time.sleep(2)
    self.driver.find_element(By.ID, 'sbxJxRegEmail').send_keys('[email protected]')
    time.sleep(1)
    self.driver.find_element(By.ID, 'sbxJxRegPswd').send_keys('Comm@nd7890')
    time.sleep(1)
    self.driver.find_element(By.ID, 'loginBtn').click()
    time.sleep(3)
    #WDW(self.driver, 10).until(EC.url_matches('http://localhost:8888/SurveySite/main.html'))
    #self. driver.get('http://localhost:8888/SurveySite/main.html')
    time.sleep(1)
    try:
        #self. driver.get('http://localhost:8888/SurveySite/main.html')
        WDW(self.driver, timeout=10).until(EC.url_matches('http://localhost:8888/SurveySite/main.html'))
    except:
        print("Login failed: 404 Not found")
    time.sleep(3)

Here’s the HTML code with the JavaScript redirect function

<div class="sbCtaLoaderWrapper loginSubmitButtonWrapper">
            <button id="loginBtn" class="login submit button" 
onclick="redirectToMain()">Sign in</button>
            <script>
                function redirectToMain() {
                    window. location.href = "http://localhost:8888/SurveySite/main.html";
                }
            </script>
        </div>

Here’s the MAMP path:

/Applications/MAMP/htdocs/SurveySite/main.html

AG-GRID table carriage return feed avoids fixed rows

 <ag-grid-angular
    [style.width]="'100%'"
    [style.height]="scrollY"
    [class]="agThemeClass"
    [rowData]="dataList"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [localeText]="agGridLocaleText"
    [enterMovesDown]="true"
    [enterMovesDownAfterEdit]="true"
    (cellEditingStopped)="cellEditingStopped($event)"
    [pinnedBottomRowData]="rowDataBottom"
    [stopEditingWhenCellsLoseFocus]="true"
    (gridReady)="onGridReady($event)"
    [rowSelection]="'multiple'"
    [suppressRowClickSelection]="true"
    (selectionChanged)="onSelectionChanged($event)"
    (cellKeyPress)="onCellKeyPress($event)"
  >
  </ag-grid-angular>

[enterMovesDown]=”true” [enterMovesDownAfterEdit]=”true”
To reach the return feed line, but will change to the bottom fixed total line, is there any way to avoid?

Searching For Weighty Vehicles Fix Administration?

Searching For Weighty Vehicles Fix Administration?
Development goliaths depend on breakdown administrations to keep their weighty hardware moving. They utilize business vehicles to move machines and devices. One might say that they depend on trucks to move development hardware to locales. Or on the other hand it would be more fitting to say that development organizations depend on Edmonton rock solid mechanics in Edmonton to keep their vehicles moving.

Why development organizations depend on breakdown administrations given by mechanics?

A major development organization
can enlist experienced mechanics for administration and fix of its business vehicles. Be that as it may, rethinking the occupation is more helpful than employing mechanics. Rethinking works sets aside cash and time. However, the greatest benefit of breakdown administration is that it is accessible constantly.

Benefit of breakdown administration

  1. Accessibility of ability

Adjusting and fixing enormous business vehicles is the occupation of learnt and experienced car engineers. A development organization would need to make a different help and fix office to get speedy help for its business vehicles. The organization would require employing ability and since it is a development organization, recruiting auto specialist could be troublesome and furthermore a costly occupation for the organization.

  1. Decrease of support cost of vehicles

The expense of employing auto designers would build the upkeep cost of the vehicles over the long haul. It isn’t known when the organization would require administration of its architects yet it would need to pay and save the maintenance group prepared for work. In any case, reevaluating the maintenance work will decrease the running expense of the vehicles over the long haul. The organization will pay just when it takes administrations.

  1. Accessibility of extra parts

Employing a breakdown organization would free you from the problem of saving a stock of extra parts for your business vehicles. Your breakdown specialist organization will orchestrate the parts as and when required. You just need paying for the parts changed by the specialist co-op.

  1. Nonstop help

A breakdown administration organization could propose nonstop help by adding extra charge. Likewise the specialist co-op would organize mechanics in the event of staff crunch. In any case, a development organization would need to deal with the maintenance work with anything that work drive it has accessible, on the off chance that the organization enlists no breakdown specialist co-op.

How to find a business vehicle fix organization?

Size: The specialist co-op ought to be of huge size with many mechanics working. Having a huge labor force is a confirmation that you will get speedy help. The specialist co-op would have the option to answer your call, assuming that it has save labor force to deal with mass burden.

Process: You ought to get a fast methodology number to find support. Additionally you ought to be given holding up time in which you could find support. The specialist co-op could charge a proper yearly charge for administration to keep things basic and helpful for the clients.

Objective: Objective with employing breakdown administration ought to be to keep vehicles in running condition constantly. With convenient business vehicle assessment Edmonton, you can guarantee your vehicles stay in great shape and have little need of crisis fix.

Objective with employing breakdown administration ought to be to keep vehicles in running condition constantly. With convenient business vehicle assessment Edmonton, you can guarantee your vehicles stay in great shape and have little need of crisis fix.

global style doesn’t apply on all components in StencilJs

I’m using StencilJs. The problem is I can’t use global styles inside shadow=true components.
In this section of Docs it explicitly says we can use it for adding font-face and css-reset. But I’m not able to use this feature. it only applies to components with shadow=false

Here is my global.style.scss

body{
  background-color: red;
}

button{
  cursor: pointer;
  border: none;
  box-shadow: none;
  outline: none;
  &:hover, &:focus{
    outline: none;
    box-shadow: none;
  }
}

in stencil.config.ts I have

export const config: Config = {
  namespace: 'areas-power',
  globalStyle: 'src/assets/styles/global.style.scss',
  outputTargets: [
    {
      type: 'dist',
      esmLoaderPath: '../loader',
    },
    {
      type: 'dist-custom-elements',
    },
    {
      type: 'docs-readme',
    },
    {
      type: 'www',
      serviceWorker: null, // disable service workers
    },
  ],
  plugins: [
    sass()
  ]
};

I also added its link to index.html file. style only apply to body tag. it doesn’t apply on buttons inside other components. How I can add shared css-reset and font-face to all components in Stencil?

Creating a Custom draggable Modal Sheet in Angualrjs

On clicking of a button I am opening a custom modal sheet. Here is the code for Custom Modal sheet. What I am currently doing is that this modal pops up it has 70% height. If i click outisde of the popup that showAllMeasurements() gets called and it closes the popup.

I want to add dragging functionality using the icon rectangleIcon (svg)

When it is hold by mouse cursor or in mobile screen it is hold byfinger and move upwards or downwards I want the measurementTray div height to be moved accordingly means it change height as we are holding and moving the icon up and down.

if i am holding the icon and I pick the thumb or mouse click from icon and its height is less than 25% so call showAllMeasurements()
If i am holding the icon and I pick the thumb or mouse click from icon and its height is more than 75% so make measurementTray div height to 100%
If i am holding the icon and I pick the thumb or mouse click and its height is in between 25% and 75% so measurementTray div height to 60%

I have done some implementation from my end but its not working

    <div class="measurementTray" ng-show="project.showAllMeasurementsBar">
                    <div class="trayContentMeasurementTray">
                        <img alt="" class="rectangleIcon" 
                                    src="assets/Icons/rectangle.svg"
                                      ng-mousedown="project.startDrag($event)" ng- 
                                          touchstart="project.startDrag($event)"
                                          ng-mouseup="project.endDrag()" ng- 
                                          touchend="project.endDrag()"
                                          ng-mouseleave="project.endDrag()" ng- 
                                          touchcancel="project.endDrag()" />

                        <img alt="" class="resetScale crossIconforMeasurement"
                            src="assets/closeMeasurementBarCross.svg" ng- 
                 click="project.showAllMeasurements()" />
                        <div class="measurementOptionHeading">View All 
                       Measurementss</div>
                        <div class="measurementTrayOption"
                            ng-repeat="dimension in project.linesInfo | orderBy:'-lineId'"
                            ng-class="{ 'firstOption': $first }">
                            <div>
                                <div class="labelName">{{dimension.dimensionLabel == "" ? 'Untitled' :
                                    dimension.dimensionLabel}}</div>
                                <div class="labelMeasurementInches">{{dimension.measurement}}</div>
                            </div>
                            <div class="labelMeasurementCm">{{
                                project.convertUnitToCentimeters(dimension.measurement) }} cm</div>
                        </div>
                    </div>
                </div>

CSS

.measurementTray {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    transform-origin: bottom;
    height: 70%;
    background: #FFFFFF;
    border: 1px solid rgba(34, 34, 34, 0.2);
    border-radius: 10px 10px 0px 0px;
    z-index: 101;
    overflow-y: auto;
}

.measurementTray.active {
    transition: transform .3s ease;
}

.measurementTray:not(.active) {
    transform: translateY(100%) !important;
    transition: transform .3s ease;
}

.trayContentMeasurementTray {
    padding: 5px 0 43px 0;
}



.crossIconforMeasurement {
    float: right;
    height: 27px;
    width: 27px;
    position: relative;
    top: 11px;
    margin-right: 24px;
}


.measurementTrayOption {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    border-bottom: 1px solid #BBC1C3;
    padding: 17px 0px 14px 0px;
}

.measurementTrayOption .labelName {
    font-family: 'Segoe UI';
    font-style: normal;
    font-weight: 600;
    font-size: 13px;
    line-height: 17px;
    color: rgba(109, 121, 131, 0.8);
}

.measurementTrayOption .labelMeasurementInches {
    font-family: 'Segoe UI';
    font-style: normal;
    font-weight: 600;
    font-size: 28px;
    line-height: 37px;
    color: #333333;
}

.measurementTrayOption .labelMeasurementCm {
    align-self: flex-end;
    margin-bottom: 4px;
    font-family: 'Segoe UI';
    font-style: normal;
    font-weight: 700;
    font-size: 16px;
    line-height: 21px;
    color: #6D7983;
}

.measurementTrayOption.firstOption {
    border-top: 1px solid #BBC1C3;
    margin-top: 17px;
}

JS

function showAllMeasurements() {
    if(vm.showTray) {
        vm.showTray = false;
        angular.element('.tray').toggleClass('active', vm.showTray);
    }
    vm.showAllMeasurementsBar = !vm.showAllMeasurementsBar;
    angular.element('.measurementTray').toggleClass('active', 
         vm.showAllMeasurementsBar);
}

// Inside your controller or component
vm.minHeightPercentage = 25; // Minimum height percentage
vm.maxHeightPercentage = 75; // Maximum height percentage
vm.dragging = false; // Flag to track dragging state
vm.startY = 0; // Initial Y position when dragging starts
vm.startHeight = 0; // Initial height of the measurementTray div

// Function to handle the mouse or finger hold event
vm.startDrag = function (event) {
    if (event.target.classList.contains('rectangleIcon')) {
        vm.dragging = true;
        vm.startY = event.clientY || event.touches[0].clientY; // Get initial Y position
        vm.startHeight = angular.element('.measurementTray').height(); // Get initial height of the measurementTray div
        console.log('Start Drag - startY:', vm.startY, 'startHeight:', vm.startHeight);
    }
};

// Function to handle dragging while moving the mouse or finger
vm.handleDrag = function (event) {
    if (vm.dragging) {
        var currentY = event.clientY || event.touches[0].clientY; // Get current Y position
        var deltaY = currentY - vm.startY; // Calculate the change in Y position
        var windowHeight = window.innerHeight; // Get the window height
        var tray = angular.element('.measurementTray'); // Select the measurementTray element

        var newHeightPercentage = (vm.startHeight + deltaY) / windowHeight * 100; // Calculate the new height percentage
        console.log('Handle Drag - currentY:', currentY, 'deltaY:', deltaY, 'newHeightPercentage:', newHeightPercentage);

        // Restrict the new height percentage within the specified range
        newHeightPercentage = Math.max(vm.minHeightPercentage, Math.min(vm.maxHeightPercentage, newHeightPercentage));

        // Apply the new height to the measurementTray div
        tray.css('height', newHeightPercentage + '%');
    }
};

// Function to handle the end of dragging (mouse release or finger lift)
vm.endDrag = function () {
    if (vm.dragging) {
        vm.dragging = false;
        var tray = angular.element('.measurementTray'); // Select the measurementTray element
        var trayHeight = tray.height(); // Get the current height of the measurementTray div

        if (trayHeight < vm.minHeightPercentage) {
            project.showAllMeasurements(); // Call the showAllMeasurements function if height is less than 25%
        }

        console.log('End Drag');
    }
};

Any leads would be highly appreciated. Thanks

Avoiding unnecessary updates in React Context

I am using a custom hook with a timer to update a Context Provider. I then wrap the Provider component around the components that need the timer.

export const useTimer = () => {
  const [a, setA] = useState()
  const [b, setB] = useState()
  const [c, setC] = useState()

  // Start the timer
  useEffect(() => {
    const interval = setInterval(() => {

      // Do some calculations on a, b, c
      // Their values change independently at each interval
      // then setA(someValue), setB(someValue) etc

    }, 30)
    return () => clearInterval(interval)
  }, [a, b, c])

  return [a, b, c]
}

export const TimerContext = createContext()

export const TimerProvider = ({ children }) => {
  
  return (
    <TimerContext.Provider value={useTimer()}>
      {children}
    </TimerContext.Provider>
  )
}

Because I’m returning a new array from useTimer every time, it updates the Provider every 30ms, not when the values change. This causes unnecessary rerenders in the wrapped components. If I return an object instead the result is the same, because it’s a new object. And I can’t return multiple independent variables in JavaScript.

Moreover, some components only need a and b, while others only need c. I’d like to create independent Contexts, all based on a single running timer, which only update when the needed values have changed.

How can I get around this?

the deprecated lifecycle methods in React

I wanted to deeply get the reasons for why such lifecycle hooks as componentWillMount, componentWillReceiveProps and componentWillUpdate became removed from React 17 and, sure, react docs explains it that those hooks get in the way of async rendering thus affects the future development of react. However, I wanted to go deeper and get the actual reasons.

Firstly, question about componentWillMount. It says that the hook is not recommended to be used for side effects. Why? I mean, it says ‘

componentWillMount will not return before the first render’

does it mean that if fetch returns after the first render then componentWillMount will be run again? is that the main reason why it was removed from React 17?

Secondly, about componentWillReceiveProps, it says that this hook is synchronous and if we put side effects in it then React will wait until that side effect gets finished before running the next lifecycle hook, as a result, with side effects componentWillReceiveProps turns into blocking hook. Right?

Lastly, about componentWillUpdate, is it true that this hook was removed because it was misused for performing side effects like data fetching or DOM manipulation, if so, what is wrong with that?

How can we store TestRigor captured values in a text file using JavaScript file handling and Node.js?

After running the test cases on TestRigor we get captured values in key and values tabular data format. We want those values to be stored in a text file so that we can download and use it externally. How do we do it?

Since TestRigor supports JavaScript can we use file handling to create a .txt file where all the values in “” all stroed so that it can be downloaded externally??