How to assign non-string dynamic attributes to a nested component in Svelte?

For a Svelte component with dynamic attributes which are not strings (i.e. a number and array), for example MySimpleComponent.svelte:

<script lang="ts">
    export let index : number;
    export let paragraphs: string[];
</script>

<h3> { index } </h3>
{#each paragraphs as paragraph, i}
    <p> { paragraph } </p>  
{/each}

What is the correct syntax to place that component in a different component, and specify those attributes inline? I am trying this, but it doesn’t work:

<script lang="ts">
    import MySimpleComponent from './MySimpleComponent.svelte';
</script>

<MySimpleComponent
    index = { 1 },
    paragraphs = {[
        'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
        'Aut vel quia vel ducimus eius perferendis.' 
    ]},
/>

The error is TS 2322: Type 'string' is not assignable to type 'number' (or to type string[]). I assume because the { } syntax is implicitly expecting a string inside, meaning { 1 } is really '1', not 1.

What is the correct way to do this? Thanks.

Unable to append an image to d3 svg element

I am working on a power bi custom visual using d3 and typescript. I have declared my constructor as below:

constructor(options: VisualConstructorOptions) {
    this.host = options.host;

    // Declare the svg property
    this.svg = d3
      .select(options.element)
      .append("svg")
      .classed(Visual.ClassName, true);

    this.svg
      .append("svg:image")
      .attr(
        "xlink:href",
        "http://www.google.com/intl/en_com/images/logo_plain.png"
      )
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", 40)
      .attr("height", 40);
  }

But the thing is no actual image appears on canvas/svg. Only an image icon appears as shown below. What might be the issue and its solution.
And thanks in advance.

enter image description here

Why current time is 6 hours behind in javascript? [duplicate]

I am using express.js. Javascript current datetime is 6 hours behind from my local time. How can I get the actual correct time in any local timezone automatically ?

I dont want to set timezone manually in my application. Instead, want to make it dynamic as I am using my app worlwide. Is it possible ?

var d = new Date()

console.log(d);

Select field value not changing on setState in onChange

My Select value is gotten from data.RowCount.Value. Changing the value is not reflected until the next render.

const [data, setData] = ({RowCount: {"Value": 5}})

...
<TextField 
    select 
    value={data.RowCount.Value} 
    onChange={(e) => {
        setData((prev) => {
            prev.RowCount.Value = e.target.value; 
            return prev;
        });
    }}>
    <MenuItem>Item</MenuItem>
</TextField>

Typescript store updating one click late in a click event listener

I’m trying to know if the shift key is being pressed when clicking a checkbox (I’m using Svelte). I need a store that will be updated in “real time” according to the state of the shift key.

I have a property in a store.ts file:

export let is_shift_pressed = writable(false)

In the <script> tag of my Svelte component:

import { is_shift_pressed } from './stores/store';

window.addEventListener('click', async function (e) {
   // e.shiftKey has always the correct value that I expect
   is_shift_pressed.set(e.shiftKey);
   // but the store is late of 1 click
});

I have a checkbox:

<input type="checkbox" on:click={checkboxClicked}/>

When the checkbox is clicked, I try to display the value of the store. It should be equal to the value of e.shiftKey at the moment when the store was updated.

function checkboxClicked(){
   console.log(shiftPressed)
   // prints the value of the previous click
}

Uploaded images: uploaded SVGs do not fit display container

I have a form with an upload image field. Images can be png, jpeg or svgs.
When the image is uploaded and is an SVG, is doesnt fit the container size.
Cloudify is being used to handle the URL of the uploaded data.
Is not a SVG inline, I have no control of the format the user will upload.

<img
  class="vehicle-image"
  [src]="provUrl(imageUrl)"
  alt="Uploaded Image"
/>

.vehicle-image {
  object-fit: contain;
  width: 100%;
  height: 100%;
}

it works fine for pngs or jpegs, but not for SVGs…what could I have to work this around for SVGs also?

Individual Regex matching for 2 similar expressions

I have 2 regexes that share the same first half. The second regex has additional parameters that are a param and number.

First Regex: //param1/param2/param3/
Second Regex //param1/param2/param3?additionalParam=([0-9]+)/

I choose to compare different values against these regexes which I have placed in a config file and loop over. If they match then it returns a value.

When I run a list of values against them, the first regex always returns and the second one never returns as it matches the input value on the first regex and never reaches the second to compare.

for example:

string1: 'param1/param2/param3'  //returns on Regex1 
string2: 'param1/param2/param3?additionalParam=123456'  //still returns on Regex1 because it matches the first part. 

How do I match on them individually so I get the right return value?

login form with android studio and reactive-native

I have a react-native app. And I try to login with email and password. I am using android studio for the emulator.

But the problem I am facing is that if I try to login with variables it deosn’t work. But if I do it hardcoded it works.

So this is my login form:

export const LoginScreen = ({ navigation }) => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const { onLogin, error, isLoading } = useContext(AuthContext);

    return (
        <AccountBackground>
            <AccountCover />
            <Title>Dierenwelzijn app</Title>
            <AccountContainer>
                <AuthInput
                    label="E-mail"
                    value={email}
                    textContentType="emailAddress"
                    keyboardType="email-address"
                    autoCapitalize="none"
                    onChangeText={(u) => setEmail(u)}
                />
                <Spacer size="large">
                    <AuthInput
                        label="Password"
                        value={password}
                        textContentType="password"
                        secureTextEntry
                        autoCapitalize="none"
                        onChangeText={(p) => setPassword(p)}
                    />
                </Spacer>

                {error && (
                    <Spacer size="large">
                        <Text variant="error">{error}</Text>
                    </Spacer>
                )}

                <Spacer size="large">
                    {!isLoading ? (
                        <AuthButton onPress={() => onLogin({ email, password })}>Login</AuthButton>
                    ) : (
                        <ActivityIndicator animating={false} />
                    )}
                </Spacer>
            </AccountContainer>
            <Spacer size="large">
                <AuthButton mode="contained" onPress={() => navigation.goBack()}>
                    Back
                </AuthButton>
            </Spacer>
        </AccountBackground>
    );
};

