Refining this name parse pattern

I had help deriving this pattern (ECMAScript Flavor) and have made small adjustments, but I’m stuck on the third name token in the test string.

Van H. Manning properly parses to Van H. Manning (just use trim() to remove extra space)

Lionel Van Deerlin properly parses to Lionel Van Deerlin

But Van Taylor does not parse to Van Taylor

Can this pattern be adjusted to properly parse Van Taylor along with the other instances of Van?

I’m still working out how this pattern works and how to understand this particular regex wizardry.

TIA

How to scroll to a certain element of a component triggered by the click of a sibling component?

I’m quite new to ReactJS and I need a bit of guidance :

I’ve got a ReactJs/Vite App that fetches and lists countries in alphabetical order.

I added a side nav with the alphabet in form of clickable elements.
When a certain letter is clicked I want my app to scroll to the first country that start with that letter.

Right now my “SideNav” and “ListCountries” components are sibling of their parent “App”

I tried adding data-attr to each country with their first letter but how would I access that from the sibling and how would I scrollTo a certain data-attr?

I need your guidance of how to approach that problem

Array declaration in typescript

I started learning TS and I have a doubt around Array in TS.

Code –

let array: Array<number> = [123];
array = [5,6];
array= [];

In the above code TS compiler is not throwing any error. But I have a doubt, when I am declaring the array to be Array<number> in this scenario when I am setting my array to a blank array it should throw error but its not.

Is there a way in TS where I can define array in a manner that it should always have at least a number in an Array and in case of blank or no values in an Array it should throws a compile time error ?

Editable fields inside aggrid table are moving out of table while scrolling [Angular]

I have a ag-grid table in angular and I am trying to edit the date column which is custom and I used the following config:

...(column.id === "date" && {
    cellEditor: customDateEditor,
    editable: true,
    cellEditorPopup: true
   })

and in my customDateEditor component , the code is :

<p-calendar [(ngModel)]="date" [showIcon]="true" appendTo="body"></p-calendar>

Here, Iam using primeng datepicker to open when i click on date column cell in the table. This is working as expected.

Issue is when i open the datepicker and start scrolling top or bottom , the field is moving out of the ag-grid table.

How can I keep the field fixed at the position it opened even after scroll? or how to close the date-picker on scroll, something like invoking params.api.stopEditing() , (to perform this , i am not able to find any event that gets triggered on table scroll).

I tried using css properties to fix the position , but didnt work. I also tried giving appendTo=”table-id” , but the calendar popup is hiding under the table when opened.

I have tried reading the documentation to find if there is any configuration for this similar to popupParent , but no luck.

The ag-grid version iam using is :

"ag-grid-angular": "29.1.0",
"ag-grid-community": "29.1.0",
"ag-grid-enterprise": "29.1.0",

Any suggestions or help on this would be greatly appreciated. Thanks in advance.

React-router-dom with custom sidebar

I am new to ReacjJS, and i would like to use the react-router-dom with my custom sidenav.

I have created the styling for a sidebar navigation, and now i would like to make the buttons clickable with react router dom, i have this until now:

Sidenav Component:

function sidenav() {
  return (
    <div className='sidenav'>
      <ul className='sidenavList'>
      {SidenavData.map((val, key) => {
        return ( 
        <li
        key={key} 
        className="listItem" 
        id={window.location.pathname == val.link ? "active" : ""} 
        onClick={() => {
          window.location.pathname = val.link
          }}
          >
          <div id="icon">{val.icon}</div>  
          <div id="title">{val.title}</div>
          <div>{val.title}</div>
          </li>
      );
      })}
      </ul>

    </div>
  )
}

App.js

function App() {
  return (
    <main>
            <Routes>
              <Route path="/dashboard" component={Dashboard} exact />
              <Route path="/kalender" component={Kalender} />
              <Route component={Error} /> 
            </Routes>
        </main>
  );
}

updateUrl() always redirects to the starting page URL and not to the specific page

