Passing a variable to python using Ajax method

I want to pass a variable using Ajax from a JS function to a python function in my Django project.
I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs.
However how to I pass my variable through this ajax call? I just want to pass the local variable so it can be printed by the python function.

JS

function calling (){
    var local = 25
    
    $.ajax({
        type:'GET',
        url:'printsome/',
        success: function(response){
            console.log('success');
            console.log(local);
        },
        error: function (response){
            console.log('error');
        }
    });

}

python

def print_some(request):
    from django.http import JsonResponse
    print('this python function was called')
    return JsonResponse({})

Calculate duration startDate & endDate from an HTML form

Im wondering if anyone can point me to some documentation on how to solve my issue.
Still new at native JS, and looking to do some date calculations.

Basically I need to calculate the duration between X and Y dates from and HTML forms input type date.

I have a rough sketch of my HTML and JS..
but still I cannot solve the issue without propper guidance and documentation.

       <div>
          <form>
              <label for="start-date"></label>
              <input type="date" id="start-date">

              <label for="end-date"></label>
              <input type="date" id="end-date">

              <label for="duration"></label>
              <input type="text" id="duration">
         </form>
       </div>

    const startDate = document.getElementById("start-date").value
    const endDate = document.getElementById("end-date").value
    let duration_from_form = document.getElementById("duration").value

    let duration = endDate - startDate;


    if (duration_from_form === ""){
        duration_from_form = duration;
    }
}

I know both of them a rough mockups and not ideal, but I’d love some help finding propper documentation on this matter.
Kind regards

How to optimize router in nodejs koa?

I use koa to create a nodejs application, and I try to optimize.

app.js

'use strict';
const Koa = require("koa");
const Router = require("koa-router");
const router = new Router();

const stuff = require("./router/stuff.js");
router.use("/stuff", stuff.routes());
//more routers like above
const home = require("./router/home.js");
router.use(home.routes());

app.use(router.routes(), router.allowedMethods());
app.listen(port);

There’re some router files in folder router, such as stuff.js, home.js, client.js

stuff.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("stuff", {

        });
    })
module.exports = router;

home.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("home", {

        });
    })
module.exports = router;

client.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("client", {

        });
    })
module.exports = router;

I think the way I wrote is still very amateurish, how to optimize it? Thank you.

Animating grid layout using CSS variables

I’m trying to animate a grid layout using transitions. As far as I can tell, this should be implemented: https://ishoudinireadyyet.com/

I even found a demo of this working: https://codepen.io/matuzo/post/animating-css-grid-layout-properties

But I cannot get it to work myself. What am I doing wrong? https://stackblitz.com/edit/gridlayout-animation?file=index.html

const toggleSidebar = () => {
  const layoutEl = document.querySelector('.layoutEl');
  const currentWidth = getComputedStyle(layoutEl).getPropertyValue('--collapse-panel-width');
  const isOpen = currentWidth == '30rem';
  layoutEl.style.setProperty('--collapse-panel-width', !isOpen ? '30rem' : '2rem');
};
@property --collapse-panel-width {
  syntax: '<length>';
  initial-value: 2rem;
  inherits: true;
}

.layoutEl {
  --collapse-panel-width: 2rem;
  display: grid;
  overflow: hidden;
  grid-template: 
    'header   header' auto 
    'content sidebar' 1fr 
    'footer   footer' auto 
    / 1fr var(--collapse-panel-width);
  gap: 0.3rem;
  height: 100vh;
  transition-property: all;
  transition-duration: 0.5s;
  transition-timing-function: ease-in-out;
}

header {
  grid-area: header;
  background-color: #0055ff;
  color: white;
}

main {
  grid-area: content;
}

aside {
  grid-area: sidebar;
  background-color: #0055ff;
  color: white;
}

footer {
  grid-area: footer;
  background-color: #0055ff;
  color: white;
}
<html>

<head>
  <meta charset="UTF-8" />
</head>

<body class="layoutEl">
  <header>Header</header>
  <main>
    <h1>Main content</h1>
    <button type="button" onclick="toggleSidebar()">Toggle sidebar</button>
  </main>
  <aside>Sidebar</aside>
  <footer>Footer</footer>
