Parameters of my function in React child component are not being passed to the parent component’s function. Why is this happening?

In the parent:

 const [newPinPosition, setNewPinPosition] = React.useState({ lat: 0 , lng: 0 });
 const updateNewPinPos = (pos) => {
   console.log(pos);
   setNewPinPosition({ lat: pos.lat, lng: pos.lng });
  };

  // in the render method of the parent react component
  <Draggable
     draggable={draggable} 
     newPinPosition={newPinPosition}   
     setCenterPos={() => { getCurrentCenter(map); }}
     updatePos={() => { updateNewPinPos(newPinPosition); }}
   />

In the child:

const updatePosition = useCallback(() => {
const marker = markerRef.current;
// console.log(`marker._latlng : ${marker._latlng}`);
props.updatePos(marker._latlng);
});

<StyledMarker   
   position={props.newPinPosition}
   draggable={props.draggable}
   ref={markerRef}
   eventHandlers={{
      dragend: () => {updatePosition();},
      }}
 >

I am using React Leaflet to render a world map. I am trying to update the state (position object) of a draggable marker on the dragend event.

When dragend fires, updatePos fires as well (as it should) and it calls props.updatePos (as it should).

The issue is this: in the console.log of the child, I have the position object of the marker. This is the expected and correct behavior. In the parent component, the updateNewPinPos function is being called, but the pos parameter is an empty object. This happens even though I am calling the function with the marker._latlang object. Why is this happening? How is this object being “lost” between child and parent?

I am quite new to react so I apologize if this is pretty basic, but I am struggling a lot with this. I can provide more information if necessary.

React 17 Warning: Did not expect server HTML to contain a in

I have read through the existing solutions and still cant seem to get it to work.

components/NavBar.tsx

import { Box, Link } from "@chakra-ui/react";
import { FunctionComponent } from "react";
import NextLink from "next/link";

interface NavBarProps {}

const NavBar: FunctionComponent<any> = (props) => {
  return (
    <Box {...props} bg="tomato" w="100%" p={4} ml={"auto"} color="white">
      <NextLink href="/login">
        <Link mr={4}>Login</Link>
      </NextLink>
      <NextLink href="/register">
        <Link>Register</Link>
      </NextLink>
    </Box>
  );
};

export default NavBar;

index.tsx

import NavBar from "../components/navbar";

const Index = () => (
  <>
    <NavBar></NavBar>
    <div>hello world</div>
  </>
);

export default Index;

Error Screenshot
Error Messsage

NestJS/Express return PDF file from external URL in response

I’m calling an external API that returns a PDF file and I want to return this PDF file in my controller function response.

In My controller class:

  @Get(':id/pdf')
  async findPdf(@Param('id') id: string, @Res() res: Response) {
    const response = await this.documentsService.findPdf(id);

    console.log(response.data); 
    // this prints the following:
    // %PDF-1.5
    // %����
    // 2 0 obj
    // << /Type /XObject /Subtype /Image /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter // /DCTDecode /Width 626 /Height
    //  76 /Length 14780>>
    //  stream
    // and go on...

    return res
      .status(200)
      .header('Content-Type', 'application/pdf')
      .header('Content-Disposition', response.headers['content-disposition'])
      .send(response.data);
  }

In My service class:

  findPdf(id: string): Promise<any> {
    return firstValueFrom(
      this.httpService
        .get(`/docs/${id}/pdf`)
        .pipe(map((response) => response))
        .pipe(
          catchError((e) => {
            throw new BadRequestException('Failed to get PDF.');
          }),
        ),
    );
  }

However I’m getting a blank PDF file in my response.

The internal API call works fine, I’ve tested it from Postman and the PDF file is correct.

What am I doing wrong?

Yandex maps создание карты

Нужна помощь в реализации простого скрипта на яндекс карте.

  1. Пользователь щелкает на карте в любое место и ставит два маркера на карту. Так же есть возможность удалить эти точки.
  2. Записать эти точки в файл в виде географических координат.