I have a flask app and I try to load my table copying URL on browser.
For example, when I use table pagination URL is builded like this

http://localhost:5000/?length=5&page=5
http://localhost:5000/?length=5&page=6
...

When I try to load the page directly from these URLs a problem occurs: the table is always loaded from its starting address http://localhost:5000/?length=5&page=1 regardless of the page specified in the URL

&page=5 or &page=6 or other pages are completely ignored so the data is not loaded to that specific page

My current code that handles everything is this javascript code

$(document).ready(function() {
    var urlParams = new URLSearchParams(window.location.search);
    var lengthParam = parseInt(urlParams.get('length'));  
    var startParam = parseInt(urlParams.get('start'));
    if (!isNaN(startParam) && startParam >= 0) {
        dataTable.page(parseInt(startParam / lengthParam)).draw();
    }

    var dataTable = $('#userTable').DataTable({
        ajax: {
            url: '/search',
            data: function (d) {
                d.searchTerm = $('#userTable_filter input').val();
                d.length = d.length || lengthParam;  // Aggiungi questa linea
                d.page = d.start / d.length;
                d.start = urlParams.get('start') || d.start;
            }
        },

        processing: true,
        serverSide: true,
        lengthMenu: [5, 10, 25, 100, 500],
        "columns": [
            {data: 'id'},
            {data: 'username'},
            {data: 'badge'},
            {data: 'extra'}
        ],
    });

    // Add an event listener for the DataTables event that occurs when the search term changes
    $('#userTable').on('search.dt', function() {
        updateUrl();
    });

    // Add an event listener for the DataTables event that occurs when the number of displayed entries changes
    $('#userTable').on('length.dt', function() {
        updateUrl();
    });

    // Add an event listener for the DataTables event that occurs when the page changes
    $('#userTable').on('page.dt', function() {
        updateUrl();
    });

    function updateUrl() {
        var searchTerm = $('#userTable_filter input').val();
        var length = $('#userTable_length select').val();
        var page = dataTable.page.info().page;
    
        var url = window.location.href.split('?')[0];
        var params = [];
    
        if (searchTerm) {
            params.push('search=' + encodeURIComponent(searchTerm));
        }
    
        if (length) {  // Modifica questa condizione
            params.push('length=' + encodeURIComponent(length));
        }
    
        params.push('page=' + encodeURIComponent(page + 1));
    
        if (params.length > 0) {
            url += '?' + params.join('&');
        }
    
        history.replaceState({}, '', url);
    }


    // Check if there are parameters in the query string at startup
    var searchParam = urlParams.get('search');
    

    if (searchParam) {
        $('#userTable_filter input').val(decodeURIComponent(searchParam));
        dataTable.search(decodeURIComponent(searchParam)).draw();
    }

    if (lengthParam) {
        $('#userTable_length select').val(decodeURIComponent(lengthParam));
        dataTable.page.len(decodeURIComponent(lengthParam)).draw();
    }

    if (startParam) {
        dataTable.page(parseInt(startParam / lengthParam)).draw();
    }

    // Check if there are parameters in the query string at startup
    var pageParam = parseInt(urlParams.get('page'));
    if (!isNaN(pageParam) && pageParam >= 0) {
        dataTable.page(pageParam).draw();
    }

});

I think the problem is in the updateUrl() function, in my python code I don’t see any particular problems

@app.route('/search', methods=['GET'])
def search_data():
    try:
        search_term = request.args.get('search[value]')
        start = int(request.args.get('start', 0))
        length = int(request.args.get('length', 5))
        order_column = int(request.args.get('order[0][column]'))
        order_dir = request.args.get('order[0][dir]')
 
... [other code]

Is this the correct way of defining routes when using paths loaded from api?

