Just out of curiosity, how would you access the global window object inside a function with this signature:
function bla(window){
// How to access the global 'window' object here? Because 'window' is now local.
}
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
Just out of curiosity, how would you access the global window object inside a function with this signature:
function bla(window){
// How to access the global 'window' object here? Because 'window' is now local.
}
Component 1
<script>
import { data } from "../data";
export default {
name: "HelloWorld",
data() {
return {
items: data,
};
},
};
</script>
**data.js**
export const data = [
{
id: 1,
val: "1",
kk: "mm",
status: "ok"
},
{
id: 2,
val: "2",
kk: "aa",
status: "ok"
},
{
id: 3,
val: "3",
kk: "dd",
status: "notok"
},
{
id: 4,
val: "4",
kk: "gg",
status: "medium"
},
{
id: 5,
val: "5",
kk: "gg",
status: "notok"
},
{
id: 6,
val: "6",
kk: "gg",
status: "ok"
},
{
id: 7,
val: "7",
kk: "gg",
status: "medium"
},
{
id: 8,
val: "7",
kk: "gg",
status: "notok"
},
{
id: 9,
val: "9",
kk: "gg",
status: "medium"
}
];
<template>
<div>
<b>Vuejs dynamic routing</b>
<div v-for="item in items" :key="item.id">
<input type="checkbox" />
<b>{{ item.id }}.</b>
<router-link :to="{ name: 'UserWithID', params: { id: item.id, item } }">
{{ item.val }}
</router-link>
</div>
</div>
</template>
Component 2
<script>
import { data } from ".././datatwo";
export default {
name: "HelloWorld",
data() {
return {
selects: data,
};
},
};
</script>
**datatwo.js**
export const data = [
{
id: 1,
val: "a",
kk: "mm",
status: "notok"
},
{
id: 2,
val: "b",
kk: "aa",
status: "ok"
},
{
id: 3,
val: "c",
kk: "dd",
status: "ok"
},
{
id: 4,
val: "d",
kk: "gg",
status: "medium"
},
{
id: 5,
val: "e",
kk: "gg",
status: "medium"
},
{
id: 6,
val: "f",
kk: "gg",
status: "ok"
},
{
id: 7,
val: "g",
kk: "gg",
status: "medium"
},
{
id: 8,
val: "h",
kk: "gg",
status: "notok"
},
{
id: 9,
val: "i",
kk: "gg",
status: "medium"
}
];
<template>
<div>
<b>Vuejs dynamic routing2</b>
<div v-for="select in selects" :key="select.id">
<input type="checkbox" />
<b>{{ select.id }}.</b>
<router-link
:to="{ name: 'UserWithIDTwo', params: { id: select.id, select } }"
>
{{ select.val }}
</router-link>
</div>
<br /><br /><br />
</div>
</template>
I have two components called component1, component2. Where in both components data is coming from individual .js called(data.js, datatwo.js)
So when user click on checkbox from componet1, I need to show the names which is in component2(datatwo.js) based on the status present in datatwo.js(component2)
for example like. in my case status is categorized into 3 types called. “ok”, “notok” “medium”. So when user click on checkbox from component1, i need to display name present in component2(dtatwo.js) and drawing lines like below. and when user uncheck checkbox it need to hide again.
code:- https://codesandbox.io/s/data-change-dynaic-t48f9?file=/src/datatwo.js
i’m a complete beginner in when it comes to jsdom and i just want to know how to simulate the user typing the string and hitting solve button this is what i got so far
unitTest.js
suite("UnitTests", () => {
beforeEach(function () {
return JSDOM.fromFile(path.join(__dirname, "../views/index.html"), {
resources: "usable",
runScripts: "dangerously",
}).then((resolve) => {
window = resolve.window;
document = resolve.window.document;
textArea = document.getElementById("text-input");
error = document.getElementById("error");
solveButton = document.getElementById("solve-button");
});
});
suite("solver solve method", function () {
test("Valid puzzle strings pass the solver", function () {
const invalidPuzzleString =
"1.5..2.84..63.12.7.2..5.....9..1....8.2.367473.7.2..9.47...8..1..16....926614.478";
textArea.textContent = invalidPuzzleString;
solveButton.dispatchEvent(
new window.MouseEvent("click", { bubbles: true })
);
console.log(textArea.textContent);
console.log(error.innerHTML);
assert.equal(
error.innerHTML,
'<code>{ "error": "Puzzle cannot be solved" }</code>'
);
});
```
I am trying to create a login form whereby the users data is fetched via a fetch request and is checked with the following javascript code:
fetch('./login.php', {
method: 'GET'
})
.then((res) => res.json())
.then(res => {
let user = []
for (let data of res){
user.push({
email: "'"+data.email+"'",
password : "'"+data.password+"'"
})
}
let button = document.querySelector('.btn btn-danger submit');
function login(){
let email = document.getElementById('useremail').value;
let password = document.getElementById('userpassword').value;
for(i=0; i < user.length; i++){
if(email == user[i].email && password == user[i].password){
window.location = "home.html";
}
}
}
button.onclick = login();
})
Whenever I check the console it shows the error in the title.
Is there something wrong with how I am trying to go about this?
Here is my HTML code for the form (using bootstrap):
<form action="" id="loginform">
<div class="mb-3">
<label for="useremail" class="form-label">Email:</label>
<input type="email" class="form-control" id="useremail" aria-describedby="Email" name="useremail" required>
</div>
<div class="mb-3">
<label for="userpassword" class="form-label">Password:</label>
<input type="password" class="form-control" id="userpassword" aria-describedby="Password" name="userpassword" required>
</div>
<button class="btn btn-danger submit" type="submit">Login</button>
<div class="row mt-3">
<a href="register.html" class="text-decoration-none text-decoration-underline text-dark fst-italic">Don't have an account? Register Here.</a>
</div>
</form>
I am trying to send data into mongodb database using postman. Everything seems fine but i am getting error.
My code looks like this. i have tried to follow MVC pattern. It is bit messy. Hope i can get solution. I have used express generator
This is app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
const {
createUserRoute,
usersRouter,
indexRouter
} = require('./routes');
// const createUserRoute = require('./routes/createuser-route');
require('./db_init');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// app.use('/', indexRouter);
// app.use('/users', usersRouter);
app.use('/adduser', createUserRoute);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
This is database initializer
const mongoose = require('mongoose');
const dbUrl = "mongodb://localhost:27017/payroll-system";
mongoose.connect(dbUrl, (err,success) => {
if(err){
console.log('Error connecting to database');
}
else{
console.log('Connected to database');
}
})
This is create user router
var express = require('express');
var router = express.Router();
// var UserModel = require('../models/user-model');
const {createUser} = require('../controller/createUser');
router.post('/', createUser);
// router.post('/', function (req, res, next) {
// const user = new UserModel(req.body);
// user.save((err, result) => {
// if (err) {
// res.json(err);
// }
// else {
// res.json(result);
// }
// })
// });
module.exports= router;
It handles every routes and exports them to app.js
module.exports.createUserRoute = require('./createuser-route');
module.exports.indexRoute = require('./index');
module.exports.usersRoute = require('./users');
This is usercreate controller
var express = require('express');
var router = express.Router();
var UserModel = require('../models/user-model');
function createUser(req,res,next){
const user = new UserModel(req.body);
user.save((err,result) => {
if(err){
res.json(err);
}
else{
res.json(result);
}
})
}
module.exports = {createUser};
Database Model looks like this
const mongoose = require('mongoose');
const employeeSchema = new mongoose.Schema({
name:{
type:String,
required:true
},
email:{
type:String,
required:true,
unique:true
},
// password:{
// type:String,
// required:true
// },
phone:{
type:Number,
required:true
},
address:{
type: String,
required: true
},
date_of_birth:{
type:Date,
// required:true
},
gross_salary:{
type:Number,
required:true
},
gender:{
type:String,
enum:['male','female','other']
},
position:{
type: String,
enum:['Board Member','Senior Developer', 'Junior Developer','Admin Officer','Project Manager','Intern','Staff']
},
bank:{
type: String,
required: true,
enum:['Agriculture Bank','Bank of Kathmandu','Citizens Bank','Everest Bank','Nepal Investment Bank','Nepal SBI Bank','Nepal Union Bank','Standard Chartered Bank']
},
account_number:{
type:Number,
required:true
},
account_holder_name:{
type:String,
required:true
},
status:{
type:String,
enum:['active','inactive']
},
shift:{
type:String,
enum:['Full Time','Part Time', 'Hour Basis']
},
marital_status:{
type:String,
enum:['Married','Unmarried']
}
});
const Employee = mongoose.model('Employee', employeeSchema);
module.exports = Employee;
How can i insert https:// codepen.io/marcbizal/pen/YXEmyQ menu effect in my wordpress theme ?
I am using a theme of Avada
On my flask app I want to create a feature so a user can query the database, have the browser display the results in a table and then download it in a csv.
Is the plan I have below secure? Would end users be able to manipulate the JSON?
My overall design plan to accomplish this is as follows in pseudocode:
(Python) pulls Query from database and puts results in JSON using JSONIFY
(Python) returns JSON to Javascript file
(Javascript) Displays the JSON in an HTML table
(Javascript) User clicks button and Javascript sends JSON to flask endpoint
(Python) Flask endpoint converts JSON into CSV
I want to create a website where you can paste your code and run it. It should debug like leetcode does. Could anyone tell what technical stack should I learn and which specific libraries would help??
I pick a file via DocumentPicker, get the URI, and pass it to a function which should open my Document (csv). But i get the Error ENSCOCOAERRORDOMAIN260.
Also i tried to see if there’s an file -nope. But i just selected it via DocumentPicker (i get Filename, size, etc via it)
That would be the function:
async readCSVsaveTOJson(uri){
var RNFS = require('react-native-fs');
//console.log(RNFS.TemporaryDirectoryPath);
realDoc = uri.replace('file:/', '');
console.log(realDoc);
var kacke = '';
var counter = 0;
for(var i in realDoc){
if(counter > 0){
kacke += realDoc[i];
}
counter++;
}
console.log('exists?');
console.log(RNFS.exists(kacke));
RNFS.readDir(kacke')
.then((result) => {
// stat the first file
console.log('result');
return Promise.all([RNFS.stat(result[0].path), result[0].path]);
})
.then((statResult) => {
if (statResult[1].isFile()) {
// if we have a file, read it
var content = RNFS.readFile(kacke);
console.log('--------------------------');
console.log(content);
return RNFS.readFile(statResult[1], 'utf8');
}
return 'no file';
})
.then((contents) => {
// log the file contents
console.log(contents);
})
.catch((err) => {
console.log('ERROR, theres is nothing');
console.log(err.message, err.code);
});
}
it throws console.log('ERROR, theres is nothing');.. buut i know there should be something.
Any recommandings?
Huge Thanks
I have an APIs of a CricClub website, in which they have all matches results and all the tournament schedules. Now I didn’t know how to listed that API data on my elementor website. If anyone know to how to deal with that types of APIs tell me.
I use the alpine.js to render a modal with a x-for loop who populate a select. Strange behavior, the x-for seems looping 2 times and I can’t understand why:
the code:
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('load', () => ({
indicateurs: [],
indicateurDictionnaireForm: {},
typeIndicateurs: {},
detectedTypeIndicateur: '',
loadIndicateur() {
$('#overlay').fadeIn();
fetch('<%= request.getContextPath() %>/mesures.load.action')
.then(response => response.json())
.then(data => {
this.indicateurs = data;
$('#overlay').fadeOut();
})
.catch(error => {
});
},
deleteIndicateur(id) {
$.ajax({
type: "DELETE",
url: "<%= request.getContextPath() %>/mesures.delete.action?indicateurDictionnaireId=" + id,
}).then(() => this.loadIndicateur());
},
postForm() {
return {
submitData() {
$.ajax({
type: "POST",
url: "<%= request.getContextPath() %>/mesures.save.action",
data: JSON.stringify(this.indicateurDictionnaireForm),
dataType: "JSON",
contentType: "application/json; charset=utf-8",
}).then(() => {
this.loadIndicateur();
this.resetForm();
$('#modalIndicateur').modal('hide');
})
},
}
},
editIndicateur(id) {
$.ajax({
type: "GET",
url: "<%= request.getContextPath() %>/mesures.load.type-indicateur.action"
}).then(data => {
this.typeIndicateurs = data;
}).then(
$.ajax({
type: "GET",
url: "<%= request.getContextPath() %>/mesures.edit.action?indicateurDictionnaireId=" + id,
}).then(data => {
this.indicateurDictionnaireForm = data;
this.detectedTypeIndicateur = data.typeIndicateur.code;
this.loadIndicateur();
$('#modalIndicateur').modal('show');
})
);
},
resetForm() {
this.indicateurDictionnaireForm = {};
}
}))
})
</script>
the modal code:
<div class="modal" tabindex="-1" role="dialog" id="modalIndicateur">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><s:text name="indicateur.ce.add"/></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="<%= request.getContextPath() %>/save.action"
method="POST"
class="w-64 mx-auto" x-data="postForm()" @submit.prevent="submitData">
<div class="form-group" style="padding-left: 15px; padding-bottom: 5px">
<div class="row">
<label class="control-label col-md-2" style="text-align: left"
for="libelle_fr">
<s:text name="indicateur.ce.libelle_fr"/></label>
<div class="col-md-8">
<input id="libelle_fr" type="text"
name="indicateurDictionnaireForm.libelleFr"
class="form-control input-sm"
x-model="indicateurDictionnaireForm.libelleFr">
</div>
</div>
<div class="row">
<label class="control-label col-md-2" style="text-align: left"
for="libelle_nl">
<s:text
name="indicateur.ce.libelle_nl"/></label>
<div class="col-md-8">
<input id="libelle_nl" type="text"
name="indicateurDictionnaireForm.libelleNl"
class="form-control input-sm"
x-model="indicateurDictionnaireForm.libelleNl">
</div>
</div>
<div class="row">
<label class="control-label col-md-2" style="text-align: left"
for="code">
<s:text name="indicateur.ce.code"/></label>
<div class="col-md-8">
<input id="code" type="text"
name="indicateurDictionnaireForm.typeIndicateurCode"
class="form-control input-sm"
x-model="indicateurDictionnaireForm.code">
</div>
</div>
<div class="row">
<label class="control-label col-md-2" style="text-align: left"
for="code">
<s:text name="indicateur.ce.code"/></label>
<div class="col-md-4">
<div class="flex flex-col w-full md:w-2/3">
<select x-model="indicateurDictionnaireForm.typeIndicateurCode"
class="form-control input-sm">
<template x-for="option in typeIndicateurs" x-effect="console.log(detectedTypeIndicateur)">
<option :key="option.code"
:value="option.code"
selected="option.code === detectedTypeIndicateur"
x-effect="console.log('code:', option.code, ' type: ', detectedTypeIndicateur)"
x-text="option.libellefr"></option>
</template>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"
@click="resetForm()">
<s:text name="common.button.quitter"/>
</button>
<button type="submit" class="btn btn-primary">
<s:text name="common.button.save"/>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
With the x-effect tag, I tried to log the value of the the detected item to be selected in the select tag and the value itself.
this is the console output when the modal is open:
// first loop
<empty string>
code: RESULTAT type: <empty string>
code: INCIDENCE type: <empty string>
code: REALISATION type: <empty string>
// second loop
REALISATION
code: RESULTAT type: REALISATION
code: INCIDENCE type: REALISATION
code: REALISATION type: REALISATION
In the first loop I see the value from my function editIndicateur() is empty so I assume, alpine.s tries to render the modal before the call back and then do a second loop.
Have you an idea why the modal is populate before the value is return by the function and also why it loops a second time?
Thanks for your help
Pretty new to coding, which is why this question might be easily answered, but after scanning the internet for 2 days now and still not having a real solution, i thought I’d just ask here.
So, as the title explains, I have an iframe inside a website I want to scrape with an id attribute (we’ll just call it iframeid) and somewhere inside this iframe I have a div container with a class attribute (we’ll call it divclass) that contains – besides other elements – multiple <a> tags. My goal is to get an array in which all the links from those <a> tags are listed, put to date I only achieved the following through researching and a bit of luck:
const elementHandle = await page.waitForSelector('iframe#iframeid');
const frame = await elementHandle.contentFrame();
await frame.waitForSelector('div[class=divclass] a');
var x = 2; //a var to determine which a tag I want
const oneA= await frame.$('div[class=entryLayer] a:nth-child(' + x + ')');
const link = await (await oneA.getProperty('href'))._remoteObject.value;
console.log(link);
What it does is it takes a variable and pulls the link of its according <a> tag, but I can’t figure out how to put it in a loop and besides that, the amount of <a> tags varies, which makes the loop for me to code even harder.
Wouldn’t it even be possible to leave out the loop completely? I found similar stackoverflow questions, but one for example only had one <a> tag which seems to change the code completely.
At the end I just want a working piece of code that I as a newbie can understand but is fairly compact at the same time.
Thanks for helping in advance!
I am trying to implement a asset sweep functionality. I want to be able to move transaction from a 100 addresses at a time to save both CPU and transaction fee.
I want to sign the transaction with Bitcore-lib and send to my Blockbook node.
I have a galaxy made of 3 planets and a spaceship and I want all of them to be clickable to load another page. I managed to do so with the 3 planets adding planet.userData = {URL: "my.html"}; but not with the spaceship, which is a GLTF loaded model.
This is how I loaded the spaceship:
const loader = new GLTFLoader();
loader.load('models/spaceship.glb', function(gltf) {
const spaceship = gltf.scene;
spaceship.scale.set(0.08, 0.08, 0.08);
spaceship.userData = {URL: "my.html"}; //Adding the URL here
objects.push(spaceship); //This is for raycasting
scene.add(spaceship);
}, undefined, function(error){
console.error(error);
});
And this is the function for the Mouse Down event:
function onDocumentMouseDown(){
mouse.x = (event.clientX/window.innerWidth)*2-1;
mouse.y = -(event.clientY/window.innerHeight)*2+1;
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(objects, true);
if ( intersects.length > 0 ) {
window.open(intersects[0].object.userData.URL); // <-- Doesn't work
}
}
When clicking on the spaceship the URL value is “undefined”. I’m sure there is another way to do so but I can’t find any solution. Thank you so much in advance to anyone helping!
I am working on an e commerce store , on the click of sign in , it pops up the google sign in , once i sign in with google . It redirects to local host instead of the wesbsite url . How do i fix it
I have a feeling it is cause of my
NEXTAUTH_URL = HTTP://LOCALHOST
below is the code
import { useSelector } from "react-redux";
import Header from "../components/Header";
import CheckoutProduct from "../components/CheckoutProduct";
import { selectItems, selectTotal } from "../slices/basketSlice";
import Currency from "react-currency-formatter";
import { signIn, signOut, useSession } from "next-auth/client"
function Checkout() {
const items = useSelector(selectItems);
const total = useSelector(selectTotal)
const [session] = useSession();
<button role="link"
onClick={signIn} className={`button mt-2 font-semibold pl-5 pr-5 `}>
SIGN IN
</button>
<button
disabled={!session} className={`button mt-2 ${!session && 'from-gray-300 to-gray-500 border-gray-200 text-gray-300 cursor cursor-not-allowed'}`}
>
{!session ? "signin to checkout" : "Pay with card"}
</button>
)}
</div>
</main>
</div>
)
}
export default Checkout
HERE IS MY NEXTAUTH FILE
import NextAuth from "next-auth"
import Providers from "next-auth/providers";
export default NextAuth({
// Configure one or more authentication providers
providers: [
Providers.Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
// ...add more providers here
],
})
HERE IS MY ENV FILE
# Authentication
GOOGLE_ID=###########################################
GOOGLE_SECRET=############################################
NEXTAUTH_URL=http://localhost:3000
I have a feeling it is cause of my NEXTAUTH_URL = HTTP://LOCALHOST