JS: Strange toString behaviour when extending Array class

I’m trying to use the map function inside the toString overwritten in my Array subclass and I’m seeing a strange behaviour. It looks like that .map is calling the constructor of my subclass for no apparent reason and throwing a TypeError.

class Seq extends Array {
    constructor(seq = '') {
        super();
        (seq.match(/.{2}/g) || []).forEach((mi) => this.push(mi));
    }
    toString() {
        return this.map(it=>it).join('');
    }
}
new Seq('1643').toString() //expects to see '1643' as the output but getting a TypeError

Recreating the array in the toString method fixes the problem, but I’d like to understand why.

toString() {
    return [...this].map(it=>it).join('');
}

Programmatically Positioning A Symbol Within A Group

I have the following code:

const docGroup = new Group({
    name: ‘@Note’
})

const noteSymbolInstance = noteSymbolMaster.createNewInstance()
noteSymbolInstance.parent = docGroup

const arrowSymbolInstance = arrowSymbolMaster.createNewInstance()
arrowSymbolInstance.parent = docGroup

const page = doc.selectedPage

docGroup.parent.page

Right now, the two symbols are positioned right on top of each other, in the top left corner of the group. I want to position the second symbol to the right of the first one, within the group. My question is this: How do I position a symbol within a group? This would be before adding it to the page.

Sketch version: 87.1

in javascript I want to creat a simple few lines function to get Heikin-Ashi from close high low open

This question if about javascript (not pyhton or pine script).

I just want to create a simple few lines function => “convert” FROM regular open, high, low and close from an exchange TO a Heikin Ashi

variables open, high, low, close are from an exchange API that return an array with regual candlesticks

here the formula

ha_open = (last_ha_open - last_ha_close) / 2;
ha_close = (open + high + low + close)/4;
ha_high = max(high, ha_open, ha_close);
ha_low = min(low, ha_open, ha_close);

where I get “stuck” is the “last_ha_open” and “last_ha_close”

**** it’s easy to save ha_open and ha_close with .push into an array

**** it’s easy to retrieving them with array[(array.length -1)] (last of array)

**** it’s where it gets tricky… : the infinite loop of calculate the first in the chain.. if wrong, the values don’t match…

is there a javascript way to do this ????

Notes i could find about Heikin-ashi

Obs:
The first Heikin-Ashi close equals the average of the open, high, low and close ((O+H+L+C)/4).
The first Heikin-Ashi open equals the average of the open and close ((O+C)/2).
The first Heikin-Ashi high equals the high and the first Heikin-Ashi low equals the low.

Java ‘calculator ‘ not providing ‘running total’ when adding last parseFloat

I am attempting to construct a basic sales calculator, based on the user’s selections.

The code below works fine, except for one issue…

With the ‘+ parseFloat(e)’ attribute removed, the user gets a nice, running total as they select or deselect their options.

However… when I attempt to add that aspect back into the equation, it will not produce a total until all selections have been made.

Instead… it will only produce ‘$NaN’, until all selections are made.

I would like to be able to achieve the handy ‘running total’ with the ‘+ parseFloat(e)’ attribute included in the equation. I can’t seem to get that to function. Any help would be appreciated.

<html>

<head>

<style>


.plus { display: none; }   


</style>

</head>

<body>

<!-- Start Pricing Calculator -->


<h1>Ice Cream Calculator</h1>

<p>To calculate the price of your Ice Cream, please make your selections below.</p>

<br>

<select id="scoops" name="scoops" onchange="calcuMath()" required>

<option selected="true" disabled="disabled">How Many Scoops?</option> 
<option value="1">1 Scoop = $1.00</option> 
<option value="2">2 Scoops = $2.00</option>

</select>

<br>
<br>

<p>Toppings: (Optional)</p>

