How to use Navigation Events (navigationHide) on SwiperJS?

I would like to use navigationHide and navigationShow Event on SwiperJS.

I set the events but nothing happens when the navigation is disabled or hidden.

const swiper = new Swiper(".swiper", {
  initialSlide: 0,
  loop: false,
  spaceBetween: 24,
  slidesPerGroup: 2,
  slidesPerView: 'auto',
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev"
  },
  on: {
    navigationHide: function () {
      console.log(this);
    }, 
    navigationShow: function () {
      console.log(this);
    }
  }
});

https://codepen.io/nuno360/pen/MWOPgVB

Restrict table data value to 4 digits

I am trying to build a simple calculator using HTML, CSS and Vanilla Javascript. Where I want to make sure that the input field (display screen) does not have more than 4 digits in the first operand and similarly for the next operands to follow.

Story so far
index.html

<table class="calculator">
    <tr>
        <td colspan="4"><input class="display-box" type="text" id="result" disabled /></td>
    </tr>
    <tr>
        <td><input class="button" type="button" value="1" onclick="display('1')" /> </td>
        <td><input class="button" type="button" value="2" onclick="display('2')" /> </td>
        <td><input class="button" type="button" value="3" onclick="display('3')" /> </td>
        <td><input class="button" type="button" value="*" onclick="display('*')" /></td>
    </tr>
    ...
</table>

script.js

function display(value) {
    document.getElementById("result").value += value;
    var ops = ["+", "-", "%", "*", "/"];
    result=document.getElementById("result").value
    console.log(result)
    if(ops.includes(value)){
        result=0
        console.log("Ops found!")
    }
    result=document.getElementById("result").value
    result=result.replace(/[^0-9]/g, '');
    console.log(result)
    if(result>9999){
        document.getElementById("result").value = "Error"
        alert("Error: Entered more than 4 digits")
    }
}

Raycast not hitting a scene child using Three.js with GMaps

Im trying to hit a pin scene child with a click in GMaps, using Three.js and threejs-overlay-view but I can’t get the object clicked. Raycaster.intersectObjects only returns [].

Image of pin

Here’s a snippet of the code, everything works fine except the intersection part.

(async () => {        
  const map = await initMap();
  const mapDiv = map.getDiv();

  const mousePosition = new Vector2();
  const raycaster = new THREE.Raycaster();
  const overlay = new ThreeJSOverlayView(mapOptions.center);

  const scene = overlay.getScene();
  overlay.setMap(map);
  ...

  map.addListener('click', ev => {
    const {domEvent} = ev;
    const {left, top, width, height} = mapDiv.getBoundingClientRect();
    const x = domEvent.clientX - left;
    const y = domEvent.clientY - top;
    mousePosition.x = 2 * (x / width) - 1;
    mousePosition.y = 1 - 2 * (y / height);

    // dont get nothing here...
    raycaster.setFromCamera(mousePosition, overlay.camera);
    const intersects = raycaster.intersectObjects(scene.children, true);
    overlay.requestRedraw();
  });

  overlay.update = () => {
    // ... and here
    raycaster.setFromCamera(mousePosition, overlay.camera);
    const intersects = raycaster.intersectObjects(scene.children, true);
    ...
    overlay.requestRedraw();
  };
})();

Glad if any help, Thanks!

JS – Set value to class property which is accessed via getter method

I have implemented this custom error:

class PostError extends Error {
  constructor(code, message) {
    super(message);

    Object.assign(this, {
      code,
      name: "PostError",
    });
  }

  get code() {
    return this.code;
  }

  get message() {
    return this.message;
  }
}

new PostError("some-code", "some-message");

When I create a PostError, I do: new PostError("some-code", "some-message");

Then… I get this exception:

TypeError: Attempted to assign to readonly property.

Any ideas how to fix this?

creating cutom nested object by adding key in javascript / node js

