How to match a regex pattern from a certain position in javascript?

I’m trying to match the markdown header using regex in javascript. A markdown header is a string starting from one or more # followed by one or more spaces and some more texts, like this:

## This is the title

The tricky thing is, I’m given a multi-line string and a 0-indexed start position, I need to check if the string starting from the given position starts with a markdown header. In other words, I need to write the following function:

/**
 * The function should return true in the following situations:
 * - text: "abcn# My Title", startPos = 4
 * - text: "abcn# My Titlenxyz", startPos = 4
 * 
 * The function should return false in the following situation:
 * - text "abcn#My Title", startPos = 0
 */
function isMarkdownHeader(text, startPos) {
    ...
}

Here is what I’ve tried:

function isMarkdownHeader(text, startPos) {
    const pattern = new RegExp(`^[^]{${startPos}}(^#+)(\s+)(.*$)`, 'm');
    return pattern.exec(text) != null;
}

console.log(isMarkdownHeader("abcn## My Titlenxyz", 4)); // true
console.log(isMarkdownHeader("abcn## My Titlenxyz", 0)); // true, which is incorrect.

The function should return false in the second invocation. But it didn’t. Why? How can I make it work?

How to rotate SVG Oval text along with path

I’m trying to rotate the SVG text path alone with an oval path like the moving text forward not
I tried but the current CSS is rotating the whole text and I’m trying is moving forward each text to next

enter image description here

