Why do accumulator take first element of an array as default value ? I have tried to find in documentation also but couldn’t.
Category: javascript
Category Added in a WPeMatico Campaign
What’s wrong inside try block as I’m getting response as Null
public static Response getRequest(String urlParameters, Map headers) { RequestSpecification spec =setCertification();
Response response = null;
try { LOGGER.info(“URL : ()”, EnvironmentPath.GET LIMITS TRANSACTION_PATH_URI + urlParameters);
response = RestAssured.given().spec(spec).when().contentType(ContentType. JSON).headers(headers) .get(EnvironmentPath.GET_LIMITS TRANSACTION_PATH URI + urlParameters).then().extract().response(); }
catch (Exception e) { LOGGER.error(“GET_REQUEST_NOT_PROCESSED- there was an exception raised while processing the request”); throw new DPMSException(“GET_REQUEST_NOT_PROCESSED – there was an exception raised while processing the request,e);
return response;
Trouble Playing Changing Audio Files in JavaScript
So essentially I am trying to build a browser game in which various texts and audio clips are played at random, and then you must choose what language it is. I’ve built the base for it which functions well with just text and choosing an answer at random, but I’m having trouble adding the sound file and having it play. This is my first real project using JavaScript and I was hoping I could get some help here.
The HTML div I’m using is as follows
<div class="field">Play Audio</div>
<button id="audio" onclick="audio_clicked()"></button>
</div>
then I have a seperate, linked .js file which I’m doing the following-
Storing the questions in a question bank
quiz[0] = new Question("Hola", "languages/spanish.mp3", "Spanish", "Italian", "Cyric");
quiz[1] = new Question("Hello", "languages/english.mp3", "English", "Spanish", "French");
quiz[2] = new Question("Haye", "languages/udhr_somali.mp3", "Somali", "Norwegian", "Swedish");
Reading the questions
document.getElementById("question").innerHTML= randomQuestion.question;
document.getElementById("audio").innerHTML=randomQuestion.audio;
and finally executing the process when the button is clicked
// play audio button clicked
function audio_clicked() {
audio.play();
}
// what to do when answer a button clicked
function answerA_clicked() {
var answerA = document.getElementById("answerA").value;
checkAnswer(answerA);
}
This is where I am having the trouble, as I’m not sure it is reading my audio correctly. It started displaying the audio file name on the button which is the opposite of what i want. The full project is on my GitHub github.com/tjsanzen/language-game
Thank you for any help you may provide 🙂
React Native Webview not loading scripts in production build -iOS
i have html file with scripts, i need to display it in React native screen so i used react-native-webview, it is working fine in ios debug build but not working in ios production build getting blank screen
This is my html page
<html >
<meta name="viewport" content="width=device-width, initial-scale=1" />
<body onload="loader();">
<script>
window.fwSettings = {
'widget_id': 7300********
};
!function () {
if ("function" != typeof window.FreshworksWidget)
{
var n = function () {
n.q.push(arguments)
};
n.q = [],
window.FreshworksWidget = n } }()
</script>
<script type='text/javascript'
src='https://widget.freshworks.com/widgets/7*********.js' async defer></script>
<script>
function loader() {
FreshworksWidget('hide', 'launcher');
FreshworksWidget('open');
};
</script>
</body>
</html>
i placed this html page in Webview like this
<WebView
source={kbHTML}
javaScriptEnabled={true}
domStorageEnabled={true}
originWhitelist={['*']}
scalesPageToFit={false}
startInLoadingState={true}
automaticallyAdjustContentInsets={false}
containerStyle={{
flex: 1,
width: '100%',
height: '100%'
}}
style={{
flex: 1,
height: height,
width: width,
resizeMode: 'cover',
}}
/>
its working fine in ios debug mode but not working in ios production build..getting blank screen.
react-native-webview: “^11.18.1”,
react-native: “0.64.2”
is any npm package available like react-xarrows for angular [closed]
Looking some similar to below for angular 8+
https://www.npmjs.com/package/react-xarrows[React Xrrows][1]
How should I force blur event inside onClick event in react?
I’ve been read through other similar posts as mine, but failed to find a suitable solution in my case. I have a react component that allow user to input something.
Inside this component, there is a button for the user to submit the input.
What I wanted now is blur the InputField once I hit the submit button.
I know in Javascript we can use something like element.blur()
This is what I am trying to do
return (
<InputField
value={props.value}
placeholder={"Type here..."}
onSubmit={() => {
props.onSubmit;
console.log('Click submit!!!');
InputField.blur();
}}
/>
);
It gives me an error said property ‘blur’ is not exist in react component. Any idea of how to do force blur in react?
I use SpeechRecoginition in google cloud client library PHP, is streaming possible?
I am using SpeechRecoginition for google cloud client library PHP.
For examples, refer to this document.
We have tested and confirmed the normal operation with local files.
But I want to SpeechRecognition by sending a voice file in real time, not a stored file.
I want to pass data to PHP using MediaRecorder js, analyze the voice coming from PHP, and deliver it back to the client.
This is the document I referenced regarding MediaRecord js.
[client.js]
var mediaRecorder;
navigator.mediaDevices.getUserMedia(constraints).then(stream=>{
var options = {
type: 'video',
mimeType: 'video/webm'
};
try{
mediaRecorder.stop()
}catch(e){}
mediaRecorder=null;
let order = 0;
mediaRecorder = new MediaRecorder(stream,options);
mediaRecorder.ondataavailable =function(e) {
if(e.data&&e.data.size>0) {
recordedChunks.push(event.data);
var reader = new FileReader();
reader.readAsArrayBuffer(e.data);
reader.onloadend = async function(event) {
let arrayBuffer = reader.result;
let uint8View = new Uint8Array(arrayBuffer);
let response = await fetch('server.php', {
method: 'POST',
body: JSON.stringify({
chunk: uint8View,
order: order
})
});
order += 1;
}
}
}
mediaRecorder.start(250);
})
[server.php]
<?php
require($_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php');
use GoogleCloudSpeechV1RecognitionConfigAudioEncoding;
use GoogleCloudSpeechV1RecognitionConfig;
use GoogleCloudSpeechV1StreamingRecognitionConfig;
$speechClient = new GoogleCloudSpeechV1SpeechClient();
try {
$recognitionConfig = new RecognitionConfig();
$recognitionConfig->setEncoding(AudioEncoding::FLAC);
$recognitionConfig->setSampleRateHertz(44100);
$recognitionConfig->setLanguageCode('ko-KR');
$config = new StreamingRecognitionConfig();
$config->setConfig($recognitionConfig);
//$audioResource = fopen('localfile path', 'r'); //original
//receive DATA
$chunk = $_POST['chunk'];
$binarydata = pack("C*", ...$chunk);
$audioResource = $binarydata;
$responses = $speechClient->recognizeAudioStream($config, $audioResource);
foreach ($responses as $element) {
//recognition result send client
}
} catch(Exception $e) {
var_dump($e);
}
I want to receive video data from [client.js] and analyze the audio in real time in [server.php].
SpeechRecogniton is needed for arrayBuffer type data created in mediaRecorder rather than local file analysis.
Please advise.
Images not showing in Nuxt app even with correct path in developer console
I am trying to display images from an assets folder in a Nuxt but it won’t work even if the src value in the HTML is correct.
Here is an excerpt of the code.
<div v-for="(item, index) in items" :key="index">
<div class="item-img">
<img :src="`../assets/imgs/${item.img}`"/>
</div>
</div>
The above path is correct as the component is inside a pages folder at the same root level as the assets folder.
I have image filenames in an array like so:
data() {
return {
images: ['image0.jpg', 'image1.jpg'],
...
}
There is an async function that is making an API call
to fetch some items. When the API is finished a random image is added to each item.
async getMovies() {
const data = axios.get `api_call_here`)
const result = await data
result.data.results.forEach((item) => {
let randomImg =
this.images[Math.floor(Math.random() *
this.images.length)]
item.img = randomImg
this.items.push(item)
})
},
I am sure the path to the images is correct and that they exist in the specified folder. I also know the path works because I can display any single image from the same assets folder inside another component at the same level.
I think I have tried every combination for the interpolation inside the src attribute and nothing has worked.
Lastly, I can see the correct path in the elements themselves when I inspect them in the developer console. What is even more baffling is the images seem to be taking up the appropriate space on the page but they are empty (blank space).
I have run out of ideas. If anyone can help me figure out what is going wrong I’d be very grateful.
WARN: Unable to locate ‘report-task.txt’ in the workspace
My stage sonarqube always fails to run the job, I’ve made sure the server is correct.
Console output
Started by user Jesaya Fernando Napitupulu
Obtained Jenkinsfile from git http://10.8.60.132/jesaya/simple-webapp.git
[Pipeline] Start of Pipeline
[Pipeline] podTemplate
[Pipeline] {
[Pipeline] node
Created Pod: kubernetes jenkins/xjoj-61-kw27q-npzb8-x2q9c
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Scheduled] Successfully assigned jenkins/xjoj-61-kw27q-npzb8-x2q9c to microk8s-worker
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Pulled] Container image "docker.io/library/openjdk:11.0.14.1-jre" already present on machine
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Created] Created container jdk
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Started] Started container jdk
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Pulled] Container image "jenkins/inbound-agent:4.11-1-jdk11" already present on machine
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Created] Created container jnlp
[Normal][jenkins/xjoj-61-kw27q-npzb8-x2q9c][Started] Started container jnlp
Agent xjoj-61-kw27q-npzb8-x2q9c is provisioned from template xjoj_61-kw27q-npzb8
---
apiVersion: "v1"
kind: "Pod"
metadata:
annotations:
buildUrl: "http://10.8.60.132:8880/job/'joj/61/"
runUrl: "job/'joj/61/"
labels:
jenkins: "slave"
jenkins/label-digest: "f4a24cf79b1ba88f85dc929f1365e192a6cbf6ee"
jenkins/label: "xjoj_61-kw27q"
name: "xjoj-61-kw27q-npzb8-x2q9c"
namespace: "jenkins"
spec:
containers:
- image: "docker.io/library/openjdk:11.0.14.1-jre"
name: "jdk"
tty: true
volumeMounts:
- mountPath: "/home/jenkins/agent"
name: "workspace-volume"
readOnly: false
- env:
- name: "JENKINS_SECRET"
value: "********"
- name: "JENKINS_AGENT_NAME"
value: "xjoj-61-kw27q-npzb8-x2q9c"
- name: "JENKINS_WEB_SOCKET"
value: "true"
- name: "JENKINS_NAME"
value: "xjoj-61-kw27q-npzb8-x2q9c"
- name: "JENKINS_AGENT_WORKDIR"
value: "/home/jenkins/agent"
- name: "JENKINS_URL"
value: "http://10.8.60.132:8880/"
image: "jenkins/inbound-agent:4.11-1-jdk11"
name: "jnlp"
resources:
limits: {}
requests:
memory: "256Mi"
cpu: "100m"
volumeMounts:
- mountPath: "/home/jenkins/agent"
name: "workspace-volume"
readOnly: false
nodeSelector:
kubernetes.io/os: "linux"
restartPolicy: "Never"
volumes:
- emptyDir:
medium: ""
name: "workspace-volume"
Running on xjoj-61-kw27q-npzb8-x2q9c in /home/jenkins/agent/workspace/'joj
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
The recommended git tool is: NONE
using credential fcf5851b-d66d-4536-9c17-c298d681ff4b
Cloning the remote Git repository
Cloning repository http://10.8.60.132/jesaya/simple-webapp.git
> git init /home/jenkins/agent/workspace/'joj # timeout=10
Fetching upstream changes from http://10.8.60.132/jesaya/simple-webapp.git
> git --version # timeout=10
> git --version # 'git version 2.30.2'
using GIT_ASKPASS to set credentials GitLab - @jesaya
> git fetch --tags --force --progress -- http://10.8.60.132/jesaya/simple-webapp.git +refs/heads/*:refs/remotes/origin/* # timeout=10
Avoid second fetch
Checking out Revision 7754fca1b5b3bfba7bbb856c933fda5f4704d9ae (refs/remotes/origin/master)
> git config remote.origin.url http://10.8.60.132/jesaya/simple-webapp.git # timeout=10
> git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
> git config core.sparsecheckout # timeout=10
> git checkout -f 7754fca1b5b3bfba7bbb856c933fda5f4704d9ae # timeout=10
Commit message: "Update Jenkinsfile"
> git rev-list --no-walk 24d08d802f19788bd1273eb9a384d1fad98d8048 # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (SAST)
[Pipeline] tool
Unpacking https://repo1.maven.org/maven2/org/sonarsource/scanner/cli/sonar-scanner-cli/4.7.0.2747/sonar-scanner-cli-4.7.0.2747.zip to /home/jenkins/agent/tools/hudson.plugins.sonar.SonarRunnerInstallation/sonar-scanner on xjoj-61-kw27q-npzb8-x2q9c
[Pipeline] withEnv
[Pipeline] {
[Pipeline] withSonarQubeEnv
Injecting SonarQube environment variables using the configuration: sonarqube-server
[Pipeline] {
[Pipeline] sh
process apparently never started in /home/jenkins/agent/workspace/'joj@tmp/durable-b5831242
(running Jenkins temporarily with -Dorg.jenkinsci.plugins.durabletask.BourneShellScript.LAUNCH_DIAGNOSTICS=true might make the problem clearer)
[Pipeline] }
WARN: Unable to locate 'report-task.txt' in the workspace. Did the SonarScanner succeed?
[Pipeline] // withSonarQubeEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // podTemplate
[Pipeline] End of Pipeline
ERROR: script returned exit code -2
Finished: FAILURE
Configuration of my sonarqube server:
Configuration of my sonar scanner tool:
pipeline {
agent {
kubernetes {
cloud 'kubernetes'
namespace 'jenkins'
yaml'''
apiVersion: v1
kind: Pod
spec:
containers:
- name: jdk
image: docker.io/library/openjdk:11.0.14.1-jre
tty: true
'''
}
}
stages {
stage('SAST') {
environment {
SCANNER_HOME = tool 'sonar-scanner'
}
steps {
withSonarQubeEnv('sonarqube-server') {
sh" ${SCANNER_HOME}}/bin/sonar-scanner
-Dsonar.projectKey=simple_webapp
-Dsonar.sources=. "
}
}
}
}
}
Relevant software version:
Sonarqube scanner: 4.7.0 2747
Sonarqube server: 8.9.8.54436
Jenkins: 2.332.2
Kubernetes (MicroK8s): 1.23.5-2+c812603a312d2b
Sonarqube Scanner plugin for Jenkins: 2.14
Kubernetes plugin for Jenkins: 3580.v78271e5631dc
This pipeline only runs a sonar scanner to scan my node.js code. For the Jenkins themselves, they run on a slave architecture.
Does anyone understand where this pipeline is going wrong? Console output does not provide a clear output of the error.
How to count the number of array of object id’s and increment
probably an easy question but a bit stumped, given this JSON structure:
{
"users": [{
"action": "update",
"payload": [{
"id": "1",
"name": "Albin Jaye"
},
{
"id": "2",
"name": "Dave Mustaine"
}
]
}],
I am testing a conditional for the users key, and then of course for creating a new entry in another file for payload I need to increment the id counter So, I have been trying this, but not working:
if(actionDetail.action === 'create') {
console.log('This is a CREATE entry');
var size = Object.keys(actionDetail.payload[0]).length;
console.log(size);
}
of course this doesn’t work, I don’t need the number of keys, I just simply need to know how to count the total numbers of objects in the payload array of objects (2 total) not sure how to do this? I am guessing a nifty use of .reduce() could do it, or similar? i.e. set a const to the reduce() and then add +1 so I have 3 in the variable for new record to be added!
trying to add docker image for frontend vite app
so I have working backend and db images within my container and I’m trying to now do the same with the frontend but I’m having a much more difficult time being able to view my app. My impression is that I had to copy over the dist folder created after running vite build. I created an image from my frontend dockerfile and updated my docker-compose file to include the frontend service but when I navigate to 3300 I get a 404. My server is running on 3300 and when I usually run vite it runs a dev server on 3000. I’m also new to using vite which has made this a little more confusing. I’ve tried messing with ports and which are exposed but have had no luck. had a much easier time containerizing the backend and my db. thanks so much for any help!
Dockerfile:
FROM node:16-alpine
RUN mkdir -p /user/src/app
WORKDIR /user/src/app
COPY ["package.json", "package-lock.json", "./"] /user/src/app/
RUN npm ci
COPY . .
EXPOSE 3300
CMD [ "npm", "run", "server:run" ]
Dockerfile-frontend:
FROM node:16-alpine
WORKDIR /user/src/app
COPY . .
RUN npm ci
RUN npm run app:build
COPY dist /user/src/app
EXPOSE 3300
CMD ["npm", "run", "app:dev"]
Docker-compose:
version: '3.9'
services:
#mongo db service
mongodb:
container_name: db_container
image: mongo:latest
env_file:
- ./.env
restart: always
ports:
- $MONGODB_DOCKER_PORT:$MONGODB_DOCKER_PORT
volumes:
- ./mongodb:/data/db
#node app service
app:
container_name: node_container
image: sherlogs_app
build: .
env_file:
- ./.env
ports:
- $NODE_LOCAL_PORT:$NODE_LOCAL_PORT
volumes:
- .:/user/src/app
stdin_open: true
tty: true
depends_on:
- mongodb
# frontend container
frontend:
container_name: frontend_container
image: sherlogs/frontend-container
build: .
env_file:
- ./.env
ports:
- $FRONTEND_LOCAL_PORT:$FRONTEND_LOCAL_PORT
volumes:
- .:/user/src/app
depends_on:
- mongodb
- app
volumes:
mongodb: {}
The content overflows after the echarts line chart refreshes the page
The content overflows after the echarts line chart refreshes the page…
It is normal to load the chart for the first time。but after refreshing the page, the content overflow…
had tried ”’this.echarts resize”’ before ”’setOption(option)”’ it doesn’t work….
cypress goes in an infinite loop to lauch webpage
I am trying to access a URL outside of the defined environment but the page load goes in a loop and does not load the home page once the authentication is completed from Login screen
My implementation is as below:
The below utility.js file launches URL based on the environment the user selects:
export class Utility {
getBaseUrl(){
let envs = Cypress.env('ENV');
console.log(envs)
if(envs == 'production'){
return "https://prodsite.site.com.au";
}else if(envs =='canarys'){
return "https://stagenv2.site.com.au";
}else if(envs =='stage'){
return "https://stageenv.site.com.au";
}
}
}
snippet of Cypress.json file configured as below:
{
"env": {
"nzUrl": "https://search.infotrack.nz"
},
"viewportWidht": 980,
"viewportHeight": 1200,
"baseUrl": "https://stageenv.site.com.au",
}
To call the utility.js, have passed the url in a constant
const url = new Utility().getBaseUrl();
Ideally, to launch the url, i use
cy.visit(url)
To access the environment variable,
cy.visit(Cypress.env('nzUrl'));
After launching the application. The login screen loads up , authenticates itself , but to show up the home page, the page goes in a loop and fails to load it self
The baseurl works as expected , no issues there.
Facing this issue when accessing the the url in env variable

Looking for some help here. I have tried the following:
- The website launches perfectly manually
- Configured cypress.json with a url for launching a webpage other than baseurl, this approach did not work
- Troubleshooted the webelements
I am looking forward for any help / suggestions with this information. Appreciate your kind help in advance
Why the button event doesnt increment the counter?
I tried to increment the counter in the test but when i press the button the value doesnt change. I used the fireEvent from React testing library and React test utils but the value still in 10.I use react 18.
CounterApp:
import {useState} from "react";
import PropTypes from "prop-types";
const CounterApp = ({value=10})=>{
const [counter,setCounter] = useState(value);
const handleAdd= ()=>{
setCounter(counter+1);
}
const handleSubstract = ()=>{
if(counter>0){
setCounter(counter-1);
}
}
const handleReset = ()=>{
setCounter(0);
}
return(
<>
<h1>CounterApp</h1>
<h2>{counter}</h2>
<button onClick={handleAdd}>+1</button>
<button onClick={handleSubstract}>-1</button>
<button onClick={handleReset}>Reset</button>
</>
);
}
CounterApp.propTypes={
value: PropTypes.number.isRequired
}
export default CounterApp;
And the test archive:
import { create} from "react-test-renderer";
import CounterApp from "../CounterApp";
import '@testing-library/jest-dom';
import ReactTestUtils from 'react-dom/test-utils';
import {fireEvent} from "@testing-library/react";
describe("Test in counterApp",()=>{
test("Should be increment the count",()=>{
const component = create(<CounterApp value={10}/>);
const values= component.root;
const button=values.findAllByType("button").at(0).props;
const counter = values.findByType("h2").props.children;
ReactTestUtils.Simulate.click(button);
expect(counter).toBe("11");
})
})
is it possible to create a webscraping application that uploads the newest ‘content’ from a website onto my own website?
I am looking to build an application that displays 3 different website’s newest content/update/changes onto my own website/application, this can be done through a link to the new content but a visual image is what I’m looking for that the link can be attached to. I’m new to programming and am just seeing if this is a viable project to work towards. Cheers for any help 🙂