let data = [
  {
    system: { id: "4gSSbjCFEorYXqrgDIP2FA", type: "Entry", name: "Author" },
    DataDetails: {
      shortSlugOption: { "en-us": "some value", "za-op": "random value" },
      mediaFileAssetLink: { "en-us": "some file", "za-op": "file Linl" },
      mediaFileAssetGalary: { hi: "file link 2" },
      singleMediaImage: { hi: "file link single", "en-us": "english link" },
    },
  },
  {
    system: { id: "1aBOO8tu3lUsjtICuIbUM5", type: "Entry", name: "Author" },
    DataDetails: {
      short: { "en-us": "details of shorts", "za-op": "short details" },
      shortSlugOption: { "hi-In": "options" },
      booleanField: { "hi-In": "true" },
    },
  },
  {
    system: { id: "2pOUGnI1oRD7nsrYs600HA", type: "Entry", name: "testing" },
    DataDetails: { testingNewValue: { "en-us": "details value" } },
  },
  {
    system: { id: "66rzYr2BpWL1VTBHdLTdSW", type: "Entry", name: "new" },
    DataDetails: {
      oneReference: { hi: "values 1" },
      multiReference: { "hi-In": "values 2" },
    },
  },
  {
    system: { id: "cIb5mqEBRWDD6hrNmFmFE", type: "Entry", name: "new" },
    DataDetails: { testingNewValue: { "hi-IN": "jksdsdo" } },
  },
  {
    system: { id: "7kRzyt4PFrX13gHcw3Z1Ko", type: "Entry", name: "testing" },
    DataDetails: { testingNewValue: { "en-us": "kknksdo" } },
  },
  {
    system: { id: "2OspeCtNK0sh2cPiuU9jIz", type: "Entry", name: "dummy" },
    DataDetails: {
      short: { "za-op": "dfvndkssa" },
      shortSlugOption: { hi: "sdocjosmdc" },
      mediaFileAssetLink: { "en-us": "jdsojocis" },
      booleanField: { "hi-In": "true" },
    },
  },
  {
    system: { id: "2eAmIIuG4xkLvatkU3RUSy", type: "Entry", name: "dummy" },
    DataDetails: {
      dummy: { "en-us": "dshcifdvk" },
      india: { "za-op": "sdci", hi: "hewd" },
    },
  },
  {
    system: { id: "7hbdS3MgfZ73TOtlu1WfXw", type: "Entry", name: "dummy" },
    DataDetails: {
      testingNewValue: { "en-us": "sdcoklsdc" },
      locationField: { hi: "sdcndkdc" },
    },
  },
];

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach((detail) => {
    detailsObj[detail] = Object.values(curr.DataDetails[detail])[0];
  });

  acc[curr.system.name][curr.system.id] = {
    ...detailsObj,
  };
  return acc;
}, {});

console.log(res);

I am storing my data in JSON file but by doing some modification in my current object.

data I want to store in JSON is like in this way

