Can I using CSS effectively achieve max-width=100% and max-height=100% without parent having explicit/fixed width and height, alternative approach?

Intro

There are already plenty of questions and answers explaining how max-width and max-height works (this one for example). Basically, if the parent is unrestricted so is the child. OK, fine, but…

Question

…But is there any other way where I could restrict size of the child to whatever size of parent would have if child was not present at all?

...
   <div class="parent"> <!-- size determined by it's parent flexbox -->
      <div class="child">
         <!-- could have large content --> 
      </div>
   </div>
...
.child {
    max-height: 100%; /* not working as needed if parent is unrestricted */
    max-width: 100%; /* not working as needed parent is unrestricted */
    overflow: auto; /* handle oversized content */
}

Context / requirements

  • Page design/layout is top-to-bottom slicing with nested layers of horizontal and vertical flexboxes
  • Whole body should never have vertical nor horizontal scroll
  • Generally, size of some child is determined by size of its parent (100% or less or fill remaining)
  • At some nested level I have parent div that has correct size determined by top-to-down nesting and I know that inner content could be larger size.
    • that larger size should be addressed with inner scrolling in case of overflow
  • Point where my parent and child meet is transition point where different layout strategies meet
    • everything “above” parent is top-to-bottom layout, meaning parent size influencing child size (higher level in DOM dictates size of lower levels)
    • everything “below” child is bottom-to-top layout, meaning child size influencing parent size (lower level in DOM dictates size of upper level)
    • meet point between those two different worlds addressed by scroll if needed

My current workaround

Since I was unable to get desired behaviour using CSS, I have failover to JS by changing child’s max-width and max-height to parent’s width and height (in pixels) during child is hidden (display: none;). I first hide child to see what would be the size of parent, then restrict size of child, and then show child back.

See JS function refreshMaxWidthAndHeight(wrapper) in JSFiddle demo what I’m actually doing.

Cons of this approach:

  • it’s messy
  • it must be triggered each time when something changes (any collapse/expand, content change, viewport size change, etc…)
    • it’s hard to exhaustively cover all cases, probably safest would be to use periodic setInterval and do checks constantly
  • in case if child content is large/heavy performance of hide->measure->show approach is not great and it causes visible flicker

JSFiddle demo example

JSFiddle demo Although this demo is very much simplified version of my situation, I’ve deliberately left in some extra layers of design slicing to demonstrate:

  • why it’s not possible to have hardcoded size limits
  • dynamics of collapsing/expanding some portions of page

NOTE current behaviour of demo is exactly behaviour that I’m trying to achieve

Questions

  • Are there any other approaches beside using max-width/max-height?
  • Is it possible to avoid need to tweak CSS with JS on every relevant content change?
  • Any pointers or search terms about how other devs are handling similar layout situations?
    • I’m thinking about last point of Context / requirements section where I’ve described top-to-bottom vs bottom-to-top meet point

“Method not allowed” error when trying to make AJAX calls [duplicate]

I am trying to create a backend for my application with PHP. I am relatively new to PHP so I am trying to just start off by creating a POST request to send a string from my Js to the PHP.
However, I get this error when I try to do so. Both files are stored in the same directory. I am using XAMPP server.

Js code (script.js):

let xhr = new XMLHttpRequest();
xhr.open('POST', 'app.php', true);
xhr.setRequestHeader('Content-Type', 'text/plain');

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error('Request failed with status:', xhr.status);
        }
    }
};

const data = 'hi';
xhr.send(data);

PHP Code (app.php):

<?php
$postData = file_get_contents('php://input');
echo $postData;
?>

Error in console:
enter image description here

Unable to receive beacon events on iOS device using react-native-kontaktio library

I’m using the react-native-kontaktio library to scan for beacons (BLE) in my React Native app. The library works correctly on Android devices, but I’m encountering issues with iOS.

Here are my platform and library versions:

  • Platform: iOS
  • react-native: ^0.68.1
  • react-native-kontaktio: ^4.1.0

I’m trying to listen for beacon events using the following code:

kontaktEmitter.addListener('didRangeBeacons', ({ beacons, region }) => {
  // Event handling logic here
});

minSdkVersion = 21
compileSdkVersion = 34
targetSdkVersion = 34

I have handled permission in info.plist like this --> 
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>'Description'</string>
        <key>NSLocationAlwaysUsageDescription</key>
        <string>'Description'</string>
        <key>NSLocationWhenInUseUsageDescription</key>
        <string>'Description'</string>
        <key>NSBluetoothAlwaysUsageDescription</key>
        <string>Description</string>

