How to generate a valid UUID v4 that starts with specific characters?
Suppose I want to generate UUID v4 that starts with 00 – short of looping through random UUIDs until I get UUID that starts with 00, is there a better way of doing it?
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
How to generate a valid UUID v4 that starts with specific characters?
Suppose I want to generate UUID v4 that starts with 00 – short of looping through random UUIDs until I get UUID that starts with 00, is there a better way of doing it?
I’ve got a function that creates a cookie (I’m using sveltekit):
event.cookies.set(AUTH_TOKEN_KEY, response.data.token, {
// send cookie for every page
path: '/',
// server side only cookie so you can't use `document.cookie`
httpOnly: false,
// only requests from same site can send cookies
// https://developer.mozilla.org/en-US/docs/Glossary/CSRF
sameSite: 'strict',
// only sent over HTTPS in production
secure: process.env.NODE_ENV === 'production',
// set cookie to expire after a month
maxAge: 60 * 60 * 24 * 30,
})
the cookie is successfully created (see image):
championship-access-token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOiIyMDIzLTA1LTIyVDAxOjI4OjMwLjk0MzAwMTE3MloiLCJpYXQiOjE2ODQ3MTY5MTAsImlkIjo3fQ.VaVfzgnib0DhzRO8jUJ-X_2BRIiAGXIq8eEQOs85anI localhost / 6/20/2023, 8:55:10 PM 192 B ✓ Strict
Now, I’ve created an axios interceptor since I want to retrieve the token stored in the cookie and attach it to my requests. The problem is that I cannot access the cookie. I’m using js-cookie, and the interceptor looks like this:
import axios from "axios";
import Cookies from 'js-cookie';
export const app = axios.create({
baseURL: "http://127.0.0.1:8080/api/v1",
timeout: 1000,
params: {},
});
app.interceptors.request.use(
config => {
console.log("interceptor -> retrieving cookie:");
Cookies.set("test123", "asdasdasd")
console.log(Cookies.get(AUTH_TOKEN_KEY));
console.log("test cookie: ", Cookies.get("test123"))
console.log("cookie: ", Cookies.get(AUTH_TOKEN_KEY));
console.log("ALL COOKIES", Cookies.get())
config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
Promise.reject(error)
}
);
In the code above I’m not trying yet to attach the value of the cookie, I’m simply trying to retrieve it at the moment but it’s always undefined. I tried to create a new cookie using js-cookie but doesn’t seem to work. Notice that the original cookie was created using a cookie helper from Sveltkit which I cannot access at this point (or at least I don’t know how since it’s only accessible from server side files), reason why I decided to use js-cookie.
Any idea what’s going on? Perhaps is the import the one that I got wrong? I already tried:
import * as Cookies from 'js-cookie' yet the result is the same.
One more thing which I don’t know if it’s relevant to the question: notice this param used to create the cookie:
httpOnly: false,
even though it is set to false, the cookie is set as httpOnly (see screenshot).
Thanks
so i have a collection of forms that users sends I generate a match when some criteria is meet between 2 forms now i’d like to send the match information to a MongoDB collection but when trying it sends empty information.
I tried the next code with different variations but it doesnt seems to work, all it does in send an object with an ID and nothing else.
const newMatch = new Match(matches)
newMatch.save()
Extended example:
const express = require("express");
const router = express.Router();
const Forms = require("../models/Forms");
const Match = require("../models/Match");
const matchMaker = {
generateMatch: async (req, res) => {
let data;
let ignore = [];
try {
data = await Forms.find();
const result1 = findMatches1(data);
const result2 = findMatches2(data);
const result3 = findMatches3(data);
if (result1.length >= result2.length && result1.length >= result3.length) {
res.json(result1);
} else if (result2.length >= result1.length && result2.length >= result3.length) {
res.json(result2);
} else if (result3.length >= result1.length && result3.length >= result2.length) {
res.json(result3);
}
function findMatches1(data) {
data.sort((a, b) => a.time.length - b.time.length);
const matchedIds = new Set();
const matches = [];
for (let i = 0; i < data.length - 1; i++) {
if (matchedIds.has(data[i]._id)) continue;
const person1 = data[i];
const options1 = person1.time;
for (let j = i + 1; j < data.length; j++) {
if (matchedIds.has(data[j]._id)) continue;
const person2 = data[j];
const options2 = person2.time;
if (
person1.date === person2.date &&
person1.place === person2.place &&
person1.modality === person2.modality
) {
const commonTime = options1.find((time) => options2.includes(time));
if (commonTime) {
matches.push({
participant1: person1.firstName + ` ` + person1.surname,
participant2: person2.firstName + ` ` + person2.surname,
date: person1.date,
time: commonTime,
modality: person1.modality,
place: person1.place,
status: person1.status,
organization: person1.organization
});
matchedIds.add(person1._id);
matchedIds.add(person2._id);
break;
const newMatch = new Match (matches)
newMatch.save()
}
}
}
}
return matches;
}
Thank you for any insight you can provice
I am trying to add sha512 to a page for making the webpage more secure to make it harder for people to brute force the hash to get access to the secret in the url prams
heres the js:
(function() {
const GetPass = function() {
var usrpass = document.getElementById("userPassword").value;
const args = window.location.search;
const urlprams = new URLSearchParams(args);
var password = urlprams.get('password')
var hash = sha256(usrpass)
if (hash==password) {
var info = urlprams.get('secret')
var urle = atob(info)
var sec = decodeURI(urle)
const htm = sec.split("n")
htm.forEach(function (item, index) {
htm[index] = item + "<br/>"
});
var html = htm.join('')
document.body.innerHTML = (html);
document.title = 'reload to exit'
document.cookie = ''
} else {
alert('Incorrect Password!')
}
};
window.GetPass = GetPass;
})();
I tried using the crypto sha512 library but it errored out same with a function I tried
I have the below problem where I am trying to get the code from appleImg and pearImg to be put into an html element called middleCell should a button be clicked and based off a value of an input (input1). How can I make this work?
<table border="1">
<tr>
<td>
<input id="input1">
<button id="leftButton" onclick="fruitTest();">Enter</button>
</td>
<td>
<p id="middleCell">Hello</p>
</td>
<td>
<button id= "clearButton" onclick="clearBox();">Clear</button>
</td>
</tr>
</table>
var appleImg = "<img src="https://codehs.com/uploads/afcd3bf7ea7baf3f7d571c6e24c352af">";
var pearImg = "<img src="https://codehs.com/uploads/e0c442f8c020685fc8016f15c2547f1e">";
// Add your JavaScript code bel
var middleCell = document.getElementById("middleCell");
function fruitTest(){
var myInput = document.getElementById("input1");
var inputValue = myInput.value;
if (inputValue > 100){
middleCell.innerHtml = appleImg;
} else if (inputValue < 0){
middleCell.innerHtml = pearImg;
}
}
function clearBox (){
middleCell.innerHtml = "";
}
I wanted the value of the middleCell to show the images based of what was entered. When 101 is enetered and button clicked, the appkle image should show up.
Also, when clicking clear, the middleCell shoould be clear. Please help!
I tried migrating my React app, which was created using create-react-app, to use Vite. I followed a variety of sources of guidance, including this.
But now when I try running npm run start, I get this strange error in the devtools console. Any idea what would be causing this?
crbug/1173575, non-JS module files deprecated.
(anonymous) @ VM10:161
I looked at all the suggestions here and none of them seemed to help in my particular situation. For example, no launch.json file was created; and the DevTools Network tab already shows No throttling.
Another clue is that when I click on VM10:161, I see the contents of a script VM10, which contains a js class called loadTimeData.
I am developing an app in ASP.net Core MVC and am using Javascript for the connection between SignalR and the front-end. I want to take the sentence in a textbox, send that sentence to the back-end which will transform that sentence into TTs in the form of a temporary file and then attach that file to an <audio> element.
<script>
const connection = new signalR.HubConnectionBuilder().withUrl("/SandboxHub").build();
connection.start().catch(err => console.error(err));
$("#sentence-input").on("input", async function () {
const sentence = $(this).val();
await connection.invoke("TransformIntoTTS", sentence);
connection.on("ReceiveFile", function (fileUrl) {
$("#audio-player").attr("src", fileUrl);
const audioPlayer = document.getElementById("audio-player");
audioPlayer.load();
});
});
My sandbox hub:
public class SandboxHub : Hub
{
public async Task TransformIntoTTS(string sentence)
{
string filePath = await TTSConverter.SaveTTSAsTemporaryFileUSAsync(sentence);
await Clients.Caller.SendAsync("ReceiveFile", filePath);
}
}
Important logic:
var tempFile = Path.GetTempFileName();
using (var fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
{
await fileStream.WriteAsync(result.AudioData);
}
return Path.GetFileName(tempFile);
What should I do?
I’ve been using discord.js v12 until I was recently forced to switch to v14 because v12 doesn’t work anymore. I’ve looked through the docs and found .isDMBased() but it doesn’t work any help?
Code:
if(message.channel.isDMBased) {
console.log('DM')
} else {
console.log('Server')
}
I’ve tried sending a message in DMs and it doesn’t do anything. But when I send a message in the server channel it logs “DM”
How to remove specific words on a string (and add the word “and” if possible) that are repeated twice but only twice and only certain characters?
Example: “Intruction in seated LE AROM x10 each instruction in standing LE AROM x10 each”.
I want it to say, “Instruction in seated LE AROM and standing LE AROM x10 each”.
I have tried looping through it and removing duplicates, but it removes duplicates that I do need. I also tried this that I found from somebody else’s question, but they were just wanting to count how many times a word was repeated, so it didn’t help me much.
function removeDuplicate(str) {
let words = JSON.stringify(str).toLowerCase().split(' ')
let wordsCount = {}
words.forEach(word => {
wordsCount[word] = (wordsCount[word] || 0) + 1
})
}
Why does this recursive function work?
let arr = []
function rep(x, n) {
if (Math.sign(x) === -1) {
return []
}
if (x < 1) {
return 1
} else {
rep(x - 1, n)
}
arr.push(n)
return arr
}
console.log(rep(5, 5))
I’m learning JS and about recursive functions. I made the above function to output an array of x, n number of times in an array. E.g. rep(2,5) would output [5,5], rep (3,3) would output [3,3,3] etc. But I don’t fully understand why it works.
Am I right in thinking that the last thing the function does is return the completed array? If so, why does it not return [] or 1 when x goes to -1? I think I’m confusing myself but I’d appreciate an clear explanation. Thanks
I created the above function and was not expecting it work. So, I made it but I don’t fully understand why it works.
I created web assembly (C++) by Emscripten. I am making some tests in JS to clarify how memory allocation works.
I have click button handler
function handler() {
const imageData = getCanvasImage();
const buffer = imageData.data.buffer;
const bufSize = imageData.width * imageData.height * 4;
const dataPtr = Module._malloc(bufSize);
const dataOnHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, bufSize);
dataOnHeap.set(new Uint8Array(buffer))
Module._free(dataPtr);
}
I just allocate memory by _malloc and release memory by _free.
Image from my canvas takes 1.4MB.
Every time I click memory of browser grows. (I monitor browser process via ProcessExplorer)
What I do wrong?
How to release memory correctly?
Thanks
Uncaught (in promise) SyntaxError: Unexpected end of JSON input at JSON.parse ()
https://drive.google.com/file/d/1twc5gKGQAETPVT4oSukLppzT9DVgYbod/view?usp=share_link
I received this erros on the server where I deployed the project.
Php 7.4.
I have the same on my dev. server. There os no error.
I have the same on another server , There os no error..
The error is appering after the first update of the field value by Livewire. (sending data)
After it JS Error -> noting to do after.
I don’t have any ide how and where to start the investigation.
Thanks
Gergely
1- php artisan optimize:clear
2- clear vendor && composer install
3- take a copy from success version on another server , same error.
4- add “@php artisan vendor:publish –force –tag=livewire:assets –ansi” to composer.json
I’d like some help on a coding error I am encountering with Mocha. I am having a hard time figuring out what I am doing wrong.
I am attempting to test an API with the Mocha framework using data from a JSON file that contains an array and validate the request body and response body using chai. Using a forLoop, each request in the array should be read and the response for each should be returned. However, only the first request is returning using the following code:
describe('Validate the Response Body for Store Orders', async function(){
let request = require('../config/data/testFile1.json');
chai.expect(request.storeOrders.collectedOrders[0]).to.exist
response = await apiEndpoint.post(request);
for(let i=0; i < response.body[0].orderLookup.orderNumber.length; ++i){
console.log(response.body[0].orderLookup.orderNumber.length)
chai.expect(response.body[0].orderLookup.orderNumber.length).to.exist
}
})
The first response is coming back 4 times rather than the responses for each request coming in once.
Here is the expected response:
The Responses should be:
[
{
"orderLookup":{
"orderNumber":"22222"
"stateCode": "IA"
}
},{
"orderLookup":{
"orderNumber":"22392"
"stateCode": "IA"
},{ "orderLookup":{
"orderNumber":"444"
"stateCode": "RI"
},{
"orderLookup":{
"orderNumber":"239129"
"stateCode": "MI"
}
]
I am receiving this instead.
[
{
"orderLookup":{
"orderNumber":"22222"
"stateCode": "IA"
}
},{
"orderLookup":{
"orderNumber":"22222"
"stateCode": "IA"
},{ "orderLookup":{
"orderNumber":"22222"
"stateCode": "IA"
},{
"orderLookup":{
"orderNumber":"22222"
"stateCode": "IA"
}
]
Here is the JSON request body:
[
{
"storeOrders": {
"orderType": "2",
"orderID": "22222",
"orderDetails": {
"productType": "Standard"
},
"collectedOrders": [
{
"orderDate": "2023-09-03",
"customerAge": "22"
}, {
"orderDate": "2024-29-03",
"customerAge": "22"
}
],
"storeDetails": {
"storeState": "IA"
}
}
},
{
"storeOrders": {
"orderType": "1",
"orderID": "444",
"orderDetails": {
"productType": "Standard"
},
"collectedOrders": [
{
"orderDate": "2023-06-03",
"customerAge": "60"
}
],
"storeDetails": {
"storeState": "RI"
}
}
}, {
"storeOrders": {
"orderType": "22392",
"orderID": "34922",
"orderDetails": {
"productType": "Standard"
},
"collectedOrders": [
{
"orderDate": "2023-09-03",
"customerAge": "22"
}, {
"orderDate": "2024-29-03",
"customerAge": "22"
}
],
"storeDetails": {
"storeState": "IA"
}
}
},
{
"storeOrders": {
"orderType": "1",
"orderID": "239129",
"orderDetails": {
"productType": "Standard"
},
"collectedOrders": [
{
"orderDate": "2023-06-03",
"customerAge": "60"
}
],
"storeDetails": {
"storeState": "MI"
}
}
}
]
I tried using forEach instead of a for Loop and encountered the same issue.
When looking at the NextJS MongoDB Starter, I noticed this bit of code:
if (process.env.NODE_ENV === 'development') {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
global._mongoClientPromise = this.clientPromise;
}
Here is a link to the file I am talking about.
Now, I know of the global object, but what I do not understand is how merely assigning a value to it preserves it, since global._mongoClientPromise is never accessed thereafter. In fact, this is the only line in the entire project where this property is used. Maybe it is obvious to some, but I am not a JavaScript expert, so can somebody please explain this to me?
In JS for example, is n + 0.5 - 0.5 always going to equal n, for any integer n? If so is it because 0.5 is a power of 2 and so can be represented exactly?