- Local Storage (Weight: 10%) When the user clicks one of the buttons in the top right corner
(gold or gray), the system stores the color in the local storage and changes the color of “Best
Cakes” to either gold or gray. When the page first loads, it reads the color in the local storage,
and styles “Best Cakes” accordingly. Write code in the set_color function (in script.js) so that the
color is stored in the local storage. Write code in show_color function (in script.js) so that the
color is red from local storage and used to color “Best Cakes”. - Building the cakes table based on JSON (Weight: 45%) Write JS code in the show_cakes
function in script.js that does the following: The code loops through the cakes in data.js so that
it generates HTML for data rows that show the number, cake name, calories, whether the cake
is nut free, dairy free, and gluten free. The generated HTML should be shown in the body of the
cakes table (id=cakes). Some data need to be shown in this way. If the calories are greater than
4500, show the calories in red. Otherwise, if the calories are greater than 4200, show it in
orange. Otherwise, show it in green (see Figure 1). You can add styling in style.css to help you
with this part.
For the nut-free, dairy-free, and gluten-free attributes, if the value is true, show a checkmark
symbol (which is ✔). Otherwise, show a symbol dash symbol (-). Again, have a look at
Figure 1.
Also, there is a search box on top of the cakes table. When the user types letters, the system will
find cakes with names that match the names of the cakes in the data. Also, the search can find
cakes based on the allergy type (e.g. nut free/cake free/etc.) - Building the leaflet map (Weight: 30%) Show a leaflet map for Abu Dhabi. The map should be
centered in these coordinates: 24.4539,54.3773, and with a zoom level of 12.
Then, write a script (in the function show_map) that loops through the locations data in data.js
(the variable locations). Add these as markers on the map. When the user clicks a marker, it
shows the name of the location. See Figure 2. - Form Validation (Weight: 15%) Validate the Order Your Cake form according to this logic:
The name must be at least 10 characters long.
If the user chooses a pecan pie cake, and nut allergies, an error message should show
up: “Sorry, pecan pies have nuts”. If the user chooses a cheese cake and dairy allergies,
an error message should show up: “Sorry, cheese cakes have dairy”.
Category: javascript
Category Added in a WPeMatico Campaign
Webrtc: how to broadcast one student to all participants
I have a WebRTC system that has one teacher, 10 or more students. The architecture is every student only connects to teacher.
The students are not interconnected since the network bandwidth is not as good as teacher, if too much connection may cause congestion.
But I now have a requirement that one student may need to broadcast to all students as well as the teacher(eg. the student is answing a question)
At this time I don’t want this student to connect to all other students, for the reason I mentioned above.
Is it possible use teacher as a proxy since the all the students have connected to teacher? I googled one possible method to route the teacher’s speaker(the student’s voice can be heared) to teacher’s microphone, but with no luck.
object conversion between objects javascript
how to change object from
const ob = {
"61ac2727bc40d842e43c8726": {
nama: {
value: "dianaasdasd",
},
username: {
value: "diana",
},
email: {
value: "[email protected]",
error: false,
},
userlevel: {
value: "karyawan",
},
password: {
value: "************************************************************",
},
jenis_kelamin: {
value: "Perempuan",
},
alamat: {
value: "sasddad",
},
},
};
remove “61ac2727bc40d842e43c8726”, value and return object as follows
how to convert to
this image
Background color change on hover not working (jquery)
I’m hoping someone can help me with an issue I am having. I am trying to change the background color of my page when mousing over a nav link on the page. I have tried to use jquery for this (last lines of my js code) but it doesn’t seem to be working. I think some of my other Js is interfering in some way because it worked on a simple test page before.
https://codepen.io/adamkelly153/pen/gOGaJYq
$('#hover-01').on('mouseenter', function(){
$('#hover-change').css('background-color', 'blue');
});
$('#hover-01').on('mouseleave', function(){
$('#hover-change').css('background-color', 'red');
});
Any help much appreciated! Sorry if I have missed some key info, happy to provide it.
Adam
Mocked imported function is not called by jest unit test
I just want to mock a function which is imported in the function, which I want to test:
content.ts
import { getFileContent } from './files' // Mock this one
export const example = async (argv) => { // This function should be tested
let result = {}
const { nodes } = await getFileContent(argv) // Mock this one
console.log(nodes)
result = nodes.type
return result
}
file.ts
export const getFileContent = async (argv) => {
try {
return reader(argv.path) // reader is a function inside this file which reads files using `fs`
} catch (error) {
console.error(error)
}
}
content.spec.ts
import { example } from './content'
const mockGetContent = jest.fn(() =>
Promise.resolve({ nodes: { type: 'app' } })
)
jest.mock('./files', () => ({
getFileContent: () => mockGetContent
}))
test('should call mock function', async () => {
const argv = { path: './file.json'}
await example(argv)
expect(mockGetContent).toHaveBeenCalled()
})
But the expect fails, as mockGetContent
has not been called. Also the console.log
prints undefined
.
What am I missing?
Firebase Hosting Authentification signInSuccessUrl not working
I have a problem that after Firebase Hosting Authentification the link to my page (signedIn.html) is not working (Failed to load resource: the server responded with a status of 404 ()).
The authentification itself seems to be working working well, and if I test it on Visual Studio Code debugger, the link to “signedIn.html” is also working, but not on firebase hosting after firebase deploy.
According firebase deploy protocol, all files are successfully uploaded to firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult(authResult, redirectUrl) {
return true;
},
uiShown() {
document.getElementById('loader').style.display = 'none';
},
},
signInFlow: 'popup',
signInSuccessUrl: 'signedIn',
signInOptions: [
firebase.auth.EmailAuthProvider.PROVIDER_ID,
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
],
};
ui.start('#firebaseui-auth-container', uiConfig);
How can we detect parent component’s state variable changing in react child component?
I want to execute some action in child component.
For example, when I click navigation bar button, navigation bar will be not visible and bar chart element width will be full size
But it requires to redraw chart and chart is placed in child component.
Please note your idea to solve this problem.
google sheets. transfer of data from one sheet to another (in different ranges) according to different conditions
please help with the script. I will briefly describe what is needed: there is a sheet with data, this data must be distributed to another sheet according to the condition.
in detail what needs to be done is written in the table on the “log” sheet
https://docs.google.com/spreadsheets/d/1Kw-H6hte7hriPPUQNzMKGxjiH4fQSN3gyQmNo-WZ8fc/edit?usp=sharing
(list of messages LOG telegrams chat. these messages have data about a stock market transaction
Chat telegram messages will be saved (written) to this list using a script. they look like the one shown above. the first column shows the date and time the message was sent. the second column contains the name of the transaction (RUB / USD / EUR and others). all other columns have additional information for column 2 (transaction date / purchase price / commission / ticker and others).
task: it is necessary to distribute these transactions into the necessary groups on the “distribution” sheet. for example: new data came to the “log” sheet (they always come in the first line, and the old data is shifted below, for more details in the table script). they look like this
enter image description here
data is sorted by color, so it’s easier to explain. column 2 (light red color, has “euro”) – the script must determine that the “euro” group is located in the range “AK: BA” on the “distribution” sheet. and transfer the first data (slightly darker red) “S:J” to the range “AL: AS” on the sheet “distribution” and the second data (dark red) “K: L” to the range “AZ:BA” also to the sheet ” distribution”
that is, everything is carried according to the color to the bottom empty line
cells on the “distribution” sheet of standard red should not change
by the way. column 2 should not be carried over to the “distribution” sheet. it just contains information where the data should be parsed)
Call javascript on window that triggered another window to open
I have index1.html and index2.html
From index1.html I opened index2.html using window.open(‘https://localhost/index2.html’, ‘windowName’, ‘width=500, height=350, left=24, top=24, scrollbars, resizable’)
How to I call a script on index1.html from the newly opened window?
Settimout use old data
I have an array of message messages from a bot and a user. First, the add Bot Message function is triggered, where a message from the user is first added, and then from the bot after 2 seconds.
What is the problem:
The message from the user (the addUserMessage function) works fine, but after 2 seconds it adds a message from the bot, but at the same time deletes the user’s message.
I understand that setTimeout uses the old data of the message array and rewrites the message from the user
How to fix it? Thanks
const [messages, addMessages]=useState([]);
const addBotMessage=async (value, callback)=>{
addUserMessage(value, callback);
setTimeout(()=>{
addMessages([...messages,{content:BotContent[callback], time:getTime(), author:'bot'}]);
},2000)
}
const addUserMessage=(value, callback)=>{
if(!value) return;
addMessages([...messages,{content:value, time:getTime(), author:'user'}]);
}
Problem accessing ag-grid table data from VB.Net
Is there a way to loop through a javascript ag-grid table row by row from vb.net in code behind.
Remove n characters after a certain string
I have this
<div id="oZlbx"></div><div id="Yj0SU"></div>
I want to remove the 9 characters after id= in order to have
<div id=></div><div id=></div>
What is the proper way to do this?
Flatten MongoDB nested object
I have a collection which looks like this:
[{
productId: "c69b7701-c33f-4801-99f3-080450f2b6c7",
createdAt: "2021-12-04T17:33:34.221Z",
history: [{
value: 304,
storePrice: 50,
date: 1638639214000,
prevSold: {
price: 303,
createdAt: "2021-12-04T17:32:50.658Z"
}
}, ... 100+ more records]
_id: "61aba66d9085f0044f96a700"
}, ... 100+ more records]
And I’m just calling it with a basic find ie:
const slug = req.params.slug
ProductPrice.find({ productId: slug}).exec((err, data) => {
if (err){
return res.status(400).json({
error: errorHandler(err)
})
}
res.json(data)
})
I need to get the prev sold price into the same level as history.value
ie:
[{
productId: "c69b7701-c33f-4801-99f3-080450f2b6c7",
createdAt: "2021-12-04T17:33:34.221Z",
history: [{
value: 304,
storePrice: 50,
date: 1638639214000,
prevSold: 303
}, ... 100+ more records]
_id: "61aba66d9085f0044f96a700"
}, ... 100+ more records]
So far I’ve tried the following aggregate call but it’s just returning an empty array. Can anyone point me in the right direction please?
ProductPrice.aggregate([
{$match: { productId: slug }},
{$unwind: "$history.prevSold"},
{$addFields: {
"prevSold.value": "$price",
}},
{$replaceRoot: {
newRoot: "$prevSold"
}}
Thanks,
How to add tooltip to all the dynamically loaded column in material-table
so I am using React material Table in like 70 different components, so I’ve went and made my custom component that contains the material-table so the shared props are in one place and the different ones are passed as props through my customMaterialTable
component
in my different components where I’m using the customMaterialTable
comp. the columns prop look like this
columns={[{
title: 'Internal CODE',
field: 'mat_code',
render: (rowData) => (
<Tooltip title={'Internal CODE'}>
<p>{rowData.mat_code}</p>
</Tooltip>
),
},
{
title: 'External CODE',
field: 'external_mat_code',
editable: 'never',
},
{
title: 'ENGLISH DESCRIPTION',
field: 'descr_en',
}]}
and in my customMaterialComponent I’m passing the props to the original Mateiral-Table like this
columns={columns.map((column) => {
return {
...column,
cellStyle: {
backgroundColor:
column?.editable === 'never'
? 'rgba(235, 235, 228, 0.54)'
: 'inherit',
},
};
})}
and it is working great
but what I want to do is give all the columns a toolTip like in the first one up there
render: (rowData) => (
<Tooltip title={'Internal CODE'}>
<p>{rowData.mat_code}</p>
</Tooltip>
),
the problem is if I do it that way, it means I have to do it like 300 times or so in 300 different places or more, I have access to the text that will be in the tooltip title, but I’m not sure how to render the return method:
return {
...column,
cellStyle: {
backgroundColor:
column?.editable === 'never'
? 'rgba(235, 235, 228, 0.54)'
: 'inherit',
},
};
}
inside of it
when I console log each column all I found is something like this:
{
"title": "External CODE",
"field": "external_mat_code",
"editable": "never"
}
I’m sorry the question is a bit long and please don’t downvote it I have been blocked before and I need to be part of this community
if anyone have suggestions on how to do it please share with me
I think it’s more react related than Material-table
MySQL Can not open connection after call connection.end() => Error: Pool is closed
config.js
const mysql = require('mysql2');
const config = {
host: 'localhost',
port: '3306',
user: 'root',
password: 'root',
database: 'krometal',
charset: "utf8mb4_bin",
multipleStatements: true
};
const connection = mysql.createPool(config);
connection.getConnection(function (err, connection) {
//connecting to database
if (err) {
logger.log('error', err);
console.log("MYSQL CONNECT ERROR: " + err);
} else {
logger.log('info', "MYSQL CONNECTED SUCCESSFULLY.");
console.log("MYSQL CONNECTED SUCCESSFULLY.");
}
});
module.exports = {
connection
}
login.js
const loginUser = async (req, callback) => {
connection.query(sql, async function (err, rows) => {
// logic
callback(result, 401, connection);
})
}
route.js
users.post('/users/login', async (req, res) => {
await loginUser(req, async (response, code, connection) => {
await connection.end();
res.status(code).send(response);
});
});
The problem is the first time I try login worked fine, but if I try the same login API again throw the error Error: Pool is closed.
Should I use the
connection.end()
method every time I open connection or mysql2 automatically end connection?