const App = () => {
  const url = `${urlApi}gallery`;
  const [dataChange, setDataChange] = useState(false);
  const { data } = useFetchGet(url, dataChange);

  return (
    <div className ='app'>
      <h1 className='app-header'>XYZ</h1>
      <BrowserRouter>
        <Routes>
          <Route 
            element={<HomePage setDataChange={setDataChange} dataChange={dataChange} />}
            path='/'
          />
          {data && data.galleries.map((oneElement) => {
            const { path } = oneElement
            return(
              <Route 
                key={path} 
                path={`/:${path}`}
                element={
                  <TitleContext.Provider value={path}>
                    <PageLayout title={path} />
                  </TitleContext.Provider>
                }
              />
            )
          })}
          <Route 
            path='*'
            element={<NotFoundPage />}
          />
        </Routes>
      </BrowserRouter>
    </div>
  )
}
export default App

I import the useFetch custom hook into the component through which it downloads data from the API, and I get a path route from the data. is this the correct way of defining routes when using paths loaded from api?

why in this js code “readonly” property is written 2 times after task_input_el.setAttribute. when i write for only 1 time my program is not running

task_input_el = document.createElement("input");
task_input_el.classList.add("text");
task_input_el.type = "text";
task_input_el.value = task;
// check it from here plz//
task_input_el.setAttribute("readonly", "readonly"); // no idea why readonly is written 2 times//
task_content_el.appendChild(task_input_el);

i do not have any idea why “readonly” property is written 2 times after setAttribute.

Apps Script Automatic timestamp when a tab gets updated

So I’m trying to create a script that can apply to several tabs in my spreadsheet file and will automatically update the timestamp in each individual tab when something in that tab is updated/changed. The cell that I want the timestamp in is different in each tab. I thought I had it working but after not touching the file for two days and returning to it, I found that it’s no longer updating. Can anyone take a look and see where the issue is? Also, any idea why it would have been working for two days and then stopped working without any edits to the script? I’m new to java so appreciate any help. Here’s the current script I’m using:

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSheet();
  if(ss.getName()=='Sheet 1') {e.source.getSheetByName("Sheet 1")
    ss.getRange("F3").setValue(new Date())}
  if(ss.getName()=='Sheet 2') {e.source.getSheetByName("Sheet 2")
    ss.getRange("L3").setValue(new Date())}
  if(ss.getName()=='Sheet 3') {e.source.getSheetByName("Sheet 3")
    ss.getRange("K4").setValue(new Date())}
  if(ss.getName()=='Sheet 4') {e.source.getSheetByName("Sheet 4")
    ss.getRange("K4").setValue(new Date())}
}

Is there a different way I should be approaching the script for this?

JSON breaking on short-description property, Can someone please indenity the issue in the short-description property

I get a long JSON from server but it is breaking on short-description property.

//1st Example
"short-description":"Objectives</h4>Psychoactive substance experimentation among Tunisian adolescents remains one of the most threatening public health concerns. In spite of this, little is known about the prevalence and predictors of these behaviors in the Tunisian context. This study aims to assess the prevalence of tobacco, alcohol and illicit drug experimentation and its predictive factors among adolescents in the delegation of Nfidha, Sousse governorate, Tunisia.
Methods</h4>We conducted a cross sectional study in middle and high schools in the delegation of Nfidha, Sousse governorate, Tunisia, during the first trimester of the 2019-2020 school year using an anonymous questionnaire self-administered to a randomly drawn representative sample of 1,352 pupils. Data collected included socio-demographic characteristics, substance experimentation among school-adolescents, academic performance as well as family and peer' factors.
Results</h4>Tobacco was the most commonly experimented substance with a prevalence rate of 17.5u202F% (CI 95u202F%: 14.8-18.8u202F%). The prevalence of alcohol and illicit drugs use were 3.3u202F% [CI 95u202F%: (2.1-3.9u202F%)] and 2u202F% [CI 95u202F%: (1.1-2.6u202F%)] respectively. Being male (Adjusted (AOR)=4.09, p<0.001), being a high school pupil (AOR=2.81, p<0.001), having experiencing academic failure (AOR=1.60, p=0.007) and having a father and siblings who use tobacco (AOR=1.72, p=0.002; AOR=2.03, p=0.001 respectively) were the predictors of tobacco experimentation in the multivariate logistic regression analysis. Additionally, being male (AOR=8.40, p<0.001), having experienced academic failure (AOR=2.76, p=0.017) as well as having a father and siblings who use alcohol (AOR=5.90, p<0.001; AOR=3.03, p=0.045 respectively) and having experienced tobacco (AOR=4.28, p<0.001) were the determinants of alcohol experimentation. Similarly, having a history of academic failure (AOR=3.44, p=0.041), having peers who use illicit drugs (AOR=3.22, p=0.028), having a history of tobacco and alcohol experimentation (AOR=6.52, p<0.001; AOR=3.49, p=0.046 respectively) were the predictors of illicit drug experimentation among adolescents.
Conclusions</h4>A substantial number of socio-demographic and environmental factors have been identified as being involved in experimentation with psychoactive substance during adolescence. Therefore, further prevention programs targeting not only adolescents, but also all risk factors are needed."