<select id="plus" class="plus"><option value="add" id="add">+</option></select>

<input type="hidden" id="nuts" name="nuts" value="0">
<input type="checkbox" onchange="this.previousSibling.value=1-this.previousSibling.value; 
calcuMath();">&nbspNuts $1.00

<br>
<br>

<select id="plus" class="plus"><option value="add" id="add">+</option></select>

<input type="hidden" id="sprinkles" name="sprinkles" value="0">
<input type="checkbox" onchange="this.previousSibling.value=1-this.previousSibling.value; 
calcuMath();">&nbspSprinkles $1.00

<br>
<br>

<select id="plus" class="plus"><option value="add" id="add">+</option></select>

<input type="hidden" id="syrup" name="syrup" value="0">
<input type="checkbox" onchange="this.previousSibling.value=1-this.previousSibling.value; 
calcuMath();">&nbspSyrup $1.00

<br>
<br>
<br>

<select id="plus" class="plus"><option value="add" id="add">+</option></select>

<select id="dish" name="dish" onchange="calcuMath()" required>

<option selected="true" disabled="disabled">Cup or Cone</option> 
<option value="1">Cup = $1.00</option>
<option value="2">Cone = $2.00</option> 

</select>

<br>
<br>
<br>

TOTAL: $<a id="result"></a>

<script>
        
function calcuMath() {
var z;
var a = document.getElementById("scoops").value;
var b = document.getElementById("nuts").value;
var c = document.getElementById("sprinkles").value;
var d = document.getElementById("syrup").value;
var e = document.getElementById("dish").value;
var sel = document.getElementById("plus");
var selection = sel.options[sel.selectedIndex].value;
var more = document.getElementById("add");
if (selection == "add") 
{ z = parseFloat(a) + parseFloat(b) + parseFloat(c) + parseFloat(d) + parseFloat(e); }

document.getElementById("result").innerHTML = "" + z + ""; }   
        
</script>


<!-- End Pricing Calculator -->


</body>
</html>

Select option presets messing up after manual select

I have a list of permissions in a <select> element, and three radio buttons to select presets, instead of seelcting permissions manually.

I use the same trigger function for all four elements, and the radio buttons work beautifully until you select something manually, and then they scre up completely.

I assume that it is my XOR if(selectItems.includes(option.value) ^ invert) ... that is clogging up the works, but when I do step-through debugging, it looks correct, but the result is not the expected one…

document.getElementById('userTypeAdminInhouse').addEventListener('change', selectScope);
document.getElementById('userTypeAdminClient').addEventListener('change', selectScope);
document.getElementById('userTypeUser').addEventListener('change', selectScope);
document.getElementById('scope').addEventListener('change', selectScope);

