so I have an unordered list of buttons. its a relatively long list, and are sorted via some of these:
display:flex; flex-flow:row wrap; justify-content:space-between;
is there any way to make all of these buttons sort themselves alphabetically via javascript and keep its original look (not making it look like a list)?
Category: javascript
Category Added in a WPeMatico Campaign
I tried to handle an Axios error. It doesn’t work, how to handle it correctly?
I’m making a Discord bot, now I’m working at commands that interact with Geometry Dash API. I’m using axios to fetch the level info, and when I type the existing ID, I get the correct and working result. But if I’ll type the incorrect ID, I get a -1 error. I tried to handle this error, but nothing works. What should I do?
const axios = require("axios");
exports.run = (client, message, args) => {
const id = args[0];
axios.get(`https://gdbrowser.com/api/level/${id}`).then((response) => {
try {
const { data } = response;
const { name, id, description, author, difficulty, downloads, length, stars, orbs, diamonds, featured, epic, gameVersion, version, coins, verifiedCoins, starsRequested, ldm, objects } = data;
message.channel.send(`Name: ${name}nID: ${id}nDesc: ${description}nAuthor: ${author}nDifficulty: ${difficulty}nDownloads: ${downloads}nLength: ${length}nStars: ${stars}nOrbs: ${orbs}nDiamonds: ${diamonds}nFeatured: ${featured}nEpic: ${epic}nGame Ver: ${gameVersion}nVersion: ${version}nCoins: ${coins}nVerified Coins: ${verifiedCoins}nStarsReq: ${starsRequested}nLDM: ${ldm}nObjects: ${objects}`)
} catch (e) {
if(data === -1) {
return;
}
}
})
}
replace text in HTML [duplicate]
I have a mustache-express template which gets information from the database, I have this in my HTML code
<div class="col-12 col-sm-12 info-food" id="Availabile">
Availabile: {{Availability}}
</div>
The {{Availability}} gets replaced by its value in the database, which is true or false. How can I replace it so it shows on the page as “Yes” instead of “true” and “No” instead of “False”?
Google Sheet App Script: Match 1 values from one sheet to another sheet and then if condition met set background
I’m new to app script and still learning how to do thing. Here’s what I want to do: I have 2 sheets, in the 1st are just the names (‘List’) in columns based on each person language, the 2nd one is schedule (‘Roster’). I want to change in green the cell with person name when person is on schedule.
Any help or idea is very appreciated. Thank you in advance.
Here’s what I tried so far to do:
function addShiftColor() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var actSheet = ss.getSheetByName('List');
var rosSheet = ss.getSheetByName('Roster');
var lastCol = actSheet.getLastColumn() +1;
var lastRow = actSheet.getLastRow() +1;
var end = rosSheet.getLastRow();
for (var column = 1; column < lastCol; column++) {
for (var row = 1; row < lastRow; row++) {
var cellget = actSheet.getRange(row, column).getValue();
var cellset = actSheet.getRange(row, column);
for(i=1, j=5; i <= end, j <= end; i++,j++){
var cell1 = rosSheet.getRange(i, 1).getValue();
var cell2 = rosSheet.getRange(j, 253).getValue();
if(cell1 === cellget && cell2 === "08 -- 17"){
cellset.setBackground("green");
}
}
}
}
}
Thank you!
Cannot GET /about. Tenho um problema com express, para servir minha página [closed]
Olá desde já desejo que tudo te vá bem.
Tenho um App desenvolvido em VueJS e gostaria de servilo junto a minha API, ou seja, usar o servidor express para servir a pagina e os dados da API que serão acessados pela página.
Isso não é difícil pois ja serve tudo isso de forma eficieante, porém, quando tento acessar rotas filhas como ele me da esse erro “Cannot GET /about”
veja que quando acesso “http://localhost:3000” tudo corre bem, até posso navegar pelo app clicando nos links.
O problema é, quando faço um refresh na página ou tento acesar diretamente um link como: “http://localhost:3000/about” recebo isso GET http://localhost:3000/about 404 (Not Found).
Aqui em baixo ta o codigo que fornece o site outras rotas estão em arquivos separados e funcionan normalmente, por favor tentem me ajudar, não derrubem minha pergunta, pois, preciso resolver isso, desde já agradeço.
const express = require('express');
const app = express();
const port = 3000
const path = require('path');
//**************************/
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: false }));
//const bodyParser = require('body-parser')
//app.use(bodyParser.urlencoded({ extended: false }))
//app.use(bodyParser.json())
//**************************/
const consign = require('consign')
const db = require('./config/db.js');
const { whereNotExists } = require('./config/db.js');
app.db = db
// Serve the index.html for all the other requests so that the
// router in the JavaScript application can render the necessary components
app.use(express.static('public'))
consign()
.include('./config/passport.js')
.then('./config/middleware.js')
.then('./api')
.then('./config/routes.js')
.then('./routes')
.into(app)
//**************************** */
//**************************** */
app.listen(port, () => {
console.log(` servindo na porta ${port}...
n Seja bem vindo! `)
})
TypeScript: class property optional but not undefined
Is there any way that you can have a property on a Class that is optional, but won’t be undefined?
Note in the example below, the Class constructor takes a type of itself (that’s intentional)
class Test {
foo: number;
bar: string;
baz?: string;
constructor(test: Test) {
this.foo = test.foo;
this.bar = test.bar
this.baz = test.baz || "Default";
}
}
const first = new Test({foo: 1, bar: "Bob"});
const str = "Some Default String about Bob";
str.replace(first.baz, "New Value");
// Type 'undefined' is not assignable to type 'string | RegExp'.(
I know I can use the ! operator, but would prefer not to
str.replace(first.baz!, "New Value");
Seems maybe this question addresses it the answer — “class properties can’t rely on default values”
MySql2 query function scope not updating variable outside of the function
var names = [];
db.query(`SELECT * FROM department`, (err, rows) => {
if (err) {
console.log(err);
return;
}
names = rows.map(x => x.name);
})
console.log(names);
Hi guys, been messing with this code all day but can’t for the life of me figure out why my variable “names” will always print an empty array, rather than be populated with what occurs during this query. I defined it outside of the query scope, so shouldn’t that mean that the value I populate it with inside the scope should persist afterwards?
How can I fix this error, I guess Eslint was supposed to be installed automatically after running npm install –legacy–peer-deps [closed]
Failed to compile.
./src/index.js
Require stack:
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslint-plugin-flowtypedistutilitiesgetBuiltinRule.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslint-plugin-flowtypedistrulesnoUnusedExpressions.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslint-plugin-flowtypedistindex.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslintlibconfigplugins.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslintlibconfig.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslintlibcli-engine.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslintlibapi.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleseslint-loaderindex.js
- C:UsershpDesktopSchoolRun_Frontendnode_modulesloader-runnerlibloadLoader.js
- C:UsershpDesktopSchoolRun_Frontendnode_modulesloader-runnerlibLoaderRunner.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleswebpacklibNormalModule.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleswebpacklibNormalModuleFactory.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleswebpacklibCompiler.js
- C:UsershpDesktopSchoolRun_Frontendnode_moduleswebpacklibwebpack.js
- C:UsershpDesktopSchoolRun_Frontendnode_modulesreact-scriptsscriptsstart.js
Referenced from:
unable to get values for react js in node
I want to send values from react to node. I am using fetch but I am not getting. Here’s the code:
React Code:
const values = {email,pass}
const data = {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(values),
}
fetch('http://localhost:8000/', data)
.then(res => res.json)
.then(data => console.log(data))
Node Code:
const express = require(“express”)
const cors = require(‘cors’)
const app = express()
app.use(
cors({
origin: ‘*’
})
)
app.listen(8000, ‘localhost’)
app.post(‘/’ , ( req, res ) => {
console.log(req.body)
const data = JSON.stringify(req.body)
console.log(data)
} )
How to reset all other nested data inside parent onclick Alpine.js
I have multiple groups and multiple choices inside each group. When I click on a choice inside a group the groupcount should always + 1 and the clicked choicecount should be set to 1 while the other choicecount‘s inside the group should be reset to 0.
I have tried using $dispatch to reset all choicecount‘s inside the group to 0 before setting choicecount = 1 and groupcount++, but $dispatch doesn’t seem to trigger the other nested choicecount‘s inside the group.
For example, in the snippet below (Group 1):
Only one of G1 Option 1, G1 Option 2, G1 Option 3 should be allowed to equal 1 at a time.
If G1 Option 2 = 1 then G1 Option 1 and G1 Option 3 should = 0. The groupcount‘s are working fine.
Note: This is stripped down, radio buttons aren’t suitable for the feature I’m creating and I’m not using x-for because these groups and choices will be generated from a PHP loop. The number of groups and choices will vary.
<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<!-- GROUP 1 -->
<div x-data="{ groupcount: 0 }">
<label>Group 1 Count</label>
<input x-model="groupcount" type="text">
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G1 Option 1
</button>
</div>
</div>
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G1 Option 2
</button>
</div>
</div>
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G1 Option 3
</button>
</div>
</div>
</div>
<hr>
<!-- GROUP 2 -->
<div x-data="{ groupcount: 0 }">
<label>Group 2 Count</label>
<input x-model="groupcount" type="text">
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G2 Option 1
</button>
</div>
</div>
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G2 Option 2
</button>
</div>
</div>
</div>
<hr>
<!-- GROUP 3 -->
<div x-data="{ groupcount: 0 }">
<label>Group 3 Count</label>
<input x-model="groupcount" type="text">
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G3 Option 1
</button>
</div>
</div>
<div x-data="{ choicecount: 0 }">
<div x-on:resetAllCountsInGroup="choicecount=0">
<input x-model="choicecount" type="text">
<button type="button" x-on:click="$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++">
G3 Option 2
</button>
</div>
</div>
</div>
Why does react/javascript recreates a function instance every time we call it?
For example, onChange function:
const onChange = (e) => {
doSomething(e.target.value)
}
gets recreated on every change. Why is that, why can not the function keep the original reference?
How can I remove any specific installed node package?
In the process of developing a single page application I installed some npm package like
npm install react-currency-format --save
also
npm install react-slick --save
But I want to remove these items. Without any effect on rest of the code.
How can I do it?
how to create a file in memory from a string in NodeJS
I’d like to create a text file in memory with NodeJS, then a read stream from this file. Currently this is how I would handle this operation.
fs.writeFileSync("report.txt", 'Some Information');
const readStream = fs.createReadStream("report.txt")
// then upload file (readStream) to third party service
This requires me to save the file to disk. I want to find a way to create the Read Stream representing a Text File from a string without having to create and save the file to disk first.
use variable outside async function javascript [duplicate]
i’m trying to get the number of table line using javascript. i’m using php api with javascript.
from the php side evry thing is good and i get the lines number with the javascript function below. the problem that’s i want to use this variable outside this function .
note : inside function is working
const readNumberListe = async () => {
const data = await fetch("action.php?readNumberListe=1", {
method: "GET",
});
const response = await data.json();// the response is 5 for exepmle
var number = response.number_parent ;
console.log(number) ; // i get 5 in the console
};
readNumberListe();
// but i want to use or print 'number' here
react-admin error: ‘Cannot read properties of undifined (reading ‘id’)’
In react-admin library, when I try to post an object via http-request with the schema in the backend (id, firstname, lastname, email) with the id is autogenerated, It shows the error message : ‘Cannot read properties of undifined (reading ‘id’)”
this is the code of Create component:
const TeacherCreate = (props) => {
return (
<Create title="Teachers form" {...props}>
<SimpleForm validate={validateUserCreation}>
<TextInput source="firstname" />
<TextInput source="lastname"/>
<TextInput source="email" />
</SimpleForm>
</Create>
)
}
export default TeacherCreate
How to solve it?