Like Data present

  1. Author
  2. en-us/zo-ap / other key which are available in obj
  3. 4gSSbjCFEorYXqrgDIP2FA/ 1aBOO8tu3lUsjtICuIbUM5
  4. then the remaining json object
{
    "Author": {
        "en-us": {
            "4gSSbjCFEorYXqrgDIP2FA": {
                "shortSlugOption": "some value",
                    "mediaFileAssetLink": "some file",
                  "singleMediaImage": "english link"
            },
            "1aBOO8tu3lUsjtICuIbUM5": {
                "short":"details of shorts"
            }
        },
        "za-op": {
            "4gSSbjCFEorYXqrgDIP2FA": {
                "shortSlugOption": "random value",
               "mediaFileAssetLink":"file Linl", 
            },
            "1aBOO8tu3lUsjtICuIbUM5": {
                "short":"short details",
            }
        },
        "hi": {
            "4gSSbjCFEorYXqrgDIP2FA": {
                "mediaFileAssetGalary": "file link 2",
                  "singleMediaImage":"file link single"
            }
        },
        "hi-In": {
            "1aBOO8tu3lUsjtICuIbUM5": {
                "shortSlugOption": "options",
                    "booleanField":true
            }
        }
    },
    "dummy": {
        "en-us": {
            "2OspeCtNK0sh2cPiuU9jIz": {                
                "mediaFileAssetLink":"jdsojocis",
            },
            "2eAmIIuG4xkLvatkU3RUSy": {
             "dummy": "dshcifdvk"
            }
            "7hbdS3MgfZ73TOtlu1WfXw": {
                "testingNewValue":"sdcoklsdc"
            }
        },
        "za-op": {
            "2OspeCtNK0sh2cPiuU9jIz": {                
                "short":"dfvndkssa",  
            },
            "2eAmIIuG4xkLvatkU3RUSy": {
                "india":"sdci"
            }
        },
        "hi": {
            "2OspeCtNK0sh2cPiuU9jIz": {
                "shortSlugOption":"sdocjosmdc"
            },
            "2eAmIIuG4xkLvatkU3RUSy": {
                "india":"hewd"
            }
        }
        "hi-In": {
            "2OspeCtNK0sh2cPiuU9jIz": {                
                "booleanField":"true"
            },
            "7hbdS3MgfZ73TOtlu1WfXw": {
                "locationField":"sdcndkdc"
            }
        }
    },
    "new": {
        "hi": {
            "66rzYr2BpWL1VTBHdLTdSW": {
                "oneReference":"values 1"
            }
        },
        "hi-In": {
            "66rzYr2BpWL1VTBHdLTdSW": {
                "multiReference":  "values 2" ,
            },
            "hi-IN": {
                "cIb5mqEBRWDD6hrNmFmFE": {
                    "testingNewValue":"jksdsdo"
                }
        }
        }
    }.
    "testing": {
        "en-us": {
            "2pOUGnI1oRD7nsrYs600HA": {
                "testingNewValue":"details value"
            },
            "7kRzyt4PFrX13gHcw3Z1Ko": {
                "testingNewValue":"kknksdo" 
            }
        },
    }
}

As in above code the en-us hi hi-In hi-IN zo-ap or any other key are getting removed

but I want to create a nested json object by this name or any other name which are present inside json

How to get “to_do” from a notion block using typescript?

Recently I tried final version of Notion API. Using typescript I made a retrieve block children request:

(async () => {
    const blockId = process.env.BLOCK_ID;
    const response = await notion.blocks.children.list({
        block_id: blockId,
        page_size: 50,
    });
    console.log(response.results[1].to_do);
})();

Error message

For some reason typescript tells me that to_do doesn’t exist in type (PartialBlockObjectResponse | BlockObjectResponse). I looked at type definition and… it was there:

declare type BlockObjectResponse = {
    // ...
    {
    type: "to_do";
    to_do: {
        rich_text: Array<RichTextItemResponse>;
        color: ApiColor;
        checked: boolean;
    };
    object: "block";
    id: string;
    created_time: string;
    created_by: {
        id: IdRequest;
        object: "user";
    };
    last_edited_time: string;
    last_edited_by: {
        id: IdRequest;
        object: "user";
    };
    has_children: boolean;
    archived: boolean;
} 
// ...
}

I tried making type guard

function isToDo(value: PartialBlockObjectResponse | BlockObjectResponse): value is BlockObjectResponse {
     return "to_do" in value;
}  /* Error: TS2304: Cannot find name 'PartialBlockObjectResponse'. */

and importing type from package

import type {PartialBlockObjectResponse} from "@notionhq/client/build/src/api-endpoints"; 
// Error: Module '"@notionhq/client/build/src/api-endpoints"' declares 'PartialBlockObjectResponse' locally, but it is not exported.

Neither helped.

Error [ERR_REQUIRE_ESM] Github deploy error

I’ve recently added in some packages to my React project, since doing this I now see an error each time I run yarn run dev