function selectScope(e) {
    let scopeSelect = document.getElementById('scope');
    let selectItems = [];
    let invert = false;
    if (e.target.id == 'userTypeUser') {
        //only this one permission
        selectItems = ['user:self']
    } else if (e.target.id == 'userTypeAdminClient') {
        selectItems = ['user:read', 'admin:read', 'stats:read']
    } else if (e.target.id == 'userTypeAdminInhouse') {
        invert = true;
        //all permissions except this one
        selectItems = ['user:self']
    } else if (e.target.id == 'scope') {
        document.getElementById('userTypeUser').checked = false;
        document.getElementById('userTypeAdminClient').checked = false;
        document.getElementById('userTypeAdminInhouse').checked = false;
    }
    if (selectItems.length > 0) {
        for (const option of document.querySelectorAll('#scope option')) {
            /* If option value contained in values, set selected attribute */
            if (selectItems.includes(option.value) ^ invert) {
                option.setAttribute('selected', 'selected');
            }
            /* Otherwise ensure no selected attribute on option */
            else {
                option.removeAttribute('selected');
            }
        }
    }
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<select class="form-control" size="10" id="scope" name="scope[]" multiple required>
    <option title="Read list of admin users/all projects" value="admin:read">admin:read | Read list
        of admin users/all projects</option>
    <option title="Create admin users" value="admin:write">admin:write | Create admin users</option>
    <option title="Read client details" value="client:read">client:read | Read client details</option>
    <option title="Edit/Create client" value="client:write">client:write | Edit/Create client</option>
    <option title="Read project" value="project:read">project:read | Read project</option>
    <option title="Create/Edit project" value="project:write">project:write | Create/Edit project
    </option>
    <option title="Read User details" value="user:read">user:read | Read
        User details</option>
    <option title="User. Cannot log in to admin parts" value="user:self">user:self | User.
        Cannot log in to admin parts</option>
    <option title="Create/edit Users" value="user:write">user:write | Create/edit
        Users</option>
    <option title="Read statistics" value="stats:read">stats:read | Read statistics</option>
    <option title="Read story list" value="story:read">story:read | Read story list</option>
</select>

    <div class="form-check">
        <input class="form-check-input" type="radio" name="userType" id="userTypeAdminInhouse">
        <label class="form-check-label" for="userTypeAdminInhouse">
            Admin User (inhouse)
        </label>
    </div>
    <div class="form-check">
        <input class="form-check-input" type="radio" name="userType" id="userTypeAdminClient">
        <label class="form-check-label" for="userTypeAdminClient">
            Admin User (client)
        </label>
    </div>
    <div class="form-check">
        <input class="form-check-input" type="radio" name="userType" id="userTypeUser">
        <label class="form-check-label" for="userTypeUser">
            User
        </label>
    </div>

Vue3 scoped CSS not applied to component

I have noted some issues when trying to apply class styles to a specific component, and reloading does not help; it does not have to do with the hot reload, the development server or anything like that.

The issue seems to be that even though the styles in my Component.vue get applied after the styles in my App.vue, the applied styles from my component do not seem to be changing anything from the applied styles in my App.vue ; I still got a bottom margin that I’m trying to overwrite to 0 in my Component.vue

Or am I doing something wrong with my selectors?

This is from my App.vue:

[class$="__heading"] {
    text-align: center;
    margin-bottom: 5rem;
}

Here is my Component.vue selector, even more specific I believe:

.listado__heading {
    margin: 0;
    font-size: 3rem;
    color: var(--primario);
}

If I cut that selector from my component and paste it in the App.vue, everything works as I want it to, but it would be better to have my component’s style inside of it.

What can I do so I can have the component’s style inside the component and make it work as I want it to? I want to apply margin: 0; to that heading, but want to leave the margin-bottom: 5rem; for the rest of the headings.

Thanks!

How do I solve X is 7 or more greater than Y

I am new here, but i’m simply trying to figure out why this javascript is not working in my math program
How do i solve this problem:
X is 7 or more greater than Y in javascript.
this is what i have tried so far:

function solve (x,y) {
            if(x >= (y +7) ){
                return "green"
            }

            else {
                return "blue";
            }

Uncaught Error: [RouteWrapper] is not a component. All component children of must be a or

I’m using React Router v6 and am creating private routes for my application.

In file Route.js, I’ve the code

export default function RouteWrapper({
  element: Element,
  isPrivate,
  ...rest
}) {
  const { signed, loading } = useContext(AuthContext);

  if (loading) {
    return <div></div>;
  }

  if (!signed && isPrivate) {
    return <Navigate to="/" />;
  }

  if (signed && !isPrivate) {
    return <Navigate to="/dashboard" />;
  }

  return <Route {...rest} render={(props) => <Element {...props} />} />;
}

And in file index.js I’ve written as:

  return (
      <Routes>
        <Route path="/" element={SignIn} />
        <Route path="/register" element={SignUp} />

        <Route path="/dashboard" element={Dashboard} isPrivate />
        <Route path="/profile" element={Profile} isPrivate />
        <Route path="/customers" element={Customers} isPrivate />
        <Route path="/new" element={New} isPrivate />
        <Route path="/new/:id" element={New} isPrivate />
      </Routes>
  );
}

Is there something I’m missing?

React App Build Failure (sass/resolve-url-loader)

Creating a react app off this tutorial (https://www.youtube.com/watch?v=yqe5UB_BF7Q) and got this error when trying to apply the styles. The last step involved deleted the index.css file and replacing it with styles.scss.

I already tried npm install -g sass to no luck, anyone know what to do here?

Error output below.

Failed to compile.

Cannot find module ‘sass’
Require stack:

  • /Users/amarcin/web/node_modules/sass-loader/dist/utils.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/index.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/cjs.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/loadLoader.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/LoaderRunner.js
  • /Users/amarcin/web/node_modules/webpack/lib/NormalModule.js
  • /Users/amarcin/web/node_modules/webpack-manifest-plugin/dist/index.js
  • /Users/amarcin/web/node_modules/react-scripts/config/webpack.config.js
  • /Users/amarcin/web/node_modules/react-scripts/scripts/start.js
    WARNING in ./src/styles.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles.scss)
    Module Warning (from ./node_modules/resolve-url-loader/index.js):
    resolve-url-loader: webpack misconfiguration
    webpack or the upstream loader did not supply a source-map

ERROR in ./src/styles.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles.scss)
Module Error (from ./node_modules/sass-loader/dist/cjs.js):
Cannot find module ‘sass’
Require stack:

  • /Users/amarcin/web/node_modules/sass-loader/dist/utils.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/index.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/cjs.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/loadLoader.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/LoaderRunner.js
  • /Users/amarcin/web/node_modules/webpack/lib/NormalModule.js
  • /Users/amarcin/web/node_modules/webpack-manifest-plugin/dist/index.js
  • /Users/amarcin/web/node_modules/react-scripts/config/webpack.config.js
  • /Users/amarcin/web/node_modules/react-scripts/scripts/start.js