</body>

</html>

existe t-il un moyen de filtrer une table dynamiquement avec le nombre d’enregistrement a l’appuie

bonjour!!!
j’aimerais filtrer les elements de ma table et afficher dynamiquement le resultat. Je m’explique j”ai une table voiture avec 100 enregistrement qui contient les champs “couleur” “marque” “annee”. dans ma vue il a trois input et en dessous une div qui montre le nombre total d’enregistrement. S’il choisit couleur rouge par example alors il aura dans la div 48 enregistrement.a chaque fois qu’il selectionne un element.on lui retourne le nombre d’enregistrement correspondant. svp aidez moi

Javascript Determine if page was redirected by tag or window.location.href?

The question is pretty much the same as the title.

Is there a way in Javascript to determine whether the page has been redirected by < a href > HTML tag or by window.location.href?

I need conditions for clearing saved states of data-table:

on reload

and

on redirected via < a href > tag.

I don’t want to clear saved states for a redirection via window.location.href.

I got one on reload:

if (performance.navigation.type == 1){
      var table = $('#categoryList').DataTable();
      table.state.clear();
      table.search("").draw(); 
      table.column( '0:visible' ).order( 'asc' ).draw();
      table.page.len(10).draw();
    }

I’m looking for another one on redirected via < a href >.

Google Apps Script (Javascript) function won’t apply itself to the last worksheet

I am using Google Apps Script (which uses JavaScript) on a Google Sheet doc to carry out a data collection, cleanse and extraction process (to CSV). The whole script runs well apart from one of the functions (see code below).

For some reason it doesn’t seem to apply itself to the very last worksheet in the Google Sheet or the last item stored in the sheets array.

Once it gets to the last item in the sheets array, it will insert the two new columns (client_id and client_name) but not actually set the respective values for these two columns. For example, if client_id = 6 and client_name = "Amazon", these two values will be inserted per row of data in the respective columns for that worksheet.

It will then continue the rest of the code, creating the CSV files and then removing the newly added columns as it should.


Work-around (not ideal) #1: if I insert a blank worksheet and place it at the end, it will actually apply itself to all the useful worksheets before it – which does resolve the issue – however its not an efficient solution.


Work-around #2: I was thinking to rewrite the code as below:

from this (original): for (let i = 0; i < sheets.length; i++) { ... }

to this (new): for (let i = 0; i <= sheets.length; i++) { ... } with a nested if statement which says something along the lines of “if i = sheets.length, do nothing — else, do the usual”

I still need to test this one but yet again feels inefficient.


Current Code:

/* Adds in two columns, one for client id and one for client name to each row.
Columns will be inserted just before the data extraction process and then removed after. */

function insertClientIDsAndNames(client_id, client_name, spreadsheet_id) {
  // all the worksheets this function will apply itself to
  var spreadsheet = SpreadsheetApp.openById(spreadsheet_id);
  var sheets = [];
  
  // collects all the sheets
  for (let i = 0; i < spreadsheet.getSheets().length; i++) {
    sheets.push(spreadsheet.getSheets()[i].getSheetName());
  }

  for (let i = 0; i < sheets.length; i++) {
    var sheet = spreadsheet.getSheetByName(sheets[i]);
    
    // inserts two new columns at the start of the sheet
    sheet.insertColumns(1, 2);

    // insert column header names
    sheet.getRange(1, 1).setValue("client_id");
    sheet.getRange(1, 2).setValue("client_name");

    // returns the position of the last row/column that has content
    var lastRow = sheet.getLastRow();

    var range = sheet.getRange(2, 1, lastRow, 2);
    var values = range.getValues();

    // formats the range to plain text
    range.setNumberFormat('@STRING@');

    // sets the client id
    for (let i = 1; i < values.length; i++) {
      sheet.getRange(i + 1, 1).setValue(client_id);
    }

    // sets the client name
    for (let i = 1; i < values.length; i++) {
      sheet.getRange(i + 1, 2).setValue(client_name);
    }
  }
  
  // creates the csv files
  dataExtractAll(spreadsheet_id);

  // deletes the two new columns that were just created
  for (let i = 0; i < sheets.length; i++) {
    var sheet = spreadsheet.getSheetByName(sheets[i]);
    sheet.deleteColumns(1, 2);
  }
};

