For example:
X.addEventListener('click', function(){
Y.addEventListener('click', function(){
var z = 100;
});
console.log(z);
});
When I run the code, it’s saying ‘z is not defined’.
How do I get that local variable? Any suggestions?
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
For example:
X.addEventListener('click', function(){
Y.addEventListener('click', function(){
var z = 100;
});
console.log(z);
});
When I run the code, it’s saying ‘z is not defined’.
How do I get that local variable? Any suggestions?
I’m trying to map over this Object, which i realise you can’t do as it’s an object. But I’m not sure how to turn this object into array. The groupedUserVotes data is this
{
'621c0c5d1d0359d2cf92a16f': { votes: [ [Object], [Object], [Object], [Object] ] },
'62a7d90d08e1756a5eac83c1': { votes: [ [Object], [Object], [Object], [Object] ] },
'607e33d3a5059e001920db69': { votes: [ [Object], [Object] ] },
'607375e2b22d4c89d7d8df85': { votes: [ [Object], [Object], [Object] ] },
'61302a38f4abe40019acc544': { votes: [ [Object] ] },
'60dba2c667d10b0019285c56': { votes: [ [Object] ] },
'619208365cbf5b21a8435eb6': { votes: [ [Object] ] }
}
This is my code snippet. But basically the Object key, is the User id. I want to map over each of the users, search the user ID from the Object key, and then attach the nested user onto the object itself.
Can someone show me the correct way to do this please? Thanks alot
const withUserInfo = groupedUserVotes.map(async (userVotes) => {
const ids = Object.keys(userVotes)
const user = await UserModel.findOne({ id: ids[0] })
console.log(user, 'user')
return {
votes: userVotes,
user: user
}
})
i need to get anything that can be unique and related to the user’s device. I have used this method to get the client’s IP
$worker_ip = $request->IP();
it works well, but if many users share the same WIFI, it returns the same number. so I need to know if anything can be unique I can fetch to identify the client’s device
I am trying to interface with WebAssembly and am getting a weird error. Firefox DevTools shows it as follows:
Uncaught (in promise) TypeError: can't convert 50057 to BigInt
The code that runs right before this error occurs:
static read_int(descriptor: number): number {
console.log("read_int")
if (descriptor < 0) {
return -1;
}
let value = Wasm.readStdValue(descriptor);
if (typeof value === 'number') {
if (Number.isInteger(value)) {
return value;
}
return Math.floor(value);
}
if (typeof value === 'boolean') {
return value ? 1 : 0;
}
if (typeof value === 'string') {
return parseInt(value);
}
return -1;
}
The WebAssembly files being used here were originally being used in a system interfacing with Swift and a library called WasmInterpreter, so the descriptor is just a number which is a key in a map. The number being read at the let value = Wasm.readStdValue(descriptor); line is 50057 and it is a number. It doesn’t seem right to me that it would fail to convert such a small number to a larger number type but idk.
Thanks in advance!
I have a form in rails 4 app that has a total of 5 buttons. The first row has two buttons where only one option can be selected at a time. The 2nd row is the same as first row with different options where only one can be selected at a time. The third row has one button and can be selected or deselected regardless of the other buttons.
Question: I would normally use radial buttons and style as actual buttons, but I can’t use that option. How in rails would I accomplish selecting the button options to be submitted? I can use Javascript like here to toggle the buttons to show selected, but I need to be able to select them so the form can recognize them and be submitted. I can’t use button_to as it creates a form and I would have a form within a form.
Here is my current frontend code:
<div class="row-1">
<%= button_tag 'option 1', type: 'button', name: :host_quote, id: :reservation_host_quote_false, class: :something_here %>
<span class="or"> - OR - </span>
<%= button_tag 'option 2', type: 'button', name: :host_quote, id: :reservation_host_quote_true, class: :something_here %>
</div>
<div class="row-2">
<%= button_tag 'option 3', type: 'button', name: :insurance_only, id: :reservation_insurance_only_false, class: :something_here %>
<span class="or"> - OR - </span>
<%= button_tag 'option 4', type: 'button', name: :insurance_only, id: :reservation_insurance_only_true, class: :something_here %>
</div>
<div class="row-3">
<%= button_tag 'option 5', type: 'button', name: :stationary_only, id: :stationary_insurance_only, class: :something_here %>
</div>
How to send a chat message from the FB desktop version (without FB API) in javascript (via tempermonkey and preferably without JQuery)?
The matter seems simple. I can open a chat window, but typing messages is different. Sending the event of pressing the enter button correctly sends the message. But I have no idea how to enter it correctly. There is no input, there is a div, but editing it does not do anything by itself, because you send something else anyway. Attempting to send the letter by letter keys also does not work.
Facebook is written in React that I don’t know, so maybe there’s another way. How to fill in the message field so that exactly this content goes after pressing the enter key, or send it in a different way (no API).
const obj = [
{
id:1,
info : [
{
status:"open",
value:20
},
{
status:"closed",
value:1
},
{
status:"open",
value:100
}
]
},
{
id:2,
info : [
{
status:"open",
value:40
},
{
status:"closed",
value:1
},
{
status:"open",
value:150
},
{
status:"open",
value:250
},
{
status:"closed",
value:10
}
]
}
]
What I want to do is filter by the value of the last one whose status is open.
For example, if I want to find values greater than 200, it should only return me with an id of 2. Because the last status value of the object whose id is 2 is 250.
I tried something like this, but the status is filtering by all that are open.
const filtered = obj.filter(o => {
return o.info.find(value => {
if (value.status == "open") {
if(value.value > 200){
return true;
}
};
});
});
console.log(filtered)
I’m trying to make a browser in React and I can’t find any information on the web, can you guide me please! Thank you.-
I would like to read the contents of my .env file into a variable other than process.env in Node.js. I am currently using the dotenv library but I am willing to use something else if anyone has alternatives to offer.
In my particular .env, username and password pairs will be stored on the server-side for authentication. I would like to read the file contents without overwriting process.env because there are other parts of my application that depend on values not being overwritten. I know that override: false is set by default in dotenv, so the values won’t be overwritten, but I still need to access the new values. An example is USERNAME being set in one file to ‘xterm‘ for a third-party terminal login, but if a user’s username in the dotenv file is ‘USERNAME‘ then I need to authenticate their password against the value instead of against ‘xterm‘, if that makes sense.
If I could aggregate the data from my .env file to something like process.env.specialValues and access the information via that nested property, that would be perfect.
Example of desired end behavior for clarity: process.env.specialValues.USERNAME
I am trying to build a folder tree component where initially the component will only render the names of items at the first layer (item1, item2, item3), then when an specific item is clicked, it would show me everything listed on the next layer for that item(i.e. click on item1 would show item1.1 and item1.2, click on item1.1 will show item1.1.1). This should be done in a loop until it reaches the final layer with the just the attributes (attr1, attr2, attr3).
Note: I have simplified the item names for demo purposes, but in reality they don’t follow a specific pattern/naming system.
import React, {useState, useEffect} from 'react';
const Testing = () => {
const [expand, setExpand] = useState(false);
const data = {
"item1": {
"item1.1": {
"item1.1.1": {
"item1.1.1.1": {
"attr1": [],
"attr2": "",
"attr3": []
}
}
},
"item1.2": {
"item1.2.1": {
"item1.2.1.1": {
"attr1": [],
"attr2": "",
"attr3": []
}
}
}
},
"item2": {
"item2.1": {
"item2.1.1": {
"item2.1.1.1": {
"attr1": [],
"attr2": "",
"attr3": []
}
},
"item2.1.2": {
"item2.1.2.1": {
"attr1": [],
"attr2": "",
"attr3": []
},
"item2.1.2.2": {
"attr1": [],
"attr2": "",
"attr3": []
}
}
}
},
"item3": {
"item3.1": {
"item3.1.1": {
"item3.1.1.1": {
"attr1": [],
"attr2": "",
"attr3": []
}
},
"item3.1.2": {
"attr1": [],
"attr2": "",
"attr3": []
}
}
}
}
function parse(data) {
if (typeof data === 'object') {
return (
<li>
<ul>
{Object.entries(data).map(([key, value]) => (
<>
<li>
{key}: {typeof value === 'string' ? value : ''}
</li>
{parse(value)}
</>
))}
</ul>
</li>
);
}
if (typeof data === 'object') return (<li>{data}</li>);
return null;
}
return (
<div>
<div className="App">
{Object.entries(data).map(([key, value]) => {
return (
<ul>
<span onClick={() => setExpand(!expand)}>{key}</span>
<br />
<div style={{ display: expand ? "block" : "none", paddingLeft: 15 }}>
{parse(value)}
</div>
</ul>
);
})}
</div>
</div>
)
}
export default Testing;
Here a picture of the output I’m getting right now iwth the code above: current output; it shows item1, item2, item3 in a list; but when I click on any of them, it will just render everything else, I’m trying to find a way so that it behaves similar to a file directory tree as shown in the demo here: https://codesandbox.io/s/folder-structuring-t6oj4
i have been struggling with some logic about using multiple page objects in one method, i couldnt find any idea to use like that logic, for example;
I have three method in my page object called usersTable;
settings(options: string) {
return cy
.get(
"[style='position: fixed; z-index: 1300; inset: 0px;'] > .MuiPaper-root > .MuiList-root",
)
.contains(options);
}
menuButton(userId: string) {
return cy.get(`.user_${userId}>td>button`);
}
userRow(userId?: string) {
const userrow = ".MuiTableBody-root>tr";
if (userId === undefined) {
return cy.get(userrow);
}
return cy.get(userrow).get(`.user_${userId}`);
}
im using userRow method in this test like that;
usersTable.userRow(userId).should("not.exist");
And for exaple im using my userMenu and settings method in this test;
usersTable.menuButton(userId).click();
usersTable.settings("Impersonate").click();
Let’s come to the idea that I want to do but I can’t find the way to do it;
usersTable.userRow(userId).settings.menuButton.click()
usersTable.userRow(userId).settings.impersonate.click()
Is there a any way to use like that ? All ideas are accepted
I have had a problem for a long time that I do not understand very well why it happens, I tried everything else, however I always find it in one way or another, let me explain.
I am developing a split App, Front End with React JS and ASP .net in the BackEnd, so far so good.
I designed a page in which what I am looking for is, Before the components of my page are displayed, I want to make 2 calls to my back end to bring me 2 different resources in JSON format, both resources of Type GET and I want this to be displayed information in my components. the information I ask for is nothing special, just simple JSON text strings like username, identifier, numbers etc.
To make the call to my backend I use AXIOS, and in this case I use PROMISE JavaScript in React.
To execute it when mounting my component, I make use of React’s UseEffect, in this way I execute the 2 calls.
I’m not using Redux, I’m just using SessionStorage and LocalStorage, the logic in my head is as follows:
1.-if the sessionStorage called Client does not exist, I will execute the function GetCliente
2.- The GetCliente function makes calls to the API with AXIOS and brings me the information of the client
3.- When I bring it, I convert the JSON into a Javascript object with JSON.stringify and in this way I create the Client sessionStorage.
4.- When the Client sessionStorage is created, it will be mounted on a UseState called client whose initial state is null.
5.- When the client useState is filled, it will be painted on the page, to paint it I use this notation client?.username, to access its values ββββand if it doesn’t come, it won’t mark me an error.
6.- When the sessionStorage called Client is created, if the user decides to “Refresh” the page, he will no longer have to make the API call because he is already registered on the page, so he will only have to mount the information of the sessionStorage in my UseState, this way I don’t overload my server with requests.
Now here comes the tricky…
My logic works, I already have it implemented and it has worked, however the following errors start appearing.
1.- Sometimes, when I enter the page for the first time, of the 2 resources that I request, 1 does not arrive, I have 2 functions, getCliente() this brings me data from a client and getWarehouse() this brings me data from a warehouse.
sometimes the information from getCustomer does not arrive but the information from getWarehouse does, and on other occasions the information from getWarehouse does not arrive but the information from getCustomer does.
I have a button called close session that cleans the sessionStorage, when I try to enter the page again it does not bring me any of the 2 resources!
I went to the Network tab of my browser, and sometimes I see that my 2 resources are executed 2 times, according to what I know is by UseEffect, that it executes my function 2 times, however in the 2 occasions the request of my 2 resources are in status 304
sometimes when I go to the network tab, I see that one of my resources is in status 304, and then that same resource is executed again by the UseEffect and the status appears in 200, a sign that it was achieved but for some reason , it doesn’t load into my SessionStorage! It appears to me that the client SessionStorage was created but it is empty!
I don’t know what to do anymore, I have greatly simplified this logic at this point, however sometimes it works very well and other times it doesn’t!
Now yes, I attach all the code, I don’t really know what I’m doing wrong, even my backend doesn’t do other things like verify token or something like that, it just asks for the resource and sends it but I don’t understand why it keeps happening…
First Server code this is my endpoint that brings data from my store…
[HttpGet("almacen/{dbhandle:int}/{idcaja:int}")]
public ActionResult<string> getAlmacen(int dbhandle, int idcaja) {
string [] data = ConexionDB.Instance.Obtener_almacen_caja(dbhandle, idcaja);
var dataconvert = JsonConvert.SerializeObject(data);
return Ok(dataconvert);
}
this is my endpoint that brings my user data
[HttpGet("cliente/{dbhandle:int}")]
public ActionResult<String> getcliente(int dbhandle) {
string [] data = ConexionDB.Instance.Obtener_cliente(dbhandle);
var dataconvert = JsonConvert.SerializeObject(data);
return Ok(dataconvert);
}
both endpoints work, both with PostMan I have tested it
Now code in React…
const VentasMostrador = () => {
//varibles de estado useState
const [cliente, setcliente] = useState(null);
const [almacen, setalmacen] = useState(null);
const [cajero, setcajero] = useState(null);
const [productos, setproductos] = useState([]);
const [cambio, setcambio] = useState(false);
const [total, setTotal] = useState(0);
const [show, setShow] = useState(false);
const [productoSeleccionado, setProductoSeleccionado] = useState(null);
const [seriesylotes, setseriesylotes] = useState(null);
if(!sessionStorage.getItem("ID_CAJA")){
window.location = "/PaginaPrincipal";
}
const getCliente = async () => {
let user = JSON.parse(localStorage.getItem("datauser"));
const promise = await axios.get("https://localhost:5001/api/ventasmostrador/cliente/"+user.DbHandle);
if(promise){
let data = promise.data;
let infodata = { id: data[0], nombre: data[1], codigo: data[2] };
sessionStorage.setItem("GET_CLIENTE", JSON.stringify(infodata));
setcliente(JSON.parse(sessionStorage.getItem("GET_CLIENTE")));
} else {
console.log("no se pudo cargar los datos de almacen...");
}
};
const getAlmacen = async () => {
let user = JSON.parse(localStorage.getItem("datauser"));
let caja = JSON.parse(sessionStorage.getItem("ID_CAJA"));
const promise = await axios.get("https://localhost:5001/api/ventasmostrador/almacen/"+user.DbHandle+"/"+caja);
if(promise){
let data = promise.data;
let infodata = {
id: data[0],
caja: data[1],
idalmacen: data[2],
nombrealmacen: data[3],
};
sessionStorage.setItem("GET_ALMACEN", JSON.stringify(infodata));
setalmacen(JSON.parse(sessionStorage.getItem("GET_ALMACEN")));
} else {
console.log("no se pudo cargar los datos de almacen...");
}
};
now to execute these 2 functions I make use of UseEffect.
useEffect(() => {
let datauser = JSON.parse(localStorage.getItem("datauser"));
setcajero(datauser.Nombrecajero);
}, [])
useEffect(() => {
if(!sessionStorage.getItem("GET_CLIENTE")){
getCliente();
} else {
setcliente(JSON.parse(sessionStorage.getItem("GET_CLIENTE")));
}
console.log("cuanto se ejecuta x1...");
}, []);
useEffect(() => {
if(!sessionStorage.getItem("GET_ALMACEN")){
getAlmacen();
console.log("cuanto se ejecuta x2...");
} else {
setalmacen(JSON.parse(sessionStorage.getItem("GET_ALMACEN")));
}
}, [])
Evidence of all my explanation…
This image is when I entered the application for the first time, here it executed perfectly and the data came out.
here the information is painted in my component, all good and in the tab where sessionStorage is located both objects are created and filled.
Here comes the problem, when I press the button, logout, and I leave this page, and try to enter again so that everything can be reloaded, it stops working or 1 resource, or another resource or BOTH π
If I check the network tab, they appear to me that they arrived!
So I don’t know what to do, I know the explanation is too long and tedious but this frustrates me, I don’t know if the controller, useEffect, my javascript function or the promise is wrong.
If anyone reads this please help π
I have a page (asp.net 6 mvc web app with identity) with a list of users and I want to have a search bar to filter those users by their emails but I have no idea how to do it
Admin controller
public class AdminController : Controller
{
private readonly ILogger<AdminController> _logger;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AdminController(ILogger<AdminController> logger, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_logger = logger;
_roleManager = roleManager;
_userManager = userManager;
}
public async Task<IActionResult> ListOfUsersAndRoles()
{
var users = await _userManager.Users.ToListAsync();
var userRolesViewModel = new List<UserRolesViewModel>();
foreach (ApplicationUser user in users)
{
var thisViewModel = new UserRolesViewModel();
thisViewModel.UserId = user.Id;
thisViewModel.Email = user.Email;
thisViewModel.Name = user.UserName;
thisViewModel.Roles = await GetUserRoles(user);
userRolesViewModel.Add(thisViewModel);
}
return View(userRolesViewModel);
}
ListOfUsersAndRoles view
<h1>List of users and roles</h1>
<table class="table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.Email</td>
<td>@string.Join(" , ", user.Roles.ToList())</td>
<td>
<a class="btn btn-primary" asp-controller="Admin" asp-action="ModifyRole" asp-route-userId="@user.UserId">Modify role</a>
</td>
</tr>
}
</tbody>
</table>
This must be so easy to code but as a beginner I’m lost, the tutorials that I’m watching are either for older versions of asp.net or they don’t use mvc, EF, identity and so on so instead of learning, I’m actually getting more and more confused. From what I’m seeing, I think javascript is necessary and I have no knowledge in javascript
Any videos, websites or advices are welcome
const obj = [
{
"id":"1",
"history": [
{
"Type": "Scan",
"DamageValue": "5"
},
{
"Type": "another",
"DamageValue": "999"
},
{
"Type": "Scan",
"DamageValue": "3"
},
]
},
{
"id":"2",
"history": [
{
"Type": "Scan",
"DamageValue": "1"
},
{
"Type": "Scan",
"DamageValue": "7"
},
{
"Type": "another",
"DamageValue": "333"
},
]
}
]
I want to filter the last object whose type value is scan according to any 2 damageValue values coming from outside.
For example, When 4 and 8 are entered from outside, objects within this range should return. like,
]
{
"id":"2",
"history": [
{
"Type": "Scan",
"DamageValue": "1"
},
{
"Type": "Scan",
"DamageValue": "7"
},
{
"Type": "another",
"DamageValue": "333"
},
]
}
]
The object with an id of 1 should not provide the filter I wrote in the example. Because the damageValue of the last scan value found in history in the object whose id is 1 is 3.
edited
I am trying to practice with rest parameters, and I found that when using .join() on my rest parameter, it will join the elements but it wont use my seperator. Is there a reason for that? My code below.
function print(name, age, ...likes){
const string = likes.join(", and ")
console.log("My name is " + name + " and I'm " + age + " and I like " + string)
}
print("Joe", 22, ["animals", "cake", "coding"])