ERROR in ./src/styles.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles.scss)
Module build failed (from ./node_modules/resolve-url-loader/index.js):
Error: resolve-url-loader: error processing CSS
PostCSS received undefined instead of CSS string
at new Input (/Users/amarcin/web/node_modules/resolve-url-loader/node_modules/postcss/lib/input.js:38:13)
at encodeError (/Users/amarcin/web/node_modules/resolve-url-loader/index.js:287:12)
at onFailure (/Users/amarcin/web/node_modules/resolve-url-loader/index.js:228:14)

webpack compiled with 2 errors and 1 warning

TypeError: member.presence?.activities.values is not iterable (cannot read property Symbol(Symbol.iterator))

o código funciona porem quando testa o comando para que esta offline da erro

Print funciomando: https://i.imgur.com/YyYqh4J.png

Print quando menciona quem ta offline: https://i.imgur.com/tXs53No.png

o erro que da no terminal

  <rejected> TypeError: member.presence?.activities.values is not iterable (cannot read property Symbol(Symbol.iterator))
  at Object.run (D:Discord.js-v13-Example-maincommandsTestesuser.js:73:54)

o código

const activities = [];
  let customStatus;
  for (const activity of member.presence.activities.values()) { // ERRO E NESSA LINHA 
    switch (activity.type) {
      case 'PLAYING':
        activities.push(`Playing **${activity.name}**`);
        break;
      case 'LISTENING':
        if (member.user.bot) activities.push(`Listening to **${activity.name}**`);
        else activities.push(`Listening to **${activity.details}** by **${activity.state}**`);
        break;
      case 'WATCHING':
        activities.push(`Watching **${activity.name}**`);
        break;
      case 'STREAMING':
        activities.push(`Streaming **${activity.name}**`);
        break;
      case 'CUSTOM_STATUS':
        customStatus = activity.state;
        break;
    }
  }