//2nd Example
"short-description":"
Background</h4>Bullying is a serious public health concern remarkably common among youth. Involvement in bullying can lead to deleterious effect on the emotional well-being of pupils. The aim of this study was to assess the prevalence of bullying, its psychosocial associated factors and the perceived involvement of parents, teachers, and classmates to counteract this behavior.
Study design</h4>A cross-sectional study.
Methods</h4>We conducted this study in 2015 among a representative multistage sample of 1584 students enrolled in middle schools in the Region of Sousse using the revised Olweus Bully/Victim Questionnaire. It assesses the prevalence of bullying and covers qualitative details of bullying including psychosocial factors and perceived efforts of others to counteract bullying.
Results</h4>11.7% of respondents were classified as pure victims, 7.8% as pure bullies, 3.2% as bully-victims and 75.5% as bystanders. Compared to other groups, the bully-victims were less likely to report a feeling of empathy and liking school. They were more likely to be afraid of being bullied, aggressive and to have fewer friends in the class. Only 30.3% of the victims indicated that they told someone about being bullied. The majority of the middle school students perceived that classmates (54.1%) and teachers (39.5%) did nothing to counteract bullying.
Conclusions</h4>Information about bullying is critical and must be gathered before effective intervention is planned. Parents, teachers and students should learn effective ways to handle the bullying problem since the most effective programs are comprehensive targeting students, schools, families and the community."

//3rd Example
"short-description":"
Background</h4>Tobacco use among teenagers in an increasing concern for the international community, especially with the fact that early experimentation is now identified as a risk factor for durable consumption and addiction.
Aim</h4>To study Tobacco use and its determinants amongteenagers in the city of Sousse.
Methods</h4>A descriptive cross-sectionalstudy was carried out among a sample of teenagers enrolled in the city of Sousse (Tunisia) in 2016-2017. A two-stage sampling was conducted for the selection of adolescents. Data were collected using a self-administered questionnaire in Arabic language.
Results</h4>The sample consisted of 330 students. The prevalence of smoking was 9.7%(95% CI6,7% ;13%), with a male predominance (14.4% vs 6.3%). The mean age of onset of tobacco was 14.65 ± 1.38 years. 44.8% of parents ignore their children's smoking. The mean dependence score was 4.77 ± 3.6 (HONC test).  Factors significantly associated with smoking were gender, age, educational level, repeating school years, relationship with parents and teachers, presence of smokers in the environment, knowledge about the health risks of tobacco.
Conclusion</h4>Sensitizationactions should be strengthened within schools, starting even in primary schools, in collaboration with teachers, family and health professionals. In addition, more effective and rigorous enforcement of legislation is essential."