internal/modules/cjs/loader.js:1102
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ~/GitHub/react-project/node_modules/gatsby-recipes/node_modules/remark-mdx/index.js
require() of ES modules is not supported.
require() of ~/Documents/GitHub/react-project/node_modules/gatsby-recipes/node_modules/remark-mdx/index.js from
~/Documents/GitHub/react-project/node_modules/gatsby-recipes/dist/graphql-server/server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type":
"module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from
~/Documents/GitHub/react-project/node_modules/gatsby-recipes/node_modules/remark-mdx/package.json.

    at new NodeError (internal/errors.js:322:7)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
    at Object.<anonymous> (~/Documents/GitHub/react-project/node_modules/gatsby-recipes/dist/graphql-server/server.js:52:17)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32) {
  code: 'ERR_REQUIRE_ESM'
}

I’ve shortened the file paths for anonymity but you get the idea. I’m still able to make changes to my project locally and build the project, but when I push it to github it fails the actions and says 2 packages haven’t been installed correctly.

For instance this appears in the actions log:

out:  ERROR #98124  WEBPACK
out: 
out: Generating JavaScript bundles failed
out: 
out: Can't resolve 'react-animate-height' in '/home/dev_onlyorca/source/src/pages'
out: 
out: If you're trying to use a package make sure that 'react-animate-height' is
out: installed. If you're trying to use a local file make sure that the path is
out: correct.
out: 
out: File: src/pages/about.js

I saw some help that mentioned updating either the filename of the problematic module to .cjs or adding into the package.json file “type”: “module” but neither seemed to make any difference. I know this isn’t something that should normally happen but I have used both Yarn and npm installs in this project as some of the dependancies were only available through npm and it’s generated 2 lock files. Any help on this would be massively appreciated!

Changing transform position on mouse event?

I am making an image carousel feature, I have completed the sliding with forwarding and backward buttons with transform property. But now I am facing problems doing it perfectly with mouse events like when the mouse is clicked and dragged to left then making a smooth and user-friendly image carousels. How can I do it?

Here is the example code: – https://jsfiddle.net/dy1vk40f/1/

Any guide provided would be greatly appreciated