code is like this --> 

const ScanBeacons: React.FC = () => {
  const [beaconsCount, setBeaconsCount] = useState(0);
  const dispatch = useDispatch();
  
  useEffect(() => {
    Promise.resolve().then(beaconSetup);
    return () => {
      // remove event listeners
      if (isAndroid) {
        kontaktEmitter.removeAllListeners('beaconsDidUpdate');
      } else {
        kontaktEmitter.removeAllListeners('didDiscoverDevices');
        kontaktEmitter.removeAllListeners('didRangeBeacons');
      }
    };
  }, []);

  const beaconSetup = async () => {
    if (isAndroid) {
      // Android
      const granted = await requestLocationPermission();
      if (granted) {
        await connect();
        await startScanning();
      } else {
        Alert.alert(
          'Permission error',
          'Location permission not granted. Cannot scan for beacons',
          [{text: 'OK', onPress: () => console.log('OK Pressed')}],
          {cancelable: false},
        );
      }
    } else {
      // iOS
      await init()
      .then(() => startDiscovery())
      .catch((error: Error) => Alert.alert('error', error.message));
  
      /**
       * Will discover Kontakt.io beacons only
       */
      await startDiscovery();
  
      /**
       * Works with any beacon(also virtual beacon, e.g. https://github.com/timd/MactsAsBeacon)
       * Requires user to allow GPS Location (at least while in use)
       *
       * change to match your beacon values
       */
      await startRangingBeaconsInRegion({
        identifier: '',
        // uuid: 'A4826DE4-1EA9-4E47-8321-CB7A61E4667E',
        uuid: 'my uuid', // my beacon uuid
        major: 1,
        minor: 34,
      });
    }
  
    // Add beacon listener
    if (isAndroid) {
      /* works with any beacon */
      DeviceEventEmitter.addListener(
        'beaconsDidUpdate',
        async ({ beacons, region }) => {
          setBeaconsCount(beacons?.length);
          if(beacons?.length > 0){
            dispatch(
              setNearestBeacons({nearestBeacon: beacons[0]}),
            );
            if (isAndroid) {
                kontaktEmitter.removeAllListeners('beaconsDidUpdate');
            } else {
                kontaktEmitter.removeAllListeners('didDiscoverDevices');
                kontaktEmitter.removeAllListeners('didRangeBeacons');
            }
          }
        },
      );
    } else {
      const nearestPosition = await checkNearestPosition();
      /* works with Kontakt.io beacons only */
      kontaktEmitter.addListener('didDiscoverDevices', ({ beacons }) => {
        
      });
  
      /* works with any beacon */
      kontaktEmitter.addListener('didRangeBeacons', ({ beacons, region }) => {
        
      });
    }
  };

  return (
    <SafeAreaView>
      <StatusBar barStyle="dark-content" />
      <View style={styles.wrapper}>
        <Text style={styles.title}>react-native-kontaktio Example</Text>
        <Text>{`Check console.log statements (connected beacons count: ${beaconsCount})`}</Text>
      </View>
    </SafeAreaView>
  );
};

type error cannot read the properties of undefined style

enter image description here this is the image of the code iam trying to get solved

i am trying to set the cursorImg opacity to 1 but it is saying error
when i go to the inspect mode and refresh it it works fine but when i reload the page existing the inspect mode it gives the same error

And i am using locomotive js after removing locomotive js it works fine no errors are coming your text

To reduce request sent time when sending multipart/form-data as payload

I am sending a POST request
with headers- { “Content-Type”: “multipart/form-data” }
and payload is an object of FormData() class, where i have appended files like-

let formData = new FormData();
    files.forEach((fileObj: any) => {
        formData.append('file', fileObj, fileObj.path);
    })

This request takes 30seconds to be received on server. Is there any way I can reduce this time? Is it possible to achieve this by compressing the file before binding it with formData obj or by JSON.stringfy complete payload and extracting accordingly on backend?

react router doesn’t work for nested paths in S3

I have react-router-dom set up like below:

<Router>
    <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/post/:slug" element={<Post />} />
        // other routes
    </Routes>
</Router>