//4th Example
"short-description":"
Background</h4>Internet represents a revolution in the world of technology and communication all over the world including Tunisia. However, this technology has also introduced problematic use, especially among students. The current study aimed to determine the prevalence of Internet addiction among college students and its predictors in the region of Sousse, Tunisia.
Study design</h4>A cross-sectional study.
Methods</h4>The current study was conducted in the colleges of Sousse, Tunisia in 2012-2013. A self-administrated questionnaire was used to collect data from 556 students in 5 randomly selected colleges from the region. Collected data concerned socio-demographic characteristics, substances use and internet addiction using the Young Internet Addiction Test.
Results</h4>The response rate was 96%. The mean age of participants was 21.8±2.2 yr. Females represented 51.8% of them. Poor control of internet use was found among 280 (54.0%; CI95%: 49.7, 58.3%) participants. Low education levels among parents, the young age, lifetime tobacco use and lifetime illicit drugs use were significantly associated with poor control of internet use among students (P<0.001). While, the most influential factor on internet use among them was under-graduation with an adjusted odds ratio of 2.4 (CI95%: 1.7, 3.6).
Conclusions</h4>Poor control of internet use is highly prevalent among the college students of Sousse especially those under graduate. A national intervention program is required to reduce this problem among youth. A national study among both in-school and out-of-school adolescents and young people would identify at-risk groups and determine the most efficient time to intervene and prevent internet addiction."


//5th Example
"short-description":"
Background</h4>Nowadays, the ageing of the population became a societal frequent problem throughout the world. In Tunisia, the part of the elderly of 60 years old and over is estimated at 17,7 % in 2029. This ageing is at the origin of important health problems, in particular the increase of the frequency of the chronic diseases.
Aim</h4>To identify the Sociodemographic characteristics of the consultants of 65 years old and over, and to describe the morbidity diagnosed in this age group in the primary health care centers of the sanitary region of Sousse.
Methods</h4>We conducted a cross-sectional descriptive study in 86 primary health care centers in Sousse over 1 year (2002-2003). Medical records for 3 weeks per season were randomly selected. The International Classification of Primary Care (ICPC) was used to code recorded data.
Results</h4>2198 consultations were collected, elderly person presents on average 1,22 (± 0,55) morbid states by consultation. The main diseases identified in order were cardiovascular (26,2%), breathing (20,8%), osteo-articular (14,8%). Psychological and social disorders accounted for only 0,4% of cases. The major health problems were uncomplicated hypertension (22,4%), acute bronchitis / bronchiolitis (9,2%), diabetes mellitus type 2 (7,9%) and osteoarthritis of knee (4,7%).
Conclusion</h4>These results are important both to meet the needs of consultants and especially to better adapt the training to practice field."

How can we do late execution of an html code

I want the part of the html code to only execute when the above form is being submitted.

<body>
    <form action="/Recipes" method="post">
        <input type="text" name="recipeName" placeholder="Enter recipe Name" required>
        <button>Find</button>
    </form>
    <!-- The below code should only run once the above form is submitted and should not be executed on the page load -->

    <section class="GPT">
        <h1><%= Name %></h1>

        <% Instructions.forEach(function(instruction) { %>
            <ul><%= instruction %></ul>
        <% }); %>    

        <a href="/"><button>Home</button></a>
    </section>

</body>

Following are the technologies that I’m using:

  • NodeJS
  • EJS
  • JavaScript

I tried using functions in JavaScript that should only be called after the submission of the form.

Write a program to move data among variables [closed]

Someone guide me please.

  1. Define 4 int variables named pos1, pos2, pos3, pos4, input 4 numbers from console and assign them to these variables; display message in the following format: “pos1={a-number}; pos2={a-number}; pos3={a-number}; pos4={a-number}”. “{a-number}” are replaced with real values stored in pos1 through pos4.
  2. Left shift data in these variables: move value from one variable to another variable: move data in pos2 to pos1, pos3 to pos2, pos4 to pos3, and move data in pos1 to pos4. Display values in these variables after shift.
  3. Right shift data in these variables: move value from one variable to its successive variable: move data in pos1 to pos2, pos2 to pos3, pos3 to pos4, and move data in pos4 to pos1. Display values in these variables after shift.

I tried plugging it into Java program but it was showing me a lot of errors.