file:///C:/Users/matth/Downloads/Program%20Three.pdf
Having trouble with my assignment I am unable to make a loop with a quit command in the menu
Category: javascript
Category Added in a WPeMatico Campaign
How to calculate how many items goes in which group?
Given a number of groups (g) and a number of records (r) how to calculate how many records goes in each group by evenly distributing them?
Result should be the same as the following function, but how to get the same result without creating each array?
func = ( g, r ) => {
groups = [...Array(g).keys()].map( () => [] );
for(i=0, j=0; i<r;i++) {
groups[j].push(i);
j++;
if ( j === groups.length) j = 0;
}
return groups.map( (v) => v.length );
}
func(4, 2); //[1, 1, 0, 0]
func(4, 10); //[3, 3, 2, 2]
PHP web page work with WAMP but fails on GoDaddy
I am developing a web page using HTML, PHP and Javascript. I amp using WAMP server to develop it on my local machine. It has one PHP function:
$file = fopen("Records.txt","r");
$line = fgets($file);
fclose($file);
?>
It has one line of code within the Javascript portion to retreave $line:
```let fullstring = <?php echo json_encode($line); ?>;
It works fine using WAMP. If I view the source I see that the above line is:
```let fullstring = "Record1,Record2,Record3,Record4,Record5,Record6";
I then uploaded the file to GoDaddy and it fails. I see this instead:
```let fullstring = false;
Anyone know why? Is there a different way to retreive a PHP variable via Javascript? Eventually I need to change this because the variable $line value should not be exposed to the user.
How to use functions inside useEffect hook?
I have a function that gets users location and puts it into redux store.
export async function getLocation() {
const dispatch = useDispatch();
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== "granted") {
setErrorMsg("Permission to access location was denied");
return;
}
let location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true,
accuracy: Location.Accuracy.BestForNavigation,
maximumAge: 1000,
});
dispatch(
setLocation({
longitude: location?.coords?.longitude,
latitude: location?.coords?.latitude,
})
);}
I want to use this function inside the useEffect hook so I can take users location when they open up the application. But when I put the function inside useEffect it throws an Invalid Hook Call error. I wanna solve this problem and if you have any other opinions on getting users location I will be glad to hear them.
const Navigation = () => {
useEffect(() => {
getLocation();
}, []);
return (
<NavigationContainer>
<RootStackScreen />
</NavigationContainer>
);};
export default function App() {
return (
<Provider store={store}>
<Navigation />
</Provider>
);
}
The code sample I mentioned is above.
versions:
"expo": "~44.0.0",
"react-native": "0.64.3",
"react-redux": "^8.0.2",
"react": "17.0.1",
why does next.js return error when calling a method of array that is not assigned to a variable
I get an error when calling an unassigned array literal
[1,2,3].forEach(i=>i)
In plain JavaScript, this works fine, but in next.js I get
TypeError: Cannot read properties of undefined (reading '3')
When I assign the array to a variable it works but I don’t understand I it does not work without assigning the array
Algorithm:Three numbers multiply through three loop?
I need to compute data based on three integers
For example: A:001 B:002 C: 003.I’m going to get 1 times 2 times 3, six pieces of data
The result like: Arr = [1-1-1, 1-1-2, 1-1-3, 1-2-1, 1-2-2, 1-2-3]; This is my code
for (let index = 1; index < 2; index++) {
for (let indexB = 1; indexB < 3; indexB++) {
for (let indexC = 1; indexC < 4; indexC++) {
console.log(`${index}-${indexB}-${indexC}`);
}
}
}
Yes, it uses 3 for loops.Is there a more efficient algorithm?
Mock single function from module in Jest and assert on it
I’m trying to mock out a single function in a module with Jest and assert that I have called it with certain parameters. I have a file that roughly looks like so:
export const f = () => {
...
}
export const g = () => {
...
f(...)
}
export const h = () => {
...
g(...)
}
I’m trying to test out functions g and h, and one the assertions I’m trying to write is that f gets called with certain parameters when calling g and h. So in my tests, I want to mock out f and be able to assert what it was called with. However, when I do something like this in my tests:
import f, g, h from 'module'
jest.mock('module', () => {
const original = jest.requireActual('module')
return {
...original,
f: jest.fn()
}
})
test('g calls f correctly', () => {
g()
// I want to assert that f was called with some parameters
})
I have no reference to f, and it seems like when g gets called in the test, the actual function f is being called rather than a mock. What do I need to change here to get this working?
Use link instead of file in app.js for mp3s and jpgs – React
I am very new to react and am trying to understand how this project works: https://github.com/iamfortune/Spotify-clone-with-Ts-audio. Its from this article where you can make your own mp3 player using react: https://blog.logrocket.com/build-spotify-clone-react-ts-audio/
In there example, they have real music and pictures that are apart of the project in the src/music directory. However I want to try and use images and mp3s that are already on the internet. Here is what I tried:
// Music import
import selectremix from 'https://vgmsite.com/soundtracks/tekken-1995-ps1/ocbigjtcaz/01%20-%20Select%20%28remixed%29.mp3'
import Eyes from './music/01. Jon Bellion - Eyes To The Sky.mp3';
import Mood from './music/24kGoldn-Mood-Official-Audio-ft.-Iann-Dior.mp3';
###More below
The files from ./music/etc work but not https://vgmsite.com/soundtracks/tekken-1995-ps1/ocbigjtcaz/01%20-%20Select%20%28remixed%29.mp3 as a cors issue happened.
I am pretty sure this isn’t a cors issue because I was able to use https://codepen.io/craigstroman/pen/aOyRYx and put in the same mp3 link into the html file and it works. I think its because I am trying to import a url as file instead of just using the file on the web.
Is there a way I should approach links from the internet instead of files on the computer in this case? Here is the full app.js file. If you need anything else let me know:
import React, { useMemo, useState } from 'react';
import Player from './Player';
import { AudioPlaylist } from 'ts-audio';
// Music import
import selectremix from 'https://vgmsite.com/soundtracks/tekken-1995-ps1/ocbigjtcaz/01%20-%20Select%20%28remixed%29.mp3' ###This fails
import Eyes from './music/01. Jon Bellion - Eyes To The Sky.mp3';
import Mood from './music/24kGoldn-Mood-Official-Audio-ft.-Iann-Dior.mp3';
import Audio from './music/audio.mp3';
import Broken from './music/Cant Be Broken .mp3';
import Lazarus from './music/Lazarus.mp3';
import Sia from './music/Sia - Bird Set Free.mp3';
import Nobody from './music/T-Classic-Nobody-Fine-Pass-You.mp3';
import Yosemite from './music/Yosemite.mp3';
// Pictures import
import tekkenImg from 'https://vgmsite.com/soundtracks/tekken-1995-ps1/thumbs/cover.jpg'; ###This fails
import EyesImg from './images/Eyes to the sky.jpeg';
import MoodImg from './images/mood.jpeg';
import AudioImg from './images/lana.jpeg';
import BrokenImg from './images/lil wayne.jpeg';
import LazarusImg from './images/dave.jpeg';
import SiaImg from './images/sia.jpeg';
import NobodyImg from './images/nobody.jpeg';
import YosemiteImg from './images/travis.jpeg';
export default function App() {
const [currentSong, setCurrentSong] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);
const songs = useMemo(
() => [
{
title: 'Select (Remix)',
artist: 'Yoshie Arakawa, Shinji Hosoe, Nobuyoshi Sano, Takayuki Aihara, Hiroto Sasaki',
img_src: tekkenImg,
src: selectremix
}, ###This will not play
{
title: 'Eyes to the sky',
artist: 'Jon Bellion',
img_src: EyesImg,
src: Eyes,
},
{
title: 'Lazarus',
artist: 'Dave',
img_src: LazarusImg,
src: Lazarus,
},
{
title: 'Yosemite',
artist: 'Travis scott',
img_src: YosemiteImg,
src: Yosemite,
},
{
title: 'Bird set free',
artist: 'Sia',
img_src: SiaImg,
src: Sia,
},
{
title: 'Cant be broken',
artist: 'Lil wayne',
img_src: BrokenImg,
src: Broken,
},
{
title: 'Mood',
artist: '24kGoldn',
img_src: MoodImg,
src: Mood,
},
{
title: 'Nobody fine pass you',
artist: 'T-Classic',
img_src: NobodyImg,
src: Nobody,
},
{
title: 'Dark paradise',
artist: 'Lana Del Ray',
img_src: AudioImg,
src: Audio,
},
],
[]
);
const playlist = useMemo(() => {
return AudioPlaylist({
files: songs.map((song) => song.src),
});
}, [songs]);
const handlePlay = () => {
playlist.play();
setIsPlaying(true);
};
const handlePause = () => {
playlist.pause();
setIsPlaying(false);
};
const handleSkip = () => {
playlist.next();
setIsPlaying(true);
setCurrentSong(
(currentSong) => (currentSong + 1 + songs.length) % songs.length
);
};
const handlePrevious = () => {
playlist.prev();
setIsPlaying(false);
setCurrentSong(
(currentSong) => (currentSong - 1 + songs.length) % songs.length
);
};
return (
<>
<div className="App">
<div className="c-player">
<div className="c-player--details">
{' '}
<div className="details-img">
{' '}
<img src={songs[currentSong].img_src} alt="img" />
</div>
<h1 className="details-title">{songs[currentSong].title}</h1>
<h2 className="details-artist">{songs[currentSong].artist}</h2>
</div>
<Player
play={handlePlay}
pause={handlePause}
isPlaying={isPlaying}
setIsPlaying={setIsPlaying}
next={handleSkip}
prev={handlePrevious}
/>
</div>
</div>
</>
);
}
Pushing input into a array
For the most part, i got it all done. But when i refresh the page it does not save into the array and i cant find it, how do i make it so its not just a temp array and keep it in the website. Here is my code
const output = document.getElementById("joke")
var jokes = ["test123", "test1235", "testting 1"]
function inputJoke() {
boxvalue = document.getElementById('box').value;
jokes.push(boxvalue);
console.log(jokes);
return false;
}
function randomChoice(){
return jokes[Math.floor(Math.random() * jokes.length)]
}
function jokeText(){
output.innerHTML = `${randomChoice()}`
}
<div class="container">
<h3>Douglas Dad Joke Generator</h3>
<br>
<br>
<button id="jokeBtn" onclick="jokeText()" class="btn">Get Another Joke</button>
<div class="text" id="joke"></div>
<form onsubmit="return inputJoke()">
<input class="submit" placeholder="Dad joke" type="text" id="box">
<input class="submit" type="submit" value="Submit">
</form>
</div>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
Here is the website https://dad.sscottdev.com
Generate an array in React using specific code
I need to generate an array of 10 items and this is the code I have to use.
for (let i = 0; i < 10; i++) {
vehicles.push({
manufacturer: faker.vehicle.manufacturer(),
model: faker.vehicle.model(),
type: faker.vehicle.type(),
fuel: faker.vehicle.fuel(),
vin: faker.vehicle.vin(),
color: faker.vehicle.color()
})
}
My question is how do I use it? So far I have this:
import React from 'react';
import Stack from 'react-bootstrap/Stack'
import VehicleActions from './VehicleActions';
import VehicleList from './VehicleList';
import Vehicle from './Vehicle';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { vehicles: [] };
this.onNewContact = this.onNewContact.bind(this);
this.handleContactSelected = this.handleContactSelected.bind(this)
this.handleDeleteContact = this.handleDeleteContact.bind(this)
}
onNewContact(vehicle) {
this.setState((state) => {
return {
vehicles: state.vehicles.concat(vehicle)
}
})
}
handleContactSelected(manufacturer) {
this.setState((state) => {
return {
selected: manufacturer
}
})
}
handleDeleteContact(manufacturer) {
this.setState((state) => {
return {
vehicles: state.vehicles.filter((vehicle) => vehicle.manufacturer !== manufacturer),
selected: null
}
})
}
handleGenerateVehicle() {
this.props.onNewContact(this.generateContact())
}
render() {
return (
<Stack gap={3} className="col-md-10 mx-auto">
<VehicleActions onNewContact={this.onNewContact}
selectedContact={this.state.selected} />
<Vehicle />
<VehicleList vehicles={this.state.vehicles}
onContactSelected = {this.handleContactSelected}/>
</Stack>
)
}
}
export default App
I’m using the “npm install react-bootstrap bootstrap @faker-js/faker” to generate the random text, I have tested it in the alert or console log and it works, but I have no clue where to insert it so the 10 values are shown in a column.
Selenium Webdriver: Fallbacks for Wait Timeout Exceptions?
I’m currently using Selenium WebDriver (ran through node.js) to scrape a bunch of weather data dispersed over several decades (since the site only loads one day’s worth of data per page at my desired full resolution!). An integral part of the process thus involves jumping between URLs, waiting for the appropriate data table (if applicable) to load for the page of each corresponding date.
While my current approach works for the vast majority of pages, using the explicit waiting method await driver.wait( until.elementsLocated( By.css( #myDataTableOfInterest)), 10000), there are occasional periods with no available data (where the website omits the table element altogether), thus also triggering a TimeOut error on my scraper (since the non-existent table obviously can’t be found!) that unfortunately also halts my entire program.
I assume however there must be some fairly standard fallback built into Selenium’s waiting methods that lets you run alternative code (or simply move on to the rest of the test – perhaps with some log) in case an expected condition doesn’t materialize after the specified waiting time?
My original thought was to bypass it by attaching .then(<some empty/log function>,error => {continue}) (since this code is happening in a loop that iteratively updates the day URL) but it appears that the “continue” operation isn’t valid if it’s nested inside a function within the loop..
Mitt event bus, not working inside axios interceptor but works fine in my vue components
I’m working with VueJs and mitt for the eventBus, the mitt is loaded globally as you can see and works fine :
main.js
const emitter = mitt();
const app = createApp(App)
app.config.globalProperties.emitter = emitter
I call the eventBus in all my component like that : it works fine
this.emitter.emit(‘eventName’, data)
My problem is when I use that inside axios interceptor I get an error ( undefined )
my client.js ( axios instance )
const client = axios.create({
// withCredentials: true,
baseURL: ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://mydomain.test/api')
});
client.interceptors.response.use((response) => {
// problem is here
this.emitter.emit('alert', response.data);
return response;
}, (error) => {
return Promise.reject(error.message);
});
export default client;
How to manage this array [duplicate]
I want to know what is the best way to manage the next array to count the answers per day and return the expected result, with dynamic data.
My array:
[
{
Date: 2022-06-17,
Answer: "New"
}
{
Date: 2022-06-17,
Answer: "New"
}
{
Date: 2022-06-17,
Answer: "Update"
}
{
Date: 2022-06-18,
Answer: "New"
}
{
Date: 2022-06-18,
Answer: "Delete"
}
{
Expected return with a function:
[
{
Date: 2022-06-17,
New: 2,
Update: 1
}
{
Date: 2022-06-18,
New: 1,
Delete: 1
}
]
I’m not looking for someone to make it for me, just want to know what method would you use
I am getting a 404 error page after deploying my react app on Github (help please)
So I followed the steps on installing gh-pages and deploying my project onto github. However, my github page is giving me a 404 error and gave me this message:
“If this is your site, make sure that the filename case matches the URL.
For root URLs (like http://example.com/) you must provide an index.html file”.
I have been googling around and nothing comes up.
I even switch the branch to gh-pages, but the page comes out blank.
Here is my package.json file:
{
"name": "dessert-menu",
"version": "0.1.0",
"homepage": "https://aaronv-github.github.io/DessertMenu/",
"private": true,
"dependencies": {
"-": "^0.0.1",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "^5.0.1",
"save": "^2.5.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -b master -d build",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"gh-pages": "^4.0.0",
"react-router-dom": "^6.3.0"
}
}
Node: how to test multiple events generated by an async process
I need to test an async Node.js library which periodically generates events (through EventEmitter) until done. Specifically I need to test data object passed to these events.
The following is an example using mocha + chai:
require('mocha');
const { expect } = require('chai');
const { AsyncLib } = require('async-lib');
describe('Test suite', () => {
const onDataHandler = (data) => {
expect(data.foo).to.exist;
expect(data.bar).to.exist;
expect(data.bar.length).to.be.greaterThan(0);
};
it('test 1', async () => {
const asyncLib = new AsyncLib();
asyncLib.on('event', onDataHandler); // This handler should be called/tested multiple times
await asyncLib.start(); // Will generate several 'events' until done
await asyncLib.close();
});
});
The problem is that even in case of an AssertionError, mocha marks the test as passed and the program terminates with exit code 0 (instead of 1 as I expected).
The following uses done callback instead of async syntax, but the result is the same:
require('mocha');
const { expect } = require('chai');
const { AsyncLib } = require('async-lib');
describe('Test suite', () => {
const onDataHandler = (data) => {
expect(data.foo).to.exist;
expect(data.bar).to.exist;
expect(data.bar.length).to.be.greaterThan(0);
};
it('test 1', (done) => {
const asyncLib = new AsyncLib();
asyncLib.on('event', onDataHandler);
asyncLib.start()
.then(asyncLib.close)
.then(() => done());
});
});
I have also tried with a “pure” Node.js approach using the native assert.ok without any 3rd part library:
const { strict: assert } = require('assert');
const { AsyncLib } = require('async-lib');
const test = async () => {
const onDataHandler = (data) => {
assert.ok(data.foo != null);
assert.ok(data.bar != null);
assert.ok(data.bar.length > 0);
};
asyncLib.on('event', onDataHandler);
const asyncLib = new AsyncLib();
await asyncLib.start();
await asyncLib.close();
}
(async () => {
await test();
})();
Even in this case, an AssertionError would make the program to terminate with exit code 0 instead of 1.
How can I properly test this code and make the tests correctly fail when is there an assertion error?