and the context:

 
 export const AuthContextProvider = ({ children }) => {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [user, setUser] = useState(null);

    
    const onLogin = (email, password) => {      
        setIsLoading(true);
        loginRequest(email, password)
            .then((u) => {              
                setUser(u);
                setIsLoading(false);
            })
            .catch((e) => {
                setIsLoading(false);
                setError(e.toString());
            });
    };

    return (
        <AuthContext.Provider value={{ isAuthenticated: !!user, isLoading, error, user, onLogin }}>
            {children}
        </AuthContext.Provider>
    );
};

So this doesn’t work.I get this error:

Object {
  "email": Array [
    "Enter a valid email address.",
  ],
  "password": Array [
    "This field is required.",
  ],
}

But if I do:

loginRequest("[email protected]", "password")

it works.

Question: how to use the variables to login?

ul element is hidden behind another html element, z-index doesn’t work either

My application has a side menu that converts to a slimmer mode when clicking on a certain button. Some items in the menu have sub-menu items. The issue I am facing right now is that the sub-menu works fine when the menu is in expanded mode but it doesn’t work fine when in the slim mode. It’s hidden behind another element. I am attaching a screenshot for your reference, just to show you what I mean.

enter image description here

I am also attaching the css media query that corresponds to this

&.menu-layout-slim {
.layout-menu {
                    padding: 0;

                    > li {
                        position: relative;

                        &.layout-root-menuitem {
                            > .layout-menuitem-root-text {
                                display: none;
                            }

                            > a {
                                display: block;
                            }
                        }

                        > a {
                            text-align: center;
                            padding: 15px;
                            padding-left: 20px;

                            i:first-child {
                                font-size: 19px;
                            }

                            span:not(.p-ink), i.menuitem-toggle-icon {
                                display: none;
                            }

                            &:hover + .layout-menu-tooltip {
                                display: block;
                            }
                        }

                        > ul {
                            @include overlay-shadow();
                            border: 1px solid #cccccc;
                            background-color: $menuBg;
                            position: absolute;
                            top: 0;
                            left: 73px;
                            display: none;
                            min-width: 200px;
                            border-radius: $borderRadius;


}

I am also attaching the sub menu component for your reference

<ng-template ngFor let-child let-i="index" [ngForOf]="root ? item : item.items">
  <li [ngClass]="{ 'active-menuitem': isActive(i) }" [class]="child.badgeStyleClass"
    *ngIf="child.visible === false ? false : true">
    <a [href]="child.url || '#'" (click)="itemClick($event, child, i)" (mouseenter)="onMouseEnter(i)" class="ripplelink" [name]="child.key"
      *ngIf="!child.routerLink" [attr.tabindex]="!visible ? '-1' : null" [attr.target]="child.target"  [tooltipDisabled]="!app.isSlim()" pTooltip="{{child.label}}" tooltipPosition="right">
      <i [ngClass]="child.icon" class ="col-icon"></i><span>{{ child.label }}</span>
      <i class="fa fa-fw fa-angle-right menuitem-toggle-icon" *ngIf="child.items"></i>
      <span class="menuitem-badge" *ngIf="child.badge">{{ child.badge }}</span>
    </a>

    <a (click)="itemClick($event, child, i)" (mouseenter)="onMouseEnter(i)" class="ripplelink" *ngIf="child.routerLink" [name]="child.key"
      [routerLink]="child.routerLink" routerLinkActive="active-menuitem-routerlink"  [tooltipDisabled]="!app.isSlim()" pTooltip="{{child.label}}" tooltipPosition="right"
      [routerLinkActiveOptions]="{ exact: true }" [attr.tabindex]="!visible ? '-1' : null" [attr.target]="child.target" style="height: '*'">
      <i [ngClass]="child.icon" class ="col-icon"></i><span>{{ child.label }}</span>
      <i class="fa fa-fw fa-angle-right menuitem-toggle-icon" *ngIf="child.items"></i>
      <span class="menuitem-badge" *ngIf="child.badge">{{ child.badge }}</span>
    </a>
    <div class="layout-menu-tooltip">
      <div class="layout-menu-tooltip-arrow"></div>
      <div class="layout-menu-tooltip-text">{{ child.label }}</div>
    </div>
    <div class="submenu-arrow" *ngIf="child.items"></div>
    <ul app-submenu class="sub-menu" [item]="child" *ngIf="child.items" [visible]="isActive(i)" [reset]="reset"
      [parentActive]="isActive(i)" [@children]="
              (app.isSlim() || app.isHorizontal()) && root
                  ? isActive(i)
                      ? 'visible'
                      : 'hidden'
                  : isActive(i)
                  ? 'visibleAnimated'
                  : 'hiddenAnimated'
          "></ul>
  </li>
</ng-template>

I have tried making the position as fixed but it throws the sub-menu to the top and it could be an issue as I need the sub-menu in fron of the respective menu item.

enter image description here

I am also attaching the animations property of the component in the ts file.

@Component({
  // tslint:disable-next-line:component-selector
  selector: '[app-submenu]',
  templateUrl: './app-sub-menu.component.html',
  styleUrls: ['./app-sub-menu.component.scss'],
  animations: [
    trigger('children', [
      state(
        'hiddenAnimated',
        style({
          height: '0px'
        })
      ),
      state(
        'visibleAnimated',
        style({
          height: '*'
        })
      ),
      state(
        'visible',
        style({
          display: 'block'
        })
      ),
      state(
        'hidden',
        style({
          display: 'none'
        })
      ),
      transition('visibleAnimated => hiddenAnimated', animate('400ms cubic-bezier(0.86, 0, 0.07, 1)')),
      transition('hiddenAnimated => visibleAnimated', animate('400ms cubic-bezier(0.86, 0, 0.07, 1)'))
    ])
  ]
})

Let me know in the comments if I need to provide any other detail that help you in debugging the issue.

i want to generate a key of pw , why the result is undefined?

why the result is undefined?

let PW = 26;
let pwArray = [0,1,2,3,4,5,6,7,8,9]
let submitEl = document.getElementById("submit");
let element = "";

for (let index = 0; index < pwArray.length; index++) {
    const RandomNum = Math.floor(Math.random()*pwArray.length);
    let pwSlice = pwArray.slice(RandomNum,RandomNum+1);
    let PWc = pwSlice*RandomNum;
     element += pwArray[PWc];

}
console.log(element);

please help,thanks

why the result is undefined?

how to interact with my internal web application through an outlook add in

I have an internal website where we used to track and update our attendance. Now i want to develop an outlook add in through which I can apply the leave from the add in itself instead of logging into the internal website. We can assume that the credentials are same for both outlook and the internal application.

I am new to the whole concept of Add ins and I created a sample application and I think we might need an api or something like that to interact with the internal application. I need some solid examples to proceed further. I want to know if its possible and if so how to change the manifest and javascript accordingly.

Next JS does not identify GSAP plugin module added via cdn

I’m trying to use a gsap plugin module via cdn in my Next JS project.
So i started adding Script tags inside the Head tag in my _document.js
This is my code:

import { Html, Head, Main, NextScript } from "next/document";
import Script from "next/script";
export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <Script
          src={
            "https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/ScrollTrigger.min.js"
          }
          strategy="beforeInteractive"
        />
        <Script
          src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"
          strategy="beforeInteractive"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Then i tried to use ScrollTrigger inside my index.jsx, like this:

 ScrollTrigger.addEventListener("scrollEnd", () =>
    console.log("scrolling ended!")
  );

But i’m getting this error:

ReferenceError: ScrollTrigger is not defined

I’m not a CDN user, but in GSAP docs this is what they recommend. Since sometimes it has instant load, and it has a great amount of users.
I’ve already read the next js docs. That’s why i added these Script tags. But i am still getting this error…ERROR

Why isn’t my error overriding the try block in try / catch? [duplicate]

I am working on my very first javascript application (a dictionary app) and I am having trouble using try / catch. The try block seems to work with no problems and I can search for words in the API, however the error does not work.

When searching for a word that does not exist, there should be an error message instead of the search result, but this is not appearing. Instead, the data still seems to be getting returned from the function fetchData() and passed into the subsequent function displayData() and causing the error.

I might be incorrect here, but shouldn’t the catch block prevent the return statement from the try block from being executed? I have tried adding return to the catch block to see if it would change anything, but I’m out of my depth here and can’t find a solution. Can anyone help point me in the right direction?

Here is a jsfiddle: https://jsfiddle.net/trpxL0kj/

Here is my code:

const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";
const form = document.querySelector('.form');
const input = document.querySelector('.form-input');
const content = document.querySelector('.content');
const details = document.querySelector('.details');


const fetchData = async () => {
  let inputWord = document.querySelector('.form-input').value;
  try {
    const response = await fetch(`${url}${inputWord}`);
    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    details.innerHTML = 'This word is not in the dictionary.';
  }
};

const displayData = async (entry) => {
  const word = entry[0].word;
  const grammar = entry[0].meanings[0].partOfSpeech;
  const definition = entry[0].meanings[0].definitions[0].definition;
  const example = entry[0].meanings[0].definitions[0].example || '';
  details.innerHTML = ` 
    <article class="result">
      <p class="word">${word}</p>
      <p class="grammar">${grammar}</p>
      <p class="definition">${definition}</p>
      <p class="example">${example}</p>
    </article>
  `;
};

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const data = await fetchData(url);
  displayData(data);
});

event emitter and *ngIf render component on second click in Angular

I have one modal which is render based on condition. I use jQuery to load this modal conditionally. I’ve created this modal as separate component. In bootstrap 4 it’s working fine, but in bootstrap 5 it did not render on first click. I need to click two times to render my modal.

button-modal.componenet.html

 <div *ngIf="isVPN && isAddDeviceEnabled" class="mb-2">
       <button
          type="button"
          (click)="addVpnEntry.emit({ isAddVpn: true, openFor: 'ea' })"
          class="btn btn-outline-primary"
          data-bs-toggle="modal"
          data-bs-target="#addVpnInterface"
          >
       {{ 'Link EA'}}
       </button>
    </div>

botton-modal.component.ts

      @Component({
            selector: 'app-botton-modal',
            templateUrl: './botton-modal.component.html'
        })
        export class BottonModalComponent{
        @Output() addVpnEntry?: EventEmitter<any> = new EventEmitter<any>();
        
        linkPEDevice(isAddVPN: boolean, openFOR: string) {
                this.addVpnEntry.emit({ isAddVpn: isAddVPN, openFor: openFOR });
            }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

placed-modal-page.component.html

<!-- Modal -->
    <div *ngIf="isAddVpnEntry">
        <div id="addVpnInterface" class="modal fade" role="dialog">
            <modal-implementation-componenet
                *ngIf="openReason === 'ea'"
                (close)="close($event)"
                [vpnData]="selectedVpnInterface"
                [deviceInfo]="deviceInfo"
            >
            </modal-implementation-componenet>
        </div>
    </div>

placed-modal-page.component.ts

  @Component({
        selector: 'app-placed-modal-page',
        templateUrl: './placed-modal-page.component.html',
        styleUrls: ['./placed-modal-page.component.css'],
        encapsulation: ViewEncapsulation.None})
        export class DeviceInterfacesEthernetComponent implements OnDestroy {
        @ViewChild(BottonModalComponent) childcomponent: BottonModalComponent;
    addVpnEntry({ isAddVpn, openFor }) {
            if (isAddVpn) {
                this.openReason = openFor;
                $('#addVpnInterface').modal('show');
                this.isAddVpnEntry = true;
            }
        }   

When I click first time, It throws following error and add the placed-modal-page.component.html code in DOM and then on second click the modal is showing.

    caught TypeError: Cannot read properties of undefined (reading 'backdrop')
    at bt._initializeBackDrop (scripts.js:11:138858)
    at new bt (scripts.js:11:137752)
    at bt.getOrCreateInstance (scripts.js:11:115079)
    at HTMLButtonElement.<anonymous> (scripts.js:11:141870)
    at HTMLDocument.We (scripts.js:11:111355)
    at W.invokeTask (polyfills.js:23:9522)
    at W.runTask (polyfills.js:23:4509)
    at W.invokeTask [as invoke] (polyfills.js:23:10671)
    at oe (polyfills.js:23:24586)
    at ye (polyfills.js:23:25005)

Also, if we emit object then how we can obtain various field valued using $event variable. IN our case we have object of {isAddVPN: boolean, openFOR: string}?

Append data to streaming response

I am creating an application built on top of OpenAI’s chatGPT. I am using their API’s streaming option to allow streaming. In my Remix (nodejs) backend, I simply pipe the response through to the client:

const theresponse:any = await openai.createChatCompletion(...);
return new Response(theresponse.body, { headers: headers  });

I would like to append some data to the response sent to the client, but I am unsure how to do it. Everything I try breaks the stream. How does it work with streaming?