Any help would be great as I feel it is a simple solution and I can’t quite see it for some reason!

Cheers.

TYPO3 – Add a JavaScript file and rendering the JS-file to a HTML file

I use TYPO3 ver. 10.4.21 and extensions sitepackage builder.

I added a JavaScript file in sitepackage, but my JavaScript codes don’t be read. Strictly speaking, javascript is read, but my JS codes don’t work on my page (HTML).

Maybe, my JS file doesn’t render my html file? I don’t know…..

In setup.typoscript:

includeJS {
        slider1_script = EXT:mein_projektarbeit/Resources/Public/JavaScript/Dist/slider1.js
        slider1_script.type = text/javascript
}
includeJSFooter {
        slider1_script = EXT:mein_projektarbeit/Resources/Public/JavaScript/Dist/slider1.js
        slider1_script.type = text/javascript
}

And in my html file (Slider1.html):

<html data-namespace-typo3-fluid="true" xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers">
    <f:comment>
        <link href="css/slider1.css" rel="stylesheet">
        <f:layout name="ContentElements/slider1" />
        <script src="{f:uri.resource(path: 'Public/JavaScript/Dist/slider1.js')}"></script>
    </f:comment>
    <f:section name="Main">
    <div class="menu-btn"></div>
       <div class="navigation">
           <div class="navigation-items">
              <a href="#">Home</a>
              <a href="#">About</a>
    .....

in my JS file (Slider1.js):

const menuBtn = document.querySelector(".menu-btn");
const navigation = document.querySelector(".navigation");

menuBtn.addEventListener("click", () => {
    menuBtn.classList.toggle("active");
    navigation.classList.toggle("active");
});

If I run this codes, then an error comes up:
enter image description here

I think the JS file doesN#t render into my html file, that’s why the error comes up.

Did I have to write more codes in html or setup.typoscript?

If I write my JS codes in html and I run them, the Javascript works well. But I want to separate the JS file and HTML file, because I want to use Fluid in my HTML file…
(JavaScript didn’t work, if I used fluid e.g. <data.variable> in my HTML file!)

I hope someone can help me with this problem.

Thank you.

How to update map features properties

I have already mapped my map as below. After mapping, I added some properties to my map features. So How could I update this map. I try this map.getSource('lines').setData(responseData) but I got two overlapping map. Any help is appreciated.

map.on('load', function() {

    map.addSource('lines', {
        type: 'geojson',
        data: responseData
        });

        map.addLayer({
            'id': 'lines',
            'type': 'fill',
            'source': 'lines',
            'layout': {},
            'paint': {
                'fill-color': '#4682B4',
                'fill-opacity': 0.8,
            }
        });
        map.setPaintProperty('lines', 'fill-color', ['get', 'color'])
})

Adding some properties to the already mapped map.

const links = await fetch(`http://127.0.0.1:8000/api/network/4/edges/`);
const linksData = await links.json();
let ar = map.getSource('lines')._data.features.map((item, i) => {
    let currentLayer = linksData.find(
        element => element.edge_id === item.properties.edge_id)
    item.properties.name = currentLayer.name
    item.properties.length = currentLayer.length
    item.properties.speed = currentLayer.speed
    item.properties.lanes = currentLayer.lanes
})

Updating the map after adding properties

map.getSource('lines').setData(responseData)
map.setPaintProperty('lines', 'fill-color', ['interpolate', ['linear'],
            ['get', 'lanes'], 0, 'rgb(255, 255, 255)', 5, 'rgb(255, 0, 0)'])

But instead of updating the map, I got two overlapping maps. How can I fixed it please?

Create and/or Configure Google, FB Apps via API (for user login and subscription)

I’m looking for a solution to automate creation of Google apps (Google developer) to enable user login through user’s Google account.
A public webpage with a Google login would use the app.

It might be possible through Google API but I cannot prove this one.
The same issue would be with Facebook – I found one very old answer (=It is not possible to create an application using Graph API).