svg {
overflow: visible !important;
padding:50px;
}
svg text{
-webkit-animation: loading 8s linear infinite;
-moz-animation: loading 8s linear infinite;
transform-origin: center
}
@-webkit-keyframes loading {
100%{
webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
@-moz-keyframes loading {
100%{
moz-transform: rotate(360deg);
transform: rotate(360deg);
}
}
<svg class="Oval_text_svg" width="400"  fill="#C3A97E" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 511 746">
   <defs>
      <pattern id="img1_ad77a587-4b9f-4d4a-9ef6-976c76e4841d" patternUnits="userSpaceOnUse" width="610" height="915">
         <image href="https://via.placeholder.com/728x890.png" x="0" y="0"></image>
      </pattern>
   </defs>
   <path fill="url(#img1_ad77a587-4b9f-4d4a-9ef6-976c76e4841d)" id="Oval_text" d="M 255.5 745.5 C 246.8091888427734 745.5 238.0447235107422 744.8538818359375 229.4499053955078 743.5796508789062 C 220.9792785644531 742.3237915039062 212.4674530029297 740.42724609375 204.1510009765625 737.9429321289062 C 187.7884521484375 733.0548095703125 171.6926422119141 725.7604370117188 156.310546875 716.2623901367188 C 141.2030944824219 706.933837890625 126.6308212280273 695.3866577148438 112.9986343383789 681.9414672851562 C 99.49217987060547 668.620361328125 86.79063415527344 653.3209228515625 75.24672698974609 636.46826171875 C 63.70054626464844 619.6121826171875 53.21763610839844 601.0636596679688 44.08917999267578 581.3378295898438 C 34.87191009521484 561.4202880859375 26.95518112182617 540.1268920898438 20.5587272644043 518.0492553710938 C 14.04345417022705 495.5616455078125 9.039545059204102 472.0283508300781 5.685999870300293 448.1030883789062 C 2.244818210601807 423.552734375 0.5 398.2844543457031 0.5 373 C 0.5 347.7155456542969 2.244818210601807 322.447265625 5.685999870300293 297.8969116210938 C 9.039545059204102 273.9716491699219 14.04345417022705 250.4383697509766 20.5587272644043 227.9507293701172 C 26.95518112182617 205.8730926513672 34.87191009521484 184.5797271728516 44.08917999267578 164.6621856689453 C 53.21763610839844 144.9363708496094 63.70054626464844 126.3878173828125 75.24672698974609 109.5317306518555 C 86.79063415527344 92.67909240722656 99.49217987060547 77.379638671875 112.9986343383789 64.05854797363281 C 126.6308212280273 50.61336517333984 141.2030944824219 39.06618118286133 156.310546875 29.73763656616211 C 171.6926422119141 20.23954582214355 187.7884521484375 12.94518184661865 204.1510009765625 8.057090759277344 C 212.4674530029297 5.572727203369141 220.9792785644531 3.676181793212891 229.4499053955078 2.420363664627075 C 238.0447235107422 1.146090865135193 246.8091888427734 0.5 255.5 0.5 C 264.1908264160156 0.5 272.9552612304688 1.146090865135193 281.5500793457031 2.420363664627075 C 290.0207214355469 3.676181793212891 298.5325317382812 5.572727203369141 306.8489990234375 8.057090759277344 C 323.2115478515625 12.94518184661865 339.307373046875 20.23954582214355 354.689453125 29.73763656616211 C 369.7969055175781 39.06618118286133 384.3691711425781 50.61336517333984 398.0013732910156 64.05854797363281 C 411.5078125 77.379638671875 424.2093505859375 92.67909240722656 435.7532653808594 109.5317306518555 C 447.2994689941406 126.3878173828125 457.7823486328125 144.9363708496094 466.9108276367188 164.6621856689453 C 476.1280822753906 184.5797271728516 484.0448303222656 205.8730926513672 490.4412841796875 227.9507293701172 C 496.95654296875 250.4383697509766 501.96044921875 273.9716491699219 505.3139953613281 297.8969116210938 C 508.7551879882812 322.447265625 510.5 347.7155456542969 510.5 373 C 510.5 398.2844543457031 508.7551879882812 423.552734375 505.3139953613281 448.1030883789062 C 501.96044921875 472.0283508300781 496.95654296875 495.5616455078125 490.4412841796875 518.0492553710938 C 484.0448303222656 540.1268920898438 476.1280822753906 561.4202880859375 466.9108276367188 581.3378295898438 C 457.7823486328125 601.0636596679688 447.2994689941406 619.6121826171875 435.7532653808594 636.46826171875 C 424.2093505859375 653.3209228515625 411.5078125 668.620361328125 398.0013732910156 681.9414672851562 C 384.3691711425781 695.3866577148438 369.7969055175781 706.933837890625 354.689453125 716.2623901367188 C 339.307373046875 725.7604370117188 323.2115478515625 733.0548095703125 306.8489990234375 737.9429321289062 C 298.5325317382812 740.42724609375 290.0207214355469 742.3237915039062 281.5500793457031 743.5796508789062 C 272.9552612304688 744.8538818359375 264.1908264160156 745.5 255.5 745.5 Z" stroke="none"></path>
   <text dy="-10">
      <textPath xlink:href="#Oval_text" class="svg_title">#Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text #Text </textPath>
   </text>
</svg>

js list specific parameters from HTML in new file

smart-people.

I’m new at .js and need a little nudge..

For my first attemt I have a lot of html files in a folder and I want to get a specific part of the files listed in a separate file. How do I do this?

I have ( part of one file, the others are similar):

</script></scripts><parameters><parameter name="Revision" type="Num" description="R500 Rev.1" defaultvalue="R500 Rev.1"/></parameters><shapes><shape><element><html>

I want something like this saved to a new file:

     Folder1;Filename;type=Num
     Folder1;Filename1;defaultvalue=R500 Rev.1
     Folder1;Filename2;type=Num
     Folder1;Filename2;defaultvalue=R500 Rev.1

Should I use grep, query or something like defineproperty?
I’m using notepad++ if this information is important.
Thank you and have a nice day.

Johanna

How to rotate flower animation?

All I want is to create a rotating animation that only responds to the loudness of real-time sound input from the microphone.I want it to rotate slowly when the real-time sound is quiet and fast when the sound is loud.(For ex like a pinwheel) Help me please..

let angle = 0
let mic;
let snd, amp;

function setup() {
  createCanvas(400, 400);
  mic = new p5.AudioIn();//i want the flower leaves to rotate responds to mic
  mic.start();
  
  soundFormats('mic');
  snd = loadSound("mic"); 
  
  snd.setVolume(0.1); 
  // snd.play();
  amp = new p5.Amplitude();
}

function preload() {
 soundFormats('mic');
 snd = loadSound("mic"); 
}
function draw() {
  background(220);
  let w = map(amp.getLevel(), 0,1,0, 400);
  petals();
  noStroke(); //// the center of flower 
  fill(255);
  ellipse(200, 200, 100, 100); 
  
function petals() {   
    push()
    translate(200, 200); 
    rotate(angle); // flower leaves
    noStroke();
    const colors = ['magenta','red', 'orange','#7fff00','#0f0','#0ff','blue','#bf49ff'];

    for (let i=0; i<8; i++) {
     
    let color = colors[i];
    fill(color)
    ellipse(100, 0, 200, 60)
    rotate(radians(45));
    angle = w
    }
    pop()
  }
}

UI flicker when array is changed angular 11

I am contacting an array on value updated by the server, but the UI template flicker on concat.. what should be done to avoid such a situation.

   @Input('companies')   set setCompanyArray(companies) {
     this.showNotFound = false;> 
     if (!companies) {
       return;
     }
     companies.map((company) => {
       company['searchFilter'] = this.lastSearchedText;
    });
    if (!this.companies) {
       this.companies = companies;
       return;
     }
     this.companies = this.companies.concat(companies);

What is a good physics engine for the web? [closed]

I’m making a Minecraft clone, which means that I have a lot of non-moving objects in my scene. (blocks). This whole time, I’ve been using Ammo JS, an Emscripten port of Bullet Physics. However, there are problems I encountered:

  1. It runs out of memory very quickly and crashes, my users are constantly interrupted and forced to reload
  2. Insane amounts of lag. The game starts lagging so hard that it becomes utterly unplayable at some point

I have many static objects but not many dynamic/moving objects. Is there a physics engine that is designed for this? I don’t even need a super complex one. I don’t even need rotational physics, all I need is collision and forces. I even tried making my own but that went quite wrong. What physics engine should I use?

JS client doesn’t read response when server aborts file upload

We have an API (Spring Boot) for file uploads. If file exists it returns 409.

But js client doesn’t read this response and fails with error “net::ERR_CONNECTION_ABORTED”.

From wireshark dump I see that the backend sends the response and then closes the connection:

enter image description here

I think the problem is that js client doesn’t read the response as soon as it available.
However, Postman is able to read the response correctly.

Is it possible to implement Postman’s behavior in javascript?
I’ve tried to read response stream with Fetch API, but no luck.

Sample client code:

function uploadFile() {
try {
    console.log("Start file upload");

    const selectedFiles = document.getElementById('input').files;
    if (selectedFiles.length == 0) {
        alert("No file selected");
        return;
    }

    const file = selectedFiles[0];

    return fetch("http://localhost:9091/api/v1/storage/upload?fileId=/upload-test/test.mp4", {
        method: 'PUT',
        body: file,
        headers: {
            'Content-Type': 'application/octet-stream'
        },
    })
        .then(response => {
            console.log("Processing response");

            const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();

            return pump();

            function pump() {
                return reader.read().then(({ value, done }) => {
                    if (done) {
                        console.log("Finished stream reading");
                        return;
                    }

                    console.log(value);
                    return pump();
                });
            }
        })
        .catch((err) => console.error("error:", err));
} catch (error) {
    console.log(error);
}

}

Where do I paste Utterances tag in Jekyll Minima theme?

I want to add comments on my Jekyll website with Utterances. I use Minima theme, so I don’t have _layout/post.html.

I copied

<script src="https://utteranc.es/client.js"
        repo="sanchoi0310/comments"
        issue-term="pathname"
        theme="github-light"
        crossorigin="anonymous"
        async>
</script>

I thought I had to paste it in _site/intex.html, but the comment window was not there and my <script> tag was automatically deleted.

Where do I paste Utterances <script> tag in Jekyll Minima theme?

move incoming list to table

Returning a list from the backend. I assigned this list to context. Then I want to move the returned list to a ready component.

payment.js

   const { paymentInfoData, setPaymentInfoData } = useContext(PaymentInfoDataContext);

  const req = {
    policyNumber: '1258128722',
    renewalNumber: '00',
    policyTypeExtCode: '718',
    productTypeExtCode: '1000032'
  };

  useEffect(() => {
    if (props.location.state.policy.isActive === true && Object.keys(paymentInfoData).length === 0) {
      PolicyService.getAsosInstallments(req).subscribe(
        (response) => {
          setPaymentInfoData(response);
          // console.log(response);
        }
      );
    }
  }, []);

payment.html

<TabPanel value={value} index={0} >
  <EnhancedTable variant="edit" paymentList={paymentInfoData}/>
  <div className="policypaymentinfo__button_container">
    <AS.Button variant="outlined" onClick={handlePayment}>
      Devam
    </AS.Button>
  </div>
</TabPanel>

table.js

function createData(date, price) {
  return { date, price };
}

const rows = [
  createData('03/04/2021', '250 USD'),
];

How do I move the data inside the row? I can see the props in the console.

ember route and templates not workking

i have included a component in application.hbs

    <Auth></Auth>

next in the auh components i have the following code
auth.hbs

<form>
    <div class="text-field">
         <label>UserName:</label>
        <Input type="text" id="username" required />
        <span></span>
       
    </div>
    <div class="text-field">
        <label>Password:</label>
        <Input type="password" id="password" required />
        <span></span>
        
    </div>
    <div id="result"></div>
    <input {{action "buttonClick"}} type="submit" value="Login">
</form>

auth.js

import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';

export default class AuthComponent extends Component {
  @service router;
   @service('index') auth;

  @action
  buttonClick() {
    let username = document.getElementById('username').value;
    let password = document.getElementById('password').value;
    console.log('user is ' + username);
    var dummy = this;
    dummy.router.replaceWith('demo');
    this.get('router.router').transitionTo('demo');
}

then the router demo
demo.hbs

{{#each @model as |post|}}
  <div>
    {{post.title}}
  </div>
{{/each}}

demo.js

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class DemoRoute extends Route {
  @service router;
  async model() {
    return [
      { title: 'Ember Roadmap' },
      { title: 'Accessibility in Ember' },
      { title: 'EmberConf Recap' },
    ];
  }
}

so when i click the login button i need to view the contents returned from route but a new page is not viewed and only the login page is there but the url changes to http://localhost:8035/foodapp/#/demo but no changes to the page

router.js

import EmberRouter from '@ember/routing/router';
import config from 'foods/config/environment';

export default class Router extends EmberRouter {
  location = config.locationType;
  rootURL = config.rootURL;
}

Router.map(function () {
  // this.route('request', { path: '/req' });
  this.route('demo', { path: '/demo',resetNamespace: true });

  // this.route('index', { path: '/' }); // this is implicit, just putting it in for clarity
  // this.route('fo', function() {
  //   this.route('index', { path: '/' }); // this is implicit, just putting it in for clarity
  //   this.route('post', { path: '/:id' });
  // });

});

Can anyone help me with how can i view the template related with the route..how to get to a new page fropm the login page by transition to route..

Cypress v.10.01 Dynamic Dropbox. Not Selecting item – Has this function been removed?

I hope someone can help. I’ve been struggling with an issue with the dynamic dropbox. I’m doing an end to end shopping cart and it should select the ‘United Kingdom’ after going through the automation code to click on the dynamic drop box for shipping countries.

It types ‘united'(which is correct) but does NOT select the ‘united kingdom from the dynamic drop box’ it just ignore it completely. As you can see in this video here.

So my question is the following:

  1. Has cypress stopped automating dynamic drop boxes?
  2. If Q1 is correct (which I doubt). What are they offering instead?
  3. If I have automated this incorrectly what did I do wrong?

Automation Code for test

describe('JWT Session', () =>{

    it ('User can login via local storage', ()=>{
    
        
    cy.LoginApi().then(function(){
    
        cy.visit("https://rahulshettyacademy.com/client",{
    
                onBeforeLoad: function(window){
    
                    window.localStorage.setItem('token',Cypress.env('token',Cypress.env('token')))
    
                }//onBeforeLoad function to access local storage
    
            })//end of promise for token
    
        })//end of promise for api
    
        cy.get(".card-body button:last-of-type").eq(1).click();
        cy.get("[routerlink*='cart']").click();
        cy.contains("Checkout").click();
        cy.get("[placeholder*='Country']").type("United")
        cy.get(".ta-results button").each(($el,index,$list)=>{
            if($el.text() ==="United Kingdom"){
                cy.wrap($el).click()
            }
        })
       



    
    })//end of IT test case


    
        })//end of describe 

How to convert unicode values to normal text in Javascript?

I am getting a data from an API to my JS project. Data is about questions and answers. Texts in data are broken. Sometimes there are special characters in questions or answers.

For Expample :

Question : Which song in rapper Kanye West&#039;s album &quot;The Life of Pablo&quot; features Rihanna?

Following special characters are characters I’ve been able to catch so far. So maybe there is more in API data.

&deg;
&quot;
&deg;
&#039;
&ouml;
&rsquo;
&eacute;

The solutions that I’ve found on the internet was only focusing specific special character and solving it with .replace() function.

I want to ask you “Can you write the following function in JavaScript?”

function fixText(text){
 text = text.......??????
 return text
}

How to delete an item from my Reducer Object?

I have an object in my reducer like this :

clientData : {
1080 : [{ID : 1111,name : 'John'},{ID : 2222,name : 'Stan'},],
1090 : [{ID : 3333,name : 'Adam'},{ID : 4444,name : 'Alan'},]
}

And I want to be able to delete an item (for example Stan with 2222 ID’s)
The problem that is I don’t have the key of my property (1080), and I don’t have any idea how to achieve it.
I’ve tried the Object.values(object1) but it convert my object to array and I lost all my architecture.
Have you an idea please ?

Blazor server side application throwing “System.InvalidOperationException: JavaScript interop calls cannot be issued at this time. …” during reload

I have a file drop zone implemented in one of the pages of my blazor application, which is handled using the javascript runtime interface. In order to avoid memory leaks, I have a javascript method, which removes all the event listeners. This is called from the dispose function as follows:

public ValueTask DisposeAsync()
{
    ViewModel.PropertyChanged -= OnPropertyChangedHandler;
    GC.SuppressFinalize(this);
    return JSRuntime.InvokeVoidAsync("deInitializeDropZone");
}

This works, however if I reload the page in my browser (F5, or reload button), I get the following exceptions:

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HMI59N5RRGP7", Request id "0HMI59N5RRGP7:0000000E": An unhandled exception was thrown by the application.
      System.InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
         at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
         at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.<>c__DisplayClass69_0.<<Dispose>g__HandleAsyncExceptions|1>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.<>c__DisplayClass69_0.<Dispose>g__NotifyExceptions|2(List`1 exceptions)
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.<>c__DisplayClass69_0.<<Dispose>g__HandleAsyncExceptions|1>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.DisposeAsync()
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.<DisposeAsync>g__Await|22_0(Int32 i, ValueTask vt, List`1 toDispose)
         at Microsoft.AspNetCore.Http.Features.RequestServicesFeature.<DisposeAsync>g__Awaited|9_0(RequestServicesFeature servicesFeature, ValueTask vt)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.<FireOnCompleted>g__ProcessEvents|227_0(HttpProtocol protocol, Stack`1 events)
warn: Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer[100]
      Unhandled exception rendering component: JavaScript interop calls cannot be issued at this time. This is because the circuit has disconnected and is being disposed.
      Microsoft.JSInterop.JSDisconnectedException: JavaScript interop calls cannot be issued at this time. This is because the circuit has disconnected and is being disposed.
         at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
         at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.<>c__DisplayClass69_0.<<Dispose>g__HandleAsyncExceptions|1>d.MoveNext()
fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
      Unhandled exception in circuit 'blLlOrw1UtfEHUoPBbO_N3peh7u3Or5Uk51p5RbR5xA'.
      Microsoft.JSInterop.JSDisconnectedException: JavaScript interop calls cannot be issued at this time. This is because the circuit has disconnected and is being disposed.
         at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
         at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.<>c__DisplayClass69_0.<<Dispose>g__HandleAsyncExceptions|1>d.MoveNext()

This will only happen on reload, if I switch to another page, the dispose function is called as well, but no exception.
I’m not entirely sure what the reason for this problem is. Maybe it could relate to the initialization as well, which happens after first render:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var authState = await AuthenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            if (await ViewModel.LoadSelectedDatabase(DatasetID))
            {
                await JSRuntime.InvokeVoidAsync("initializeDropZone");
            }
            else
            {
                await JSRuntime.InvokeVoidAsync("alert", "The selected Dataset does not exist!");
                NavigationManager.NavigateTo($"datasets");
            }
        }
    }

    await base.OnAfterRenderAsync(firstRender);

    return;
}