function moveable(e) {
  if(!isDown) return;
  e.preventDefault();
  
  const x = e.pageX - scrollcontainer.offsetLeft;
  const style = window.getComputedStyle(scrollcontainer);
  const matrix = new WebKitCSSMatrix(style.transform);

  const walk = x - startX;
  const walktwo = walk * 10;
  scrollcontainer.style.userSelect = 'none';
  scrollcontainer.style.transform = `translate3d(${matrix.m41 + walk}px, 0px, 0px)`;
  startX = e.pageX;
  texx.innerHTML = `Tranlate: ${matrix.m41}`;

How to target MAP to a styled component using React and Openlayers

I am trying to use Open layers + React js but trying to target map to a syled component it shows nothing like it doesn’t detect it. Iam following documentation but cant find something similar to this

Map Component:

import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import MapaBase from "../StyledComponents/Map";


export const Mapa = () => {

  new Map({
    target: "MapaBase",
    layers: [
      new TileLayer({
        source: new XYZ({
          url: "https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        }),
      }),
    ],
    view: new View ({
        center:[0,0],
        zoom: 2
    })
  });
  return (
    <>
      <MapaBase colores="red"/>
    </>
  );
};

Styled component:

import styled from "styled-components";

const MapaBase = styled.div`
width: 100%;
height: 500px;
background-color:${props => props.colores};
`;


export default MapaBase;

sortablejs changing list first and adding new element make element positions incorrect

I am creating simple sortablejs list that can add new element after the current element and change the position. when I drag and change element to last element and add new element will add new element to the top of the element. but I want to add that below the current element.

import { Component } from '@angular/core';
import { Options } from 'sortablejs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'my-app';
  items = [1, 2, 3, 4, 5];
  items2 = this.items.slice();

  draggableOptions: Options = {
    onUpdate: (event) => {
      let newArr2 = this.items.slice();
      let newEle = this.items.splice(event.oldIndex, 1)[0];

      this.items.splice(event.newIndex, 0, newEle);
    },
    onStart: (event) => {
      // ExcelStore.dispatch({type: ExcelAction.SECTION_DRAG_START, payload: {dragIndex : event.oldIndex}});
    },
    sort: true,
  };

  addNew(item) {
    let currentIndex = this.items.indexOf(item);
    console.log(item);
    this.items.splice(currentIndex + 1, 0, item + 15);
    //this.items.push(item+15)
  }

  checkIndex(item) {
    console.log(this.items);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<h2>Drag / drop the item</h2>
<div [sortablejs] [sortablejsOptions]="draggableOptions">
  <div *ngFor="let item of items"  style="border: 1px solid" >
    <h4>{{ item }}</h4>
    <button (click)="addNew(item)">Add new</button>
    <button (click)="checkIndex(item)">check index</button>
  </div>
</div>

get list of files in encrypted zip file with javascript in browser

If I want to unzip a zip package with a password and get a list of files in the zip package, what should I do, here is the code I try to solve the above problem.

  async function getPasswdZipFiles(file, password) {
   const reader = new zip.ZipReader(new zip.BlobReader(file) ,{password})
   console.log('[ reader ] >', reader)
   const entries= await reader.getEntries()
   await reader.close()
  }

The value of entries is the archive, not the file list. How should I get the file?
I would be very grateful if I could get an answer.

Discord.js: if…else if…else return

in my /mute remove command:

if(target.communicationDisabledUntilTimestamp > interaction.createdTimestamp) {
        target.timeout(null)
      } else if (target.roles.cache.has(muted_role)) {
        target.roles.remove(muted_role)
      } else return interaction.followUp({ content: `The member is not muted.` })

But if I run the command on the member that is timed out, it:

  • Removes the timeout
  • Replies The member is not muted. and returns the following code;

while it should just remove the timeout.

How do I fix that?

call interface in Angular

I have an interface from the BE like this:

export interface DailyGoal extends Base {
  date: Date;
  percentage: number;
}

Now I’m trying to refer to that in my component.ts file

import { DailyGoal } from '../../interfaces';
  dailyGoal: DailyGoal[] = [];

But I don’t understand how to push the variable that I have into the date and percentage.
I created this function that will give me the list of days that the user may choose
(I still need to figure it out how to do the percentage)

   getDays(startDate: Date, endDate: Date) {
        const dates = [];
        const percentage = [];
        const currentDate = startDate;
        while (currentDate < endDate) {
          dates.push(new Date(currentDate));
          currentDate.setDate(currentDate.getDate() + 1);
        }

// for (let date of dates) {

    // if (date.getDay() <= 5) {
    //   percentage.push(100);
    // 
    // } else date.getDay() > 5;
    // percentage.push(0);


 if (startDate && endDate)  dates.push(endDate);
    return dates;
  }

how can I push my “date” variable into the interface?
hope you can help me, thank you so much

Why is index always 23 when handleClick() is called. REACT

I am learning React by following concepts from the tic-tac-toe tutorial. I am trying to create an online course providing platform. I have a bunch of filter buttons, each indicating a topic for course, for example, “Applied Mathematics”. Since, there are a lot of filter buttons to display, I created an array of filter buttons, by populating them from a filter list array – which contains relevant data for each filter. This is the function that does this:

renderFilters() {
        this.filterButtonList = [];
        for (var index in this.filterList) {
            index = parseInt(index);
            var item = (
                <FilterButton
                    key={this.filterList[index].param}
                    text={this.filterList[index].text}
                    param={this.filterList[index].param}
                    isActive={this.state.isActive[index]}
                    onClick={() => {
                        this.handleClick.bind(index);
                        this.handleClick(index);
                    }}
                />
            );
            this.filterButtonList.push(item);
        }
        return this.filterButtonList;
    }

The filter list looks something like this:

this.filterList = [
            { text: "All Topics", param: "all-topics" },
            { text: "Algorithms and Data Structures", param: "#cat=engineering&subcat=computerscience&spec=algorithmsanddatastructures" },
            { text: "Artificial Intelligence", param: "#cat=engineering&subcat=computerscience&spec=artificialintelligence" },
            { text: "Computer Design and Engineering", param: "#cat=engineering&subcat=computerscience&spec=computerdesignandengineering" },
            { text: "Computer Networks", param: "#cat=engineering&subcat=computerscience&spec=computernetworks" },
            { text: "Cryptography", param: "#cat=engineering&subcat=computerscience&spec=cryptography" },
            { text: "Data Mining", param: "#cat=engineering&subcat=computerscience&spec=datamining" },
            { text: "Graphics and Visualization", param: "#cat=engineering&subcat=computerscience&spec=graphicsandvisualization" },
            { text: "Human-Computer Interfaces", param: "#cat=engineering&subcat=computerscience&spec=humancomputerinterfaces" },
            { text: "Operating Systems", param: "#cat=engineering&subcat=computerscience&spec=operatingsystems" },
            { text: "Programming Languages", param: "#cat=engineering&subcat=computerscience&spec=programminglanguages" },
            { text: "Software Design and Engineering", param: "#cat=engineering&subcat=computerscience&spec=softwaredesignandengineering" },
            { text: "Theory of Computation", param: "#cat=engineering&subcat=computerscience&spec=theoryofcomputation" },
            { text: "Algebra and Number Theory", param: "#cat=mathematics&subcat=algebraandnumbertheory" },
            { text: "Applied Mathematics", param: "#cat=mathematics&subcat=appliedmathematics" },
            { text: "Calculus", param: "#cat=mathematics&subcat=calculus" },
            { text: "Computation", param: "#cat=mathematics&subcat=computation" },
            { text: "Differential Equations", param: "#cat=mathematics&subcat=differentialequations" },
            { text: "Discrete Mathematics", param: "#cat=mathematics&subcat=discretemathematics" },
            { text: "Linear Algebra", param: "#cat=mathematics&subcat=linearalgebra" },
            { text: "Mathematical Analysis", param: "#cat=mathematics&subcat=mathematicalanalysis" },
            { text: "Mathematical Logic", param: "#cat=mathematics&subcat=mathematicallogic" },
            { text: "Probability and Statistics", param: "#cat=mathematics&subcat=probabilityandstatistics" },
            { text: "Topology and Geometry", param: "#cat=mathematics&subcat=topologyandgeometry" },
        ];

And, the implementation for the <FilterButton> is this:

class FilterButton extends React.Component {
    render() {
        return (
            <button
                className={this.props.isActive === "true" ? "filters-button active" : "filters-button"}
                onClick={() => {
                    this.props.onClick();
                }}
            >
                {this.props.text}
            </button>
        );
    }
}

The implementation for handleClick(i) is this:

handleClick(i) {
    #Nothing fancy, just trying to display the value of the passed index.
    console.log(i);
}

However, clicking on any of the buttons only prints “23”, rather than printing the index of the button clicked – for example, if I click on “All Topics” button – which has a index of “0” in this filter list, it should print “0”, not “23”. The same is true, if instead of index I passed something like this.filterList[index].text to display the button text – in which case, if I click on something like “Applied Mathematics” button or “Linear Algebra” button, it only prints “Topology and Geometry” (which is the value from last row of filter list). What am I doing wrong?

Get parent object at field type policy

Let’s say that I have the following query that fetches a list of products.

query ProductList() {
  products() {
    name
    price
    stockQuantity
    isAvailable @client # This is a local-only field
  }
}

Also I have added a type policy for a local-only field at the in-memory cache creation, with a read function:

const cache = new InMemoryCache({
  typePolicies: { // Type policy map
    Product: {
      fields: { // Field policy map for the Product type
        isAvailable: { // Field policy for the isAvailable field
          read(existing, context) { // The read function for the isAvailable field
            // Return value
          }
        }
      }
    }
  }
});

How can I get the stockQuantity field of the parent Product object at the isAvailable read function?