Is it possible to programmatically (through an API) modify an existing FB or Google app to add a new website (new domain).

Can you advice about the endpoints and calls, please?

How do i use a proxy with AXIOS?

I am trying to use NORDVPN servers for proxy. I can get it working if i use a socks client but i want to use the normal servers (if possible).

const getIpUrl = "https://api.ipify.org?format=json";

export const requestCurrentIp = () =>
  axios.get(getIpUrl, {
    httpsAgent: tunnel.httpsOverHttps({
      proxy: {
        host: vpn,
        port: 89,
        proxyAuth: `${username}:${password}`,
      },
    }),
  });

When i do this, i get this message:

tunneling socket could not be established, cause=Hostname/IP does not match certificate's 
altnames:
Host: api.ipify.org. is not in the cert's altnames: DNS:*.nordvpn.com, DNS:nordvpn.com

Unable to declare onComplete function in Conf.ts >>Getting error — Type ‘(passed: any) => void’ is not assignable to type ‘() => void’.ts(2322)

I am working on a Protractor – browserstack framework from scratch.

While using onComplete function as mentioned on the site in conf.ts – https://automate.browserstack.com/dashboard/v2/quick-start/get-started#introduction

 // Code to mark the status of test on BrowserStack based on test assertions
      onComplete: function (passed) {
        if (!passed) {
          browser.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "At least 1 assertion has failed"}}');
        }
        if (passed) {
          browser.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "All assertions passed"}}');
        }
      }

I’m getting below error on Console

*Debugger attached.
conf.ts:87:1 – error TS2322: Type ‘(passed: any) => void’ is not assignable to type ‘() => void’.
87 onComplete: function (passed) {

node_modules/protractor/built/config.d.ts:410:5
 410     onComplete?: () => void;
         ~~~~~~~~~~
 The expected type comes from property 'onComplete' which is declared here on type 'Config'*



Can someone help me understand how to resolve this error?

cts query to find unique values from a field from json document in Marklogic staging

4

I’m trying to write a javaScript cts query to query only unique values from a key from a json document based on another key. i.e, similar to a query like select distinct(name) from data-hub-staging where source=’source1′

{
    "source": "source1",
    "name": "John",
    "DOB": "1-01-1990",
    "load_date": "2021-10-23 10:23:55"
}

I have been trying the below query but it returns all the fields, I wanted only the name field.

const query = cts.jsonPropertyValueQuery(
              "source",
              "source1");

[...new Set (cts.search(query)
.toArray()
  .map(doc => doc.root.name).sort())]

How to import an external model in vue.js using babylon js

I am trying to import a gltf file in vue.js using babylon.js and add 3 dimensional view to the webpage. I can’t figure out how to do that and the documentation online is pretty vague as well. Here’s what I tried:
This is what I put in Hello.vue file

<div>
<h1> Hello </h1>
<Scene>
  <Box :position="[0, 0, 5]"></Box>
</Scene>
</div>
</template>

<script src = "./Hello.js">
</script>

This is what I put in Hello.js file

import vb from 'vue-babylonjs';
import Hello from './Hello.vue';

Vue.use(vb);

new Vue({
  components: { Hello },
  render: c => c('Hello'),
}).$mount('#app');


var delayCreateScene = function () {
    // Create a scene.
    var scene = new BABYLON.Scene(engine);

    // Create a default skybox with an environment.
    var hdrTexture = BABYLON.CubeTexture.CreateFromPrefilteredData("../assets/magic_book_of_eden/textures/material_0_baseColor.png", scene);
    var currentSkybox = scene.createDefaultSkybox(hdrTexture, true);

    // Append glTF model to scene.
    BABYLON.SceneLoader.Append("../assets/magic_book_of_eden/", "scene.gltf", scene, function (scene) {
        // Create a default arc rotate camera and light.
        scene.createDefaultCameraOrLight(true, true, true);

        // The default camera looks at the back of the asset.
        // Rotate the camera by 180 degrees to the front of the asset.
        scene.activeCamera.alpha += Math.PI;
    });

    return scene;
};

If possible, could someone explain using an example how that could be done? I am getting the gltf model from sketchfab. Thank you!