I have a type that looks something like this:
type Location=`${number},${number};${number},${number};...`
Is there a Utility type like Repeat<T> that can do this for me?
like this:
type Location=Repeat<`${number},${number};`>
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I have a type that looks something like this:
type Location=`${number},${number};${number},${number};...`
Is there a Utility type like Repeat<T> that can do this for me?
like this:
type Location=Repeat<`${number},${number};`>
The below code achieves desired output. Is there a more elegant way to do this?
For example, is there some native javascript function like flatMap etc that would help?
(I know I could get rid of the intermediate variable pieces).
const config = {
fieldName1: {
validation: "schema1",
value: "abcvalue here"
},
fieldName2: {
validation: "schema2",
value: "abcvalue here"
},
}
// Desired output:
// {
// fieldName1: "schema1",
// fieldName2: "schema2",
// ...
// }
const extractValidation = (config) => {
const pieces = Object.entries(config).map(
([key, val]) => ({
[key]: val.validation
})
)
return Object.assign({}, ...pieces)
}
extractValidation(config)
So I created this script that retrieves the number of followers a playlist has on Spotify, and returns it to a cell in Google sheets. However, after working for over a year it is now broken and I can’t put my finger on why.
Here’s the script:
function SAMPLE(url) {
const res = UrlFetchApp.fetch(url).getContentText();
const v = res.match(/followers":({[sSw]+?})/);
return v && v.length == 2 ? JSON.parse(v[1].trim()).total : "Value cannot be
retrieved.";
}
Then I have the URL in a cell and next a simple formula of =SAMPLE(A1)
Here’s the error I’m getting: SyntaxError: Unexpected end of JSON input (line 4).
Any help or guidance would be highly appreciated.
Thank you!
I have a url and I want to replace the query string. For example
www.test.com/is/images/383773?wid=200&hei=200
I want to match the wid= and hei= and the numbers don’t have to be 200 to replace the whole thing so it should look like this.
Expected
www.test.com/is/images/383773?@HT_dtImage
So I’ve tried doing but it only replaced the matching wei and hei.
const url = "www.test.com/is/images/383773?wid=200&hei=200"
url.replace(/(wid)(hei)_[^&]+/, "@HT_dtImage")
When planting flowers in a pot, it’s important to make sure
that whenever you water your plant any water that doesn’t
get absorbed by the roots drains out the bottom of the pot.
Otherwise, the water will pool in the bottom of the pot and
cause your plant to rot.
You recently decided to plant some flowers of your own,
and decided to fill the base of the pot with gravel. You've
decided to write code to verify whether water will
successfully drain out of the pot.
Using a 2D array to represent your pot, individual pieces of
gravel are notated with a 1 and empty spaces between
gravel are notated with a 0.
Example Pot #1:
[
[0, 1, 1, 1, 1],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 1, 1, 0],
[1, 0, 0, 1, 0],
]
Write a function to determine whether the water can fall
from the top row to the bottom, moving through the
spaces between the gravel. Taking the example pot from
above, you can see the posible path, which is marked by
replacing the relevant 0's with asterisks (*)
[
[*, 1, 1, 1, 1],
[*, 1, *, *, *],
[*, *, *, 1, *],
[1, 1, 1, 1, *],
[1, 0, 0, 1, *],
]
Notice that the path includes both the top and bottom
rows.
Allowed moves:
The only moves allowed are up, down, left, and right.
Diagonals are not allowed.
Here are a few pots that don't drain properly, along with
explanations.
[
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
]
Explanation: The top row has no gaps
[
[1, 1, 1],
[1, 1, 0],
[1, 1, 1],
]
Explanation: The bottom row has no gaps
[
[1, 1, 1],
[1, 1, 0],
[1, 1, 1],
]
I have a div with multiple videos that when hovered on the video triggers a popover that contains the video that was hovered on. The problem I’m having is I’m cloning the video in the main div and appending it to the popover but when I clone the video it also clones the attributes of the video tag. What I want is when cloning the video before appending to popover removing the attribute autoplay and controls so that the video in the popover won’t play when hovered on the video. Is this possible? How can I remove the attribute before appending it to popover? Note: The main video tag needs the autoplay and controls attribute because I want it to start on load and also have controls.
I tried: $('video).attr("autoplay", "") and $('video).attr("autoplay", "false")
function appendImg() {
const newId = parseInt($('.infoBar').children().last().attr('id').replace('test', ''))
$('.infoBar').append('<div class="imgWrap" id="test' + (newId + 1) + '"><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4" controls autoplay/></div>')
addEvent();
}
var popOverSettings2 = {
selector: '.infoBar .imgWrap',
container: 'body',
html: true,
trigger: "manual",
placement: 'top',
sanitize: false,
animation: false,
content: function() {
setTimeout(() => {
$('.popover').css({
'width': '20%',
'height': '20%',
'overflow': 'auto'
})
})
if ($(this).attr('class') == 'imgWrap') {
const currnetInfoBarElementView = $(this).attr('id')
let source = $("#" + currnetInfoBarElementView).children()
$('.infoBarPopoverContent').empty().append('<div class="infoBarElementContentView"></div>')
$('.infoBarElementContentView').empty().append(source.clone(true).addClass('dataDisplayClone'))
$('.dataDisplayClone img').css({
'width': '100%',
'height': '100%'
})
return $('.infoBarPopoverContent').html();
}
}
}
function addEvent() {
$(function() {
$('.infoBar .imgWrap').popover(popOverSettings2)
.on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(".popover").on("mouseleave", function() {
$(_this).popover('hide');
});
}).on("mouseleave", function() {
var _this = this;
if (!$(".popover:hover").length) {
$('.popover').popover('hide');
}
});
});
}
addEvent()
button {
position: absolute;
top: 0%;
left: 0%;
}
.infoBar {
display: flex;
flex-direction: row;
position: absolute;
top: 30%;
max-width: 95%;
height: 160px;
margin: auto;
column-gap: 25px;
background-color: green;
overflow-x: auto;
}
.infoBar .imgWrap {
height: 100%;
cursor: pointer;
}
.infoBar .imgWrap video {
height: 100%;
cursor: pointer;
}
.infoBarPopoverContent {
display: none;
}
.popover .popover-body {
overflow-x: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<button onclick='appendImg()'>Click to append img</button>
<div class="infoBar" id="infoBar">
<div class="imgWrap" id='test1'><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls autoplay /></div>
<div class="imgWrap" id='test2'><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls autoplay /></div>
<div class="imgWrap" id='test3'><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls autoplay /></div>
</div>
<div class="infoBarPopoverContent"></div>
I’m updating my react project and after I updated webpack – I’m getting the following error
login:19 GET http://localhost:3000/assets/js/vendor/modernizr.min.js net::ERR_ABORTED 404 (Not Found)
login:20 GET http://localhost:3000/assets/js/customEvent.js net::ERR_ABORTED 404 (Not Found)
login:20 GET http://localhost:3000/assets/js/customEvent.js net::ERR_ABORTED 404 (Not Found)
My index html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="HandheldFriendly" content="True">
<meta name="author" content="XXX">
<meta name="description">
<link rel="shortcut icon" href="favicon.ico">
<!-- VENDOR STYLES-->
<link href="/assets/css/vendor/formValidation.css" media="all">
<link href="/assets/css/vendor/dataTables.bootstrap4.css" media="all">
<link href="/assets/css/vendor/responsive.bootstrap.min.css" media="all">
<!-- REQUIRED BASE STYLES (INCLUDES BOOTSTRAP 4 FRAMEWORK STYLES)-->
<script src="/assets/js/vendor/modernizr.min.js" type="text/javascript"></script>
<script src="/assets/js/customEvent.js" type="text/javascript"></script>
<base href="/" />
<title>Title</title>
</head>
<body style="-webkit-print-color-adjust:exact;">
<div id="app-root" class="page-wrapper">
</div>
</body>
</html>
My webpack is as follows. I’m using the copy plugin to move assets to /assets, however, when I’m pointing to where they originally were, it still shows an error.
My CSS files were also complaining but when I removed rel="stylesheet".
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const webpack = require("webpack");
const ESLintPlugin = require("eslint-webpack-plugin");
module.exports = {
output: {
publicPath: "/",
filename: "[name].[fullhash].js"
},
entry: {
main: "./src/Index.jsx",
appcss: "./src/styles/scss/app.scss",
customcss: "./src/styles/custom/main.scss"
},
module: {
rules: [
// Javascript and JSX
{
test: [/.js$/, /.jsx$/],
exclude: /node_modules/,
use: ["babel-loader"],
resolve: {
extensions: [".js", ".jsx"]
}
},
// SASS scss files
{
test: [/.css$/, /.scss$/],
use: ["style-loader", "css-loader", "sass-loader"]
},
// Fonts
{
test: /.(woff2?|gif|ttf|otf|eot|svg|png|jpg)$/,
type: "asset/resource",
// generator: {
// filename: "fonts/[name][ext][query]"
// }
}
]
},
plugins: [
new webpack.DefinePlugin({
APP_VERSION: JSON.stringify(process.env.npm_package_version)
}),
new CopyPlugin({
patterns: [
{ from: path.resolve(__dirname, "src/assets"), to: path.resolve(__dirname, "assets") },
{ from: path.resolve(__dirname, "src/styles/custom/assets"), to: path.resolve(__dirname, "assets/custom") }
]
}),
new CaseSensitivePathsPlugin(),
// Generates HTML file output with the bundles referenced in <script> and <link> elements
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new ESLintPlugin({
extensions: ["js", "jsx"],
})
],
resolve: {
alias: {
app: path.join(__dirname, "src"),
"app-api": path.join(__dirname, "src/api"),
"app-version": path.join(__dirname, "src/config/version.js")
}
}
};
Any help appreciated.
I have this object that I’m trying to loop over in a form but really can’t get it to work. Here is sample of the object.
const data = {
"Social Security": [
{
label: "Deduction Type",
value: "Social Security",
name: "SocialSecurity"
},
{
label: "Employer Rate",
value: "12.4%",
name: "SocialEmployer"
},
{
label: "Employee Rate",
value: "6.2%",
name: "SocialEmployee"
}
],
"Medicare": [
{
label: "Deduction Type",
value: "Medicare",
name: "Medicare"
},
{
label: "Employer Rate",
value: "1.45%",
name: "MedicareEmployer"
},
{
label: "Employee Rate",
value: "2.9%",
name: "MedicareEmployee"
}
]
}
form implementation
<Formik>
{({ values, isSubmitting, resetForm, setFieldValue }) => (
<Form id="payrollSettingsForm" >
<Grid container className={classes.border}>
<Grid item xs={12} md={4}>
{Object.entries(data).map(arr =>{
Array.isArray(arr) && arr.map(elm =>{
return (<TextField
label={elm.label}
value={elm.value}
name={elm.name}
/>)
})
})}
</Grid>
</Grid>
...rest of the form
</Form>
</Formik>
Tried many approaches like Object.fromEntries(). forEach I think all the methods I can find example and keep failing, maybe I’m doing something wrong, any help will be appreciated.
I have a line chart drawn with chart.js that shows some data.
I’ve added a delete element within the tooltip, but I don’t know if it’s possible to add an interaction, so that when I click the delete element, within the tooltip, some custom code is run that deletes the data from the Data base.
const weight_graphOptions = {
title: {
text: 'Weight',
display: true
},
scales: {
x: {
type: 'time',
time: {
// Luxon format string
tooltipFormat: 'dd-MM-yyyy'
},
title: {
display: true,
text: 'Date'
}
},
y: {
title: {
display: true,
text: 'kg'
}
}
},
plugins: {
tooltip: {
events: ['click'],
callbacks: {
afterFooter:
function (addDeleteButton) {
return 'Delete'
}
}
}
}
}
Does anyone know if I can do this without building my own custom-made tooltip?
How do I submit a form on an onChange event of an tag, with without triggering the default behaviour(Page reload). I found out, that I can access the form from the event with the .form element. But if I trigger .form.submit() the page reloads although I have stated on:submit|preventDefault.
I prepared an example of my Problem:
https://svelte.dev/repl/894212c7c3d847dd961745f5e9d5750a?version=3.46.2
Also is there like a clean/correct/best-practice way of solving this, without using an submit button?
Thanks in advance for your help!
I’m very new to React so any advice would be appreciated on how to move an agent thumbnail to the teamComp div when it is clicked.
I’m also lost as to how to tackle filtering the data through a dropdown menu. Like how would I update the page without refreshing so that only the agents with the selected roles appear.
Anything would help, like I said before, I am a complete beginner to React and feel like I am underutilizing a lot of what makes React powerful.
App.js
import { useEffect, useMemo, useState } from "react";
import AgentCard from "./components/agentCard";
import Select from "react-select"
function App() {
const options = useMemo(
() => [
{value: "controller", label: "Controller"},
{value: "duelist", label: "Duelist"},
{value: "initiator", label: "Initiator"},
{value: "sentinel", label: "Sentinel"},
],
[]
);
const [agentDetails, setAgentDetails] = useState([]);
const getAllAgents = async () => {
const res = await fetch("https://valorant-api.com/v1/agents/");
const results = await res.json();
const agentNames = [],
agentImages = [],
agentRoles = [],
agentDetails = [];
for (let i = 0; i < Object.keys(results["data"]).length; i++) {
if (results["data"][i]["developerName"] != "Hunter_NPE") {
agentNames.push(results["data"][i]["displayName"]);
agentImages.push(results["data"][i]["displayIcon"]);
agentRoles.push(results["data"][i]["role"]["displayName"]);
}
else {
continue;
}
}
for (let i = 0; i < agentNames.length; i++) {
agentDetails[i] = [agentNames[i], [agentImages[i], agentRoles[i]]];
}
agentDetails.sort();
setAgentDetails(agentDetails);
};
useEffect(() => {
getAllAgents();
}, []);
return (
<div className="app-container">
<h2>Valorant Team Builder</h2>
<div className="teamComp">
</div>
<Select options={options} defaultValue={options} isMulti/>
<div id="agent_container" className="agent-container">
{agentDetails.map((agentDetails) => (
<AgentCard
img={agentDetails[1][0]}
name={agentDetails[0]}
role={agentDetails[1][1]}
/>
))}
</div>
</div>
);
}
export default App;
agentCard.js
import React from 'react'
const agentCard = ({role, name, img}) => {
return (
<div className="card-container">
<div className="img-container">
<img src={img} alt={name} />
</div>
<div className="info">
<h3 className="name">{name}</h3>
<small className="role"><span>Role: {role}</span></small>
</div>
</div>
)
}
export default agentCard
index.css
@import url('https://fonts.googleapis.com/css?family=Muli&display=swap');
@import url('https://fonts.googleapis.com/css?family=Lato:300,400&display=swap');
* {
box-sizing: border-box;
}
body {
background: #EFEFBB;
background: -webkit-linear-gradient(to right, #D4D3DD, #EFEFBB);
background: linear-gradient(to right, #D4D3DD, #EFEFBB);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Lato';
margin: 0;
}
h1 {
letter-spacing: 3px;
}
.agent-container {
display: flex;
flex-wrap: wrap;
align-items: space-between;
justify-content: center;
margin: 0 auto;
max-width: 1200px;
}
.app-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 3rem 0.5rem;
}
.card-container {
background-color: #eee;
border-radius: 20px;
box-shadow: 0 3px 15px rgba(100, 100, 100, 0.5);
margin: 10px;
padding: 20px;
text-align: center;
}
.card-container:hover {
filter: brightness(70%);
transition: all 150ms ease;
}
.img-container img {
margin-top: 1.5rem;
height: 128px;
width: 128px;
}
.name {
margin-bottom: 0.2rem;
}
.teamComp h3 {
float: left;
}
I have a method that contains a for loop, and I have the main process and child processes calling this method.
20404 create: 2022-01-14 05:44:10.073
20404 create: 2022-01-14 05:44:10.075
20404 create: 2022-01-14 05:44:10.077
20404 create: 2022-01-14 05:44:10.077
send: 2022-01-14 05:44:10.078
send: 2022-01-14 05:44:10.079
send: 2022-01-14 05:44:10.079
16228 get 2022-01-14 05:44:10.081
11976 get 2022-01-14 05:44:10.081
9692 get 2022-01-14 05:44:10.082
11976 create: 2022-01-14 05:44:10.087
9692 create: 2022-01-14 05:44:10.087
16228 create: 2022-01-14 05:44:10.087
16228 create: 2022-01-14 05:44:10.113
9692 create: 2022-01-14 05:44:10.114
16228 create: 2022-01-14 05:44:10.116
11976 create: 2022-01-14 05:44:10.116
9692 create: 2022-01-14 05:44:10.117
16228 create: 2022-01-14 05:44:10.119
11976 create: 2022-01-14 05:44:10.121
11976 create: 2022-01-14 05:44:10.123
Above are logs, send is when main process sends the instruction to child process.
The first four lines are printed out from the main process, 2ms on average between every iteration
get is when a child process gets the instruction.
The first number is the process id. As you can see at this part:
11976 create: 2022-01-14 05:44:10.087
9692 create: 2022-01-14 05:44:10.087
16228 create: 2022-01-14 05:44:10.087
16228 create: 2022-01-14 05:44:10.113
9692 create: 2022-01-14 05:44:10.114
16228 create: 2022-01-14 05:44:10.116
The time gap between those two iterations is huge compared to the rest time gaps. Any ideas why this is happening?
I have got an array
const array = ['data: id=12kf1 value=29 id=12bhnd1 value=126 id=12kf1 value=29 id=12bhnd1 value=126id=12kf1 value=29 id=12bhnd1 value=126 id=12kf1 value=29 id=12bhnd1 value=126 ']
How can I count the sum of all the all value
I am using the following code from HERE which has been slightly modified. The logic of the code is: If destination sheet does not contain ID, import ID, and specific columns from source to destination.
var headerRowNumber = 1;const srcValues = srcSheet.getDataRange().getValues(); withconst srcValues = srcSheet.getDataRange().offset(headerRowNumber, 0, srcSheet.getLastRow() - headerRowNumber).getValues(); to avoid copying the header row from source.With or without these changes above, the error still occurs.
Google App Script: TypeError: Cannot read property ‘length’ of undefined (line *, file “Code”)
This error, refers to the line:
dstSheet.getRange(dstLastRow + 1, 1, values.length, values[0].length).setValues(values);
Prevent the script from copying blank (empty) rows from source to destination which is causing the error.
function importNewEmployeeIds() {
const srcSheetName = 'Source';
const dstSheetName = 'Destination';
const srcSheet = SpreadsheetApp.openById("SpreadsheetID1").getSheetByName(srcSheetName);
const dstSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(dstSheetName);
// Retrieve values from source sheet.
var headerRowNumber = 1;
const srcValues = srcSheet.getDataRange().offset(headerRowNumber, 0, srcSheet.getLastRow() - headerRowNumber).getValues();
// Retrieve values from destination sheet and create an object for searching the ID.
const dstLastRow = dstSheet.getLastRow();
const dstObj = dstLastRow == 0 ? {} : dstSheet.getRange("A1:A" + dstLastRow).getValues().reduce((o, [a]) => (o[a] = true, o), {});
// Create an array for putting to the destination sheet.
const values = srcValues.filter(r => !dstObj[r[1]]).map(r => [r[1], r[19], "", r[18]]);
// Put the values to the destination sheet.
dstSheet.getRange(dstLastRow + 1, 1, values.length, values[0].length).setValues(values);
}
On first execution of script, its successful, this is because the destination sheet has no blank (empty) rows. Once the script executes (copies row data from source to destination), it also copies the blank (empty) rows in the source sheet. Now that destination has blank(empty) rows, the script fails with this error.
Option A) At the beginning of the script, I could first delete all empty rows from the destination. This is less efficient, and does not fix the root of the issue, but at least it fixes my problem.
function removeEmptyRows(){
var sh = SpreadsheetApp.getActiveSheet();
var maxRows = sh.getMaxRows();
var lastRow = sh.getLastRow();
if (maxRows-lastRow != 0){
sh.deleteRows(lastRow+1, maxRows-lastRow);
}
}
Code found: HERE
Option B) Update the original code so it does not copy the blank rows.
[BEFORE]
const srcValues = srcSheet.getDataRange().offset(headerRowNumber, 0, srcSheet.getLastRow() - headerRowNumber).getValues();
[AFTER]
const srcValuesAndBlankRows = srcSheet.getDataRange().offset(headerRowNumber, 0, srcSheet.getLastRow() - headerRowNumber).getValues();
const srcValues = srcValuesAndBlankRows.filter(String); //Removes Blank Rows
Code Found: HERE
This code does not work. The blank rows are still copied. I suspect this is because I am using getDataRange() not getRange() like the original answer?
Option C) Modify the code so it’s not sensitive to spaces in the destination sheet. (no idea how to do this)
Option D) A better solution?