Link target unrecognized in iframe; opens in new tab

I’m working on a simple web interface that requires another web interface (that I don’t control) to be embedded, which unless someone has a better solution I’ve been serving via Apache reverse proxy to a sandboxed iframe.

The problem is, that web interface consists of a few frames of its own, and when I click a link in the navbar (<a href="main.htm" id="main.htm" target="main">LINKNAME</a>) targeting the main content frame, it opens in a new tab. If I open the reverse proxy in its own tab everything runs fine, I’ve just been unable to figure out why it’s not working properly in the iframe. At this point my assumption is that the “main” target isn’t being recognized but I don’t know why (the “_self” targets in the top and main frames do work properly).

<frameset framespacing="0" border="0" frameborder="0" rows="54,*"> 
    <frame name="top" noresize="" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" border="no" src="top.htm" target="_self"> 
    <frameset cols="166,*"> 
        <frame name="contents" target="main" src="navbar.htm" scrolling="auto" noresize="" marginwidth="5" marginheight="0"> 
        <frame name="main" src="main.htm" scrolling="auto" noresize="" target="_self" marginwidth="0" marginheight="0"> 
    </frameset> 
</frameset>

I’ve noticed that I get "Unsafe attempt to initiate navigation for frame with URL 'http://.../main.htm' from frame with URL 'http://.../navbar.htm'. The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors." in the console when clicking the links but not sure if it directly relates to the problem. I don’t understand why it considers main.htm to be an ancestor, as they’re both at the same level of the site’s hierarchy. Either way, I’m unable to allow it out of the sandbox, as it will set itself as the top level document by way of if(top!=self){top.location.href=location.href}.

Any thoughts?

why are we retuning a anonymous function in the below from JS [duplicate]

// Debouncing in Javascript
let counter = 0;
const getData = () => {
  // calls an API and gets Data
  console.log("Fetching Data ..", counter++);
}

const debounce = function(fn, d) {
  let timer;
  return function() {
    let context = this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      getData.apply(context, arguments);
    }, d);
  }
}

const betterFunction = debounce(getData, 300);
<input type="text" onkeyup="betterFunction()" />

how to use showMore showLess for top 20 users in angular

I have 20 top users with ranking by point, I got them from an api rest, so i’m trying to create a button (showMore – showLess).

At first it shows 10 users automatically and when i click showMore it will add the other 10 users that’s mean 20 users. but when i click showLess it will reduce the 10 users to show just the 10 users.

html code :

        <div class="col-md-6  text-center">
            <h2><strong>TOP 20 FANS</strong></h2>

            <div *ngFor="let top of top2" class="rank" style="width: 74%;">
                <div class="data-row">
                    <div class="row-user">
                        <div class="col-lg-4 col-md-7 col-sm-7 col-7">
                            <div class="rank-row">
                                <span class="logo-wrapper ">
                                    <img src={{top.photoUrl}}>
                                </span>
                                <div class="td-wrap"><a class="uni-link">{{top.firstname}} {{top.familyname}}</a>
                                </div>
                                <div class="location "> <img width="10px" src="../assets/localisation.png">
                                    france</div>
                            </div>
                        </div>
                        <div
                            class="col-lg-4 offset-lg-0 col-md-12 offset-md-0 col-sm-11 offset-sm-1 text-center">
                            <span><img width="25px" src="../assets/golden.png"> {{top.point}} PT</span>
                        </div>
                    </div>
                </div>
            </div>

ts code :

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  top2: any;



  constructor(private apiService: ApiService) { }


  ngOnInit() {
    this.getTop2();
  }

  getTop2() {
    this.apiService.gettop2().subscribe(res => {
      this.top2 = res;
      console.log(res)
    });

  }



}

so i’m trying to create array inside an array, and in every array i have 10 users for example :

array : [{ },{ },{ },{ },{ },{ },{ }….] —> [ [ { },{ },{ },{ }] , [ { },{ },{ },{ } ] ]

let data =[ ]

data = t[0]

showMore i++ –> data.push() t[1]

showLess i–

Using mySQL in order to create a daily command?

still getting into the shift of things with this. So i’m currently using a system to create a discord.js command which can be ran by a player and then will go onto a 24 hour cooldown, however the issue with the system below is I have no real way to store when there cooldown expires. Currently it is using an array of IDs however a user could simply time there command with the refresh of the cache and then claim it twice in quick succession.

So my question is

Is there a way to handle a per user cooldown via mySQL, or should another method be looked into. Any answer is appreciated!

const { SlashCommandBuilder } = require("@discordjs/builders");
const connection = require("../db");

let claimedCache = []

const clearCache = () => {
    claimedCache = []
    setTimeout(clearCache, 1000 * 60 * 60 * 24)
}
clearCache()