I have my frontend hosted in an S3 bucket and served through a CloudFront distribution. I also have configured an error page to forward to /index.html. All of my routes are working except for the “/post/:slug” route. It’s weird because if I navigate to a post using the useNavigate hook, it works and loads the post with the correct slug. However, if I reload on the post page or enter the post url directly in the browser (i.e. https://BASE_URL/post/slug/), it just shows a blank page and doesn’t seem to be able to identify the route. I’m at a loss because the post route works if I run my frontend locally. It just doesn’t work when I deploy with S3 and CloudFront.

Can’t maintain a connection to the cloud mongodb database as my IP address keeps changing

So I am building a node application where I am using the cloud mongodb atlas database. I have whitelisted my IP but the problem is after sometime my IP address changes and the connection to the mongodb server breaks. I cant manually set up my new IP address everytie, its not sustainable. I get the following error:

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist

I googled and found out that I can actually whitelist all IP addresses using 0.0.0.0. but it is not recommended. I am stuck and dont know what to do. Please help.

WHAT I TRIED:

  • Manually adding my previous IP address to the MongoDB database whitelist.

WHAT I EXPECT:

  • I’m looking for a solution that allows me to maintain a stable connection to my MongoDB database despite the frequent changes in my IP address. Ideally, this solution should be scalable and not reliant on manual updates. Any suggestions or insights would be greatly appreciated.

react render not showing anything

when I run npm run dev nothing shows up on my browser

but if I comment out in App.jsx the Header shows up perfectly
so I guess there is something wrong with Login.jsx ? but I have no clue

App.jsx

import GlobalStyles from "@styles/GlobalStyle.js";
import Header from "@components/Header/Header.jsx";
import MyPage from "@pages/MyPage/MyPage.jsx";
import Login from "@pages/Login/Login.jsx";

import './App.css'

function App() {

  return (
    <>
      <GlobalStyles />
      <Header/>
      <Login/>
    </>
  )
}

export default App;

Login.jsx

import {Input, StyledContainer, Logo, LogoWrap} from "./styles/LoginStyles.js"

function Login() {

  return (
    <div>
      <StyledContainer>
      <form>
        <div>
          <Input type="email" id="email" placeholder="email"/>
        </div>
        <div>
          <Input type="password" id="password" placeholder="password"/>
        </div>
        </form>
        </StyledContainer>
        </div>
  )
}

export default Login;

LoginStyles.js

import styled from "styled-components";

export const StyledContainer = styled.div`
    box-shadow: inset 0 0 15px blue;
    width: 1000px;
    height: 100vh;
`;

WebRTC file record form safari browser mac OS is very large than chrome window OS

Files collected from recordRTC on Safari and Mac OS browser. Since the file size exceeds 100 mb, the video can not be stored in the cloud and database.

Code setting camera resolution

async checkCamera() {
      await navigator.mediaDevices
        .getUserMedia({
          audio: true, video: {
            width: { min: 320, ideal: 640, max: 854 },
            height: { min: 180, ideal: 360, max: 480 },
            frameRate: { ideal: 15, max: 20 },
            facingMode: 'user'
          }

Code setting RTC option

options: {
        type: 'video',
        mimeType: 'video/webm;codecs=vp8,opus',
        disableLogs: true,
        timeSlice: 1000,
        // auto stop recording if camera stops
        checkForInactiveTracks: true,
      },
      timeForQuest: [300, 300, 300, 300, 300],
      timeLeft: 300,
      popupSixty: false

It may be possible to reduce the file size when recording videos from safari and mac os browsers for record or record file in cloud if file size above form 100 mb.

why do i get the error: TypeError: grid[(x + i)] is undefined?

so i have this function which is part of a project to create the conway’s game of life
and in there is a function to count the neighbours but it doesnt work

this is the code i made

function countNeighbours(grid, x, y){
  let count = 0;
  for (let i = - 1; i < 1; i++){
    for (let j = - 1; j < 1; i++){
      
      count += grid[x + i][y + j]
    } 
  }
  count -= grid[x][y];
  return count;
}

but it returns that grid[x + i] is undefined, why?

No expected output for Proxy Object

enter image description here

How to fix this problem ?

I’m encountering an issue with the search bar behavior in my Vue.js component. The search bar is not behaving as expected, and I’m seeking assistance in resolving this issue.

{{ letter }}

{{ country.label }}
{{ ‘+’ + country.value }}

computed: {
uniqueLetters () {
    if (this.search) {
        const regex = new RegExp(`${this.search}`, 'i')
        const filteredCountryLabels = this.dummyData
            .filter((country) =>
                regex.test(country.label.toUpperCase()) ||
                regex.test(country.value.toString())
            )
            .map((country) => country.label.charAt(0).toUpperCase())
        return [...new Set(filteredCountryLabels)].sort()
    } else {
        const fill = this.dummyData.map(country => country.label.charAt(0).toUpperCase())
        return [...new Set(fill)].sort()
    }
}

}

methods: {
filteredCountries (letter) {
const regex = new RegExp(${this.search}, ‘i’)
const filtered = this.dummyData.filter(country =>
(regex.test(country.label.toUpperCase()) || regex.test(country.value.toString())) &&
country.label.toUpperCase().charAt(0) === letter
)
console.log(filtered)
return […new Set(filtered)].sort()
}
}

Pcf Control(Dialog) Opening in new tab instead of same tab Dynamics 365

Image Attached I have created a dialog pcf control and i want to trigger it on click of a button in the ribbon in the view page in dynamics .Below is my code when i click on the button its opening the control in new tab but it should open as overlay/dialog in the same view. please let me know where i am going wrong.I have attached the image of the pcf dialog

function LaunchControl() {
    // Centered Dialog
    var pageInput = {
      pageType: "control",
      controlName: "bonj_pcfControls.DialogControl",
    
    };
    var navigationOptions = {
      target: 2,
      position: 1,
      width: { value: 50, unit: "%" },
      title: "Time Off Request",
    };
    Xrm.Navigation.navigateTo(pageInput, navigationOptions)
      .then(function () {
        // Called when the dialog closes
      })
      .catch(function (error) {
        // Handle error
      });
  }

I have tried changing the target and position values but no use .

how to test whether a value is an array or object

I have an object that has several members, each an array. I have another object that includes this object. In the constructor for the outer object, I’d like to say that if the user passes in an object, I use that as the value for the inner object. If they pass in an array, I create a new object, using the passed-in array for one of the values and generating the other values by some rules for defaults.

That is:

class Outer {
  constructor(inner) {
    if (inner is an object) { // this is the statement I don't know how to write
      this.inner=inner
    }
    else {
      this.inner={"value1":inner}
      this.inner.value2=... blah blah blah
    }
  }

In my first draft I said, if (typeof inner == “object”). That didn’t work because for arrays it returns true. I guess an array is a special case of an object.

So I tried to do it the other way and say inner instanceof Array. That didn’t work because for objects it returned undefined.

So … is there some way that I can test if a value is an object versus an array?

If it’s relevant, in the new Outer I want to pass the value in as a literal, i.e. I might say new Outer([1,2,3]) or new Outer({“value1″:[1,2,3],”value2”:[2,3,4]).

And yes, I know I can solve the problem by just always passing in an object, and that’s what I’m going to do for at least the short term. I was thinking that the New Outer was cleaner if I could say new Outer([1,2,3]) rather than new Outer({“value1”:[1,2,3]}). But it’s not that big a deal. But I’d like to know how to do this for future reference, at least.

how to convert image algorithm from C++ to PixiJS

There is a image algorithm which implements by C++

const uchar brightArray[11][256] = {{...},{...}};
cv::Mat mat = cv::imread('original.png',0);

int sharp = 5; // range:0~10
int brightness = 3; // range:-5~5

cv::Mat lowilter;
cv::Mat kernel = (cv::Mat_<float>(3, 3) << 0, -1.1, 0, -0.1, 3, 0, 0, -1, 0);
cv::filter2D(*mat, lowilter, mat->depth(), kernel);

cv::Mat tmpImg = cv::Scalar(128, 128, 128) - abs(cv::Scalar(128, 128, 128) - *mat);

cv::Mat sharpImg = cv::Mat::zeros(mat->rows, mat->cols, CV_8UC3);
sharpImg = *mat + sharp * tmpImg.mul(lowilter) / 128;

cv::Mat table(1, 256, CV_8U);
memcpy(table.data, brightArray[brightness + 5], 256);
cv::LUT(sharpImg , table, *mat);

cv::blur(*mat, *mat, cv::Size(3, 3));

Now i want to achieve the same effect by PixiJS, what can i do ?

Here I have knowed ColorMatrixFilter which can be used to adjust brigtness.,Be like:

// Apply brightness adjustment
const brightness = 0.5; // Example brightness value (adjust as needed)

// Create a ColorMatrixFilter
const colorMatrix = new PIXI.filters.ColorMatrixFilter();

// Apply brightness using the ColorMatrixFilter
colorMatrix.brightness(brightness, false);

// Apply the filter to the sprite
sprite.filters = [colorMatrix];

but i still don’t konw how to do.

PS: a newer within PixiJS