module.exports = {
    data: new SlashCommandBuilder()
    .setName('daily')
    .setDescription('Claim your daily points'),

    
    async execute(interaction) {
        if (claimedCache.includes(interaction.user.id)) {
            interaction.reply({
                content: "You have already claimed your daily reward!",
                ephemeral: true
            })
            return
        }
        connection.query(`SELECT * FROM characters WHERE char_owner = '${interaction.user.id}'`, function(err, rows) {
            if (err || !rows.length) {
                interaction.reply({
                    content: "You do not have a character!",
                    epehemeral: true
                })
                return
            }
            const currentPoints = rows[0].char_points
            
            if (interaction.member.roles.cache.has('912680123113832448')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 4}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680385685635092')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 8}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680439095889971')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 12}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680476790120448')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 16}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680542091243570')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 16}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            }

            //connection.query(`UPDATE characters SET char_points = '${currentPoints + 4}' WHERE char_owner = '${interaction.user.id}'`)
        })
    }
}```

How to call a modal when I return data a partial view from the controller in ASP.NET MVC

I have a controller where I return data in a partial view and I would like to call a modal, how can it be done?

I leave you the details of my controller and view below .

Controller

 [HttpPost]
 public async Task<ActionResult> Items(List<string> items)

  {
             
   var dto = new ItemsDetails();
   dto = items;

  return PartialView($"~/Views/Items/ItemDetails.cshtml", dto);
  (Here I want to call a modal)

}
           
 

View
That is the modal that I want to call.

<!-- Modal -->

@model Application.ItemsDetails

<div class="modal fade" id="items" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <tbody>
    @foreach (var item in Model.Items)
    {
    <tr>
        <td class="small">@item.Barcode</td>
        <td class="small">@item.ErrorMsg</td>
        <br>

    </tr>
    }
</tbody>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Webrtc screencapture or capturestream

Is there a way to capture on a specific part of the screen.. getting only the element or tag of HTML… I just want to share the video that is playing. I tried to find a solution. I tried the capturestream but the problem is there is no Output on my client-side. Any suggestion or who tried to stream only the video payer on capturestream?

Anyone who successfully broadcast live of the capturestream with broadcaster and client?

useState not working inside a custom react hook

I am Trying to separate some part of my business logic from view logic for this I am employing the use of custom react hooks which works like a controller.

My Component Structure

  1. Parent that contains toggle to switch between child 1 and child 2
  2. useCustomHook custom react hook that makes an api call and uses a state to add a loader
  3. child2 contains content to be shown which was retrieved from api call and state variable to show loader calls useCustomHook
  4. parent also calls useCustomHook which makes the api call on mount.

Why can’t I see loading on the page inside child 2 no matter how long it takes

I believe useState is setting flag to its default false when custom hook is called again on child 2

What way do i have to make use of useState hook in a custom react hook which is called from more than one place and not have the state reverted back to default value

flag is never true if you open child2

Here is the codesandbox link code

Here is the code

App.js acts as parent

import "./styles.css";
import Child1 from "./Child1";
import Child2 from "./Child2";
import { useEffect, useState } from "react";
import useCustomHook from "./customHook";
import { makeStyles } from "@material-ui/core";

const useStyles = makeStyles((theme) => {
  return {
    parent: {
      padding: "10px"
    },
    toggle: {
      margin: "10px",
      border: "1px solid black",
      display: "flex",
      justifyContent: "space-around"
    },
    child: {
      border: "1px solid black",
      width: "50%"
    }
  };
});

export default function App() {
  const [isChild1, setIsChild1] = useState(true);
  const classes = useStyles();
  const { flag, func } = useCustomHook();

  useEffect(() => {
    func();
  }, []);

  return (
    <div className="App">
      <div className={classes.parent}>Parent</div>
      <div className={classes.toggle}>
        <div
          onClick={() => {
            setIsChild1(true);
          }}
          className={classes.child}
        >
          ch1
        </div>
        <div
          onClick={() => {
            setIsChild1(false);
          }}
          className={classes.child}
        >
          ch2
        </div>
      </div>
      {isChild1 ? <Child1 /> : <Child2 />}
    </div>
  );
}

Child1.js

const Child1 = () => {
  return <div>Child1</div>;
};

export default Child1;

Child2.js

import useCustomHook from "./customHook";

const Child2 = () => {
  const { flag } = useCustomHook();

  console.log('flag ',flag);
  return (
    <div>
      <div>Child2</div>
      <div>{flag ? "loading..." : "content"}</div>
    </div>
  );
};

export default Child2;

CustomHook.js

import { useState } from "react";

const useCustomHook = () => {
  const [flag, setFlag] = useState(false);

  const sleep = async (ms) => {
    console.log("waiting");
    await new Promise((res, rej) => {
      setTimeout(() => {
        console.log("wait over");
      }, ms);
    });
  };
  const func = async () => {
    setFlag(true);

    //do some work like api call
    await sleep(10000);

    setFlag(false);
  };

  return { flag, func };
};

export default useCustomHook;

Typescript: Function accepting 2 Types but property doesn’t exist on one of the types

I have a function that takes 2 types.

handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) {
    e.stopPropagation();

    const newValue = this.computeValuesFromPosition(e.detail.x, e.detail.y, e.detail.variant);

    // other same code
})

the issue is that GridHandleDragEventType does not have a variant as part of the type. In those cases, I don’t mind sending null but I keep getting the TS issue:
Property 'variant' does not exist on type 'GridHandleDragEventType'. Is there a clean way to resolve this?

Eclipse is weird

enter image description here

Here, in this image, I have inserted the value of ‘int’ (number)variable=22, and in the braces beside ‘while’, I have entered (number < 20) and I have asked to print ‘alright’, and even the condition is not true here, the eclipse is printing ‘alright’!!

Highlighting text in Safari on iPad

I am developing an application that allows user to highlight text in a web app. With iOS on iPad many users would like to use their Apple Pencil to highlight text. While it is of course possible to highlight text by double tapping or holding the pencil down, I would like to enable users to activate a mode in which they can just brush over the text to highlight it.

Is there an API in Safari for iOS that enables such behaviour?

How to populate modal form inputs properly onto FullCalendar in javascript?

I am coming to an issue where I am trying to place the form details onto the calendar but I am stuck on this area. For testing purposes when I click on submit I am alerting the form details in that view. However, I just want it to be place on the calendar, similar to Google Calendar. Thank you for the help.
PS: Let me know if you want to see the html form as well.

here is my code:

Javascript:

    document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var myModal = new bootstrap.Modal(document.getElementById('schedule-edit'), {});
    var calendar = new FullCalendar.Calendar(calendarEl, {
        selectable: true,
        initialView: 'dayGridMonth',
        select: function(info, start, end, jsEvent) {
            myModal.show();
                if (info) {
               calendar.addEvent({
               title: title,
               start: info.startStr,
               end: info.endStr
               })
            calendar.unselect();
        },
    });
    calendar.render();
});

 function submitForm() {

        let title = document.getElementById("title").value || "";
        let project = document.getElementById("project").value || "";
        let time = document.getElementById("time").value || "";
        let timeSpent = document.getElementById("timeSpent").value || "";
        let description = document.getElementById("description").value || "";
        let editorS = document.getElementById("sampleeditor").value || "";
        let firstList = document.getElementById("firstList").value || "";
        let startDate = document.getElementById("myDate").value || "";
        let dueDate = document.getElementById("myDue").value || "";



        //for test only
       alert(title + project + time + timeSpent + description + editorS + firstList + startDate + dueDate);


    }

How can i display all the data from a data table in the Pie Chart.js?

I have this task where i have to display all the data from the table which i will provide it with an image, but i can only display the data that are shown in the data table when the pagination is: false. I need to display all the data when the pagination is: true.
This is the image display

<input class="form-control-xs" type="date" id="start" onchange="table.column(3).search(this.value).draw();">

<script>
'use strict'
let url='{{ $objApi }}';
let columnDef=[
    {"title":"ID","data":"0"},
    {"title":"Method","data":"1"},
    {"title":"Path","data":"2"},
    {"title":"Date","data":"3"},
    {"title":"Counter","data":"4"}
];

let table=$('#adminuser').DataTable({
    columns: columnDef,
    processing: true,
    serverSide: true,
    paging: true,
    ajax: {
        'url': url,
        'method': 'GET'
    },
    "searchCols": [
        null,
        null,
        null,
        {"search": currentDate},
        null
    ],
    "order": [[4, 'desc']],
    language: {
        searchPlaceholder: 'Search...',
        sSearch: '',
        lengthMenu: '_MENU_ items/page',
    },
});
</script>
 var ctx = document.getElementById("canvas").getContext("2d");
const data = {
                labels: [],


                datasets: [{
                    label: 'Counter',
                    data: [],
                    backgroundColor: [
                        'rgba(90, 57, 228, 0.7)',
                        'rgba(84, 73, 44, 1)',
                        'rgba(143, 105, 20, 0.1)',
                        'rgba(74, 3, 153, 0.1)',
                        'rgba(81, 35, 162, 0.6)'
                    ]
                }]
            }; 

let mychart = new Chart(ctx, {  type: 'pie', data: data, options: {plugins: {legend: {display: false}}},});

table.on( 'draw', function () 
{
    rows=table.rows().data().toArray();
    console.log(rows);
    let labels=[];
    let data=[];
    rows.forEach((element) => {
        labels.push(element[2] + ' ' + element[1]);
        data.push(element[4]);
    });
    mychart.data.labels = labels;
    mychart.data.datasets[0].data = data; // or you can iterate for multiple datasets
    mychart.update(); // finally update our chart
} );

How to add class name equal to the key to th in table on Ant Design Vue 3?

I need to add a class name to the th accordingly to the :key attribute in Vue 3 for some styles that I’m doing. I’m not sure how to do it and I was wondering if it’s possible to do it straight on the template. Can you guys help me?

This is my code:

<template>
     <a-table bordered :data-source="tableData.data" :columns="tableData.columns" :pagination="false" class="tableEditable">
        <template v-for="col in this.editableCells" #[col]="{ column, text, record }" :key="col">
            <div class="editable-cell">
                <div v-if="editableData[record.key + '|' + column.key] !== undefined" class="editable-cell-input-wrapper">
                    <a-input v-model:value="editableData[record.key + '|' + column.key]" @pressEnter="save(record.key, column.key)" type="number" />
                    <check-outlined class="editable-cell-icon-check" @click="this.save(record.key, column.key)" />
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ text || ' ' }}
                    <edit-outlined class="editable-cell-icon" @click="this.edit(record.key, column.key)" />
                </div>
            </div>
        </template>
        <template #buttonTable="{text, record}">
            <div class="editableTableButtonOption">
                {{text}}
                <Popper arrow :locked="true">
                    <button class="statusButtonCrud synch" v-if="showEditableButton(record.key)"> {{this.buttonText}} </button>
                    <template #content="{close}">
                        <div class="popperOptions">
                            <li v-for="options in this.optionsToEdit" :key="options" class="popperOptionsList" v-on:click="this.emitOption(options.method), close();">
                                {{$filters.translate(options.title)}}
                            </li>
                        </div>
                    </template>
                </Popper>
            </div>
        </template>
    </a-table>
</template>
<script>

import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

export default {
    name: 'TableEditable',
    props: {
        editableCells: Array,
        tableData: Object,
        buttonText: String,
        optionsToEdit: Array
    },
    emits: ['change', 'editRow', 'editColumn', 'editAllCells'],
    components: {
        CheckOutlined,
        EditOutlined
    },
    data(){
        return {
            editableData: {},
            selectedRow: '',
            selectedColumn: '',
            valueSaved: ''
        }
    },
    methods: {
        edit(row, column) {
            this.editableData[row + '|' + column] = this.tableData.data.filter((item) => row === item.key)[0][column];
        },
        save(row, column) {
            let data = {...this.tableData.data};
            if (this.editableData[row + '|' + column] == '') {
                data[row][column] = '0'
            } else {
                data[row][column] = this.editableData[row + '|' + column];
                this.valueSaved = data[row][column]
            }
            delete this.editableData[row + '|' + column];
            this.selectedRow = row;
            this.selectedColumn = column;
            this.$emit('change', data);
        },
        showEditableButton(row) {
            if (this.selectedRow == row) {
                return true
            }
        },
        emitOption(method) {
            this.$emit(method, this.selectedRow, this.selectedColumn, this.valueSaved);
        },
    },
}
</script>
<style>

Thanks in advance. If this question is not clear enough please let me know so I can edit it.

How can add properties to my objects based on the duplicates inside the array?

I have this array of objects

let arr = [
    {
        id: 1,
    },
    {
        id: 1,
    },
    {
        id: 2,
    },
    {
        id: 1,
    },
    {
        id:4,
    },
    {
        id: 3,
    },
    {
        id:4,
    }
]

i need to find and change every object in the array based on condition.
So if there are duplicates in the array i need to set on my objects 100 except last duplicate where i should have 200.
If i don’t have any duplicates than i should have again 200

So the output shpuld be

let arr = [
    {
        id: 1,
        number: 100
    },
    {
        id: 1,
        number: 100
    },
    {
        id: 2,
        number: 200
    },
    {
        id: 1,
        number: 200
    },
    {
        id:4,
        number: 100
    },
    {
        id: 3,
        number: 200
    },
    {
        id:4,
        number: 200
    }
]

so id 1 has duplicates.
That is why the fiurst occurences are set with number:100 and the last one i set with number:200.

Id 2 has number 200 because there are no duplicates and it is first occurance in the list.

what i tried

I got stuck at

for(let item of arr) {
    for(let item2 of arr) {
        if(item.id === item2.id) {
            item.number = 100;
        } else {
            item.number = 200;
        }
    }
}