Malformed or invalid request: Clarifai Api - javascript

import React from 'react';
import './App.css';
import Navigation from './components/Navigation/Navigation'
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm'
import FaceRecognition from './components/FaceRecognition/FaceRecognition'
import Rank from './components/Rank/Rank'
import Logo from './components/Logo/Logo'
import Clarifai from 'clarifai'
import Particles from 'react-tsparticles';
const particlesOptions = {
particles: {
color: {
value: "#ffffff",
},
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
direction: "none",
enable: true,
outMode: "bounce",
random: false,
speed: 6,
straight: false,
},
number: {
density: {
enable: true,
area: 500,
},
value: 100,
},
opacity: {
value: 0.5,
},
shape: {
type: "circle",
},
size: {
random: true,
value: 2,
},
},
detectRetina: true,}
//clarifai API
const app = new Clarifai.App({
apiKey: 'a2013f7d2d54452d9592d7569ce4c5bd'
});
class App extends React.Component {
constructor (){
super();
this.state = {
input : '',
imageUrl : ''
}
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input});
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
function(response) {
// do something with response
console.log(response);
},
function(err) {
// there was an error
}
);
}
render(){
return (
<div className="App">
<Particles className='particles'
id="tsparticles"
options={particlesOptions}
/>
<Navigation />
<Logo />
<Rank />
<ImageLinkForm onInputChange = {this.onInputChange} onButtonSubmit = {this.onButtonSubmit}/>
<FaceRecognition imageUrl = {this.state.imageUrl}/>
</div>
);}
}
export default App;
Whenever I am running this code, I am getting 'Invalid request' but if someone else is running the same code, there is no error and the code is working fine. I have tried changing multiple time but no solution found please help.
Response Error: {"status":{"code":11102,"description":"Invalid request","details":"Malformed or invalid request"}}
Github repo: https://github.com/devgobind/smart-recognition-brain

Related

How to Re-Initiate the child component in vueJs 3?

I need to change the values and re-initiate the component with props Data.
i tried with $emit unfortunately doesn't work my code.
chart.vue
<template>
<div class="col-12">
<div class="card">
<div class="card-header header-elements">
<div>
<h5 class="card-title mb-0">Statistics</h5>
</div>
<div class="card-header-elements ms-auto py-0">
<select name="status" class="form-select form-select-sm" v-model="chartType" #click="$emit('someEvent')">
<option value="daily" data-label="Days">Last 7 Days</option>
<option value="weekly" data-label="Weeks">Weekly</option>
<option value="monthly" data-label="Months">Monthly</option>
</select>
</div>
</div>
<div class="card-body">
<line-chart v-bind:chartData="chartData" v-bind:chartOptions="chartOptions" v-if="showLineGraph" #some-event="chartData"></line-chart>
</div>
</div>
</div>
</template>
<script>
export default {
props: {},
mounted() {
},
created(){
this.params.params = {
chart_type: "daily",
};
this.chartOptions.scales.xAxes[0].scaleLabel.display = "DAYS";
this.chartOptions.scales.xAxes[0].scaleLabel.labelString = "DAYS";
this.loadGraph();
},
data() {
return {
chartType:'daily',
showLineGraph:false,
params: {
params: {}
},
datasetSample: {
data: [],
label: "",
borderColor: "#ff5b5c",
tension: 0.5,
pointStyle: "circle",
backgroundColor: "#ff5b5c",
fill: false,
pointRadius: 1,
pointHoverRadius: 5,
pointHoverBorderWidth: 5,
pointBorderColor: "transparent",
pointHoverBorderColor: "#fff",
pointHoverBackgroundColor: "#ff5b5c",
height: 500
},
chartData: {
labels: [],
datasets: []
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
scaleLabel: {
display: "",
labelString: ""
},
gridLines: {
display: true,
},
}],
yAxes: [{
beginAtZero: true,
scaleLabel: {
display: "Amount In INR",
labelString: "Amount In INR"
},
gridLines: {
display: true,
},
ticks: {
maxTicksLimit: 10,
beginAtZero: false,
callback: function (value, index, values) {
return value.toLocaleString();
}
}
}]
},
legend: {
position: 'top',
align: 'start',
labels: {
usePointStyle: true,
padding: 15,
boxWidth: 6,
boxHeight: 6,
}
},
plugins: {
tooltip: {
// Updated default tooltip UI
backgroundColor: "#fff",
titleColor: "#000",
bodyColor: "#000",
borderWidth: 1,
borderColor: "#0560e8"
}
}
}
};
},
methods: {
loadGraph: function () {
this.chartData.datasets=[];
this.chartData.labels = [];
axios.get(window.location.href + "/get-chart-data", this.params)
.then(response => {
console.log(response.data);
if (response.data.status == 200) {
let datasets = response.data.data.datasets;
let chart_vlaues=[];
for (var key in datasets) {
if (datasets.hasOwnProperty(key)){
let temp_dataset = Object.assign({}, this.datasetSample);
temp_dataset.data = datasets[key].values;
temp_dataset.label = key;
temp_dataset.borderColor = datasets[key].colour;
temp_dataset.backgroundColor = datasets[key].colour;
temp_dataset.pointHoverBackgroundColor = datasets[key].colour;
chart_vlaues.push(temp_dataset);
}
}
this.chartData.datasets=chart_vlaues;
this.chartData.labels = response.data.data.labels;
this.showLineGraph=true;
}else {
this.chartData.datasets = [];
this.chartData.labels = [];
this.showLineGraph = true;
}
})
.catch(err => {
console.log(err);
console.log("Chart could not loaded.");
})
.then(() => {
});
},
}
}
</script>
LineChart.Vue
<script>
import { defineComponent } from 'vue'
import { Chart as ChartJS, Title, Tooltip, Legend,Line} from 'vue3-chart-v2'
export default defineComponent({
name: 'LineChart',
extends: Line,Tooltip,Legend,Title,
props: {
chartData: {
type: Object,
required: true
},
chartOptions: {
type: Object,
required: false
},
},
watch : {
someEvent: function (value) {
console.log('from watch');
}
},
mounted () {},
created(){
this.renderChart(this.chartData, this.chartOptions);
},
data(){
},
methods:{
someEvent:function(){
alert('iiiiiiiiii');
}
},
emits: {
someEvent(payload) {
console.log('some emits');
}
}
})
</script>
app.js
require('./bootstrap')
import { createApp } from 'vue'
import lineChart from './components/lineChart';
import chart from './components/chart.vue';
const app = createApp({})
app.component('chart', chart);
app.component('line-chart', lineChart);
app.mount('#app')
You use watchers wrong. They are not for watching events.
watch : {
someEvent: function (value) {
console.log('from watch');
}
},
You also did not define your custom event with emits
Please, check the Vue docs about the Component Events
The typical data flow with Vue components is
to the Component: App -> Data -> Component Props -> Watchers -> Methods
from The component: Data -> Event -> Event Handler -> App
So, if you want to re-initiate your child component, that you should update some child component's prop and then react to the change in some child component's watcher.

Particles doesn't show up in react-js

This is my code in Particle.js
import React from "react";
import Particles from "react-tsparticles";
function Particle() {
return (
<Particles
id="tsparticles"
params={{
particles: {
number: {
value: 160,
density: {
enable: true,
value_area: 1500,
},
},
line_linked: {
enable: false,
opacity: 0.03,
},
move: {
direction: "right",
speed: 0.05,
},
size: {
value: 1,
},
opacity: {
anim: {
enable: true,
speed: 1,
opacity_min: 0.05,
},
},
},
interactivity: {
events: {
onclick: {
enable: true,
mode: "push",
},
},
modes: {
push: {
particles_nb: 1,
},
},
},
retina_detect: true,
}}
/>
);
}
export default Particle;
and I call particle in Home.js
import Particle from "../Particle";
import Button from 'react-bootstrap/Button';
function Home() {
return (
<div className="mt-5">
<Particle/>
<Button href="" target="_blank" className="register-btn-inner" size="lg">
Register
</Button>
</div>
);
}
export default Home;
I checked a lot of same questions like particles.js not showing up in reactjs project and Particle.js not showing particles on ReactJS website
but solutions don't help me at all. I searched a lot but I don't understand my mistake. why Particle doesn't work?
I installed tsparticles and react-tsparticles libraries too.
You are missing the init attribute on the Particles component. It's visible in the documentation as well here
This is the documentation example:
import { useCallback } from "react";
import Particles from "react-particles";
import { loadFull } from "tsparticles";
const App = () => {
const particlesInit = useCallback(async engine => {
console.log(engine);
// you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
// this loads the tsparticles package bundle, it's the easiest method for getting everything ready
// starting from v2 you can add only the features you need reducing the bundle size
await loadFull(engine);
}, []);
const particlesLoaded = useCallback(async container => {
await console.log(container);
}, []);
return (
<Particles
id="tsparticles"
init={particlesInit}
loaded={particlesLoaded}
options={{
background: {
color: {
value: "#0d47a1",
},
},
fpsLimit: 120,
interactivity: {
events: {
onClick: {
enable: true,
mode: "push",
},
onHover: {
enable: true,
mode: "repulse",
},
resize: true,
},
modes: {
push: {
quantity: 4,
},
repulse: {
distance: 200,
duration: 0.4,
},
},
},
particles: {
color: {
value: "#ffffff",
},
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
directions: "none",
enable: true,
outModes: {
default: "bounce",
},
random: false,
speed: 6,
straight: false,
},
number: {
density: {
enable: true,
area: 800,
},
value: 80,
},
opacity: {
value: 0.5,
},
shape: {
type: "circle",
},
size: {
value: { min: 1, max: 5 },
},
},
detectRetina: true,
}}
/>
);
};

Export react table as csv

Hi guys I'm trying to export my atlassian dynamic react table as a csv file but the table I'm getting in the file is not really looking as I expected... I tried using the react-csv library but I'm getting . My dynamic table looks like this on my browser. The Columns are in {shareFilterHead} and the rows are {shareFilterRows} . Is there any other way to download this table in React as a csv file?
import React, {Component} from "react";
import DynamicTable from '#atlaskit/dynamic-table';
import styled from 'styled-components';
import { CSVLink, CSVDownload } from "react-csv";
export const createHead = (withWidth) => {
return {
cells: [
{
key: 'filterID',
content: 'Filter ID',
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
{
key: 'author',
content: 'Author',
shouldTruncate: true,
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
{
key: 'filtername',
content: 'Filter Name',
shouldTruncate: true,
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
{
key: 'jql',
content: 'JQL',
shouldTruncate: true,
isSortable: true,
width: withWidth ? 25 : undefined,
fontSize: 30,
},
],
};
};
export const shareFilterHead = createHead(true);
export default class ShareFilter extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
shareFilterRows: []
};
}
componentDidMount() {
fetch(AJS.contextPath() + "/rest/securityrestresource/1.0/results?check=ShareFilter")
.then((res)=>{
if(res.ok) {
return res.json();
}
}).then((res)=>{
this.setState({
isLoaded: true,
shareFilterRows: res.map((row, index) => ({
key: `row-${index}-${row.filterID}`,
cells: [{
key: `${row.filterID}`,
content: row.filterID,
},
{
key: `${row.author}`,
content: row.author,
},
{
key: `${row.filtername}`,
content: row.filtername,
},
{
key: `${row.jql}`,
content: row.jql,
},]}))
})
})
}
render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading Shared Filters...</div>;
} else {
return (
<Wrapper>
<div>
<DynamicTable
head={shareFilterHead}
rows={shareFilterRows}
rowsPerPage={10}
defaultPage={1}
loadingSpinnerSize="large"
isLoading={false}
isFixedSize
defaultSortKey="filterID"
defaultSortOrder="ASC"
onSort={() => console.log('onSort')}
onSetPage={() => console.log('onSetPage')}
/>
<CSVDownload data={shareFilterRows} target="_blank" />;
</div>
</Wrapper>
);
}
}
}

How to return JSON object in Javascript?

I am having issues with returning a JSON object. When I render the webpage, nothing shows up. Does anyone know how to fix this? Sorry, I am new to Javascrtipt.
import React, { useEffect, useState, useContext } from 'react'
export const MarketData = () => {
var obj = {
width: '100%',
height: '100%',
symbolsGroups: [
{
name: 'Indices',
originalName: 'Indices',
symbols: [
{
name: 'INDEX:DEU30',
displayName: 'DAX Index',
},
{
name: 'FOREXCOM:UKXGBP',
displayName: 'FTSE 100',
},
],
},
...
],
showSymbolLogo: true,
colorTheme: 'dark',
isTransparent: false,
locale: 'en',
largeChartUrl:
'https://bondintelligence.cloud.looker.com/extensions/bond_intelligence_webpage::helloworld-js/',
}
return (
<>
<text>{obj}</text>
</>
)
}
You can use JSON.stringify()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The third argument in JSON.stringify() provides new lines and indentation. If only the first argument is provided, the string will be one long line.
Your example with fix (I changed your <text> to <p> as I have never heard of a <text> HTML element):
import React, { useEffect, useState, useContext } from 'react'
export const MarketData = () => {
var obj = {
width: '100%',
height: '100%',
symbolsGroups: [
{
name: 'Indices',
originalName: 'Indices',
symbols: [
{
name: 'INDEX:DEU30',
displayName: 'DAX Index',
},
{
name: 'FOREXCOM:UKXGBP',
displayName: 'FTSE 100',
},
],
},
...
],
showSymbolLogo: true,
colorTheme: 'dark',
isTransparent: false,
locale: 'en',
largeChartUrl:
'https://bondintelligence.cloud.looker.com/extensions/bond_intelligence_webpage::helloworld-js/',
}
var objAsString = JSON.stringify(obj, null, 2)
return (
<>
<p>{objAsString}</p>
</>
)
}

Apex charts, setting series data from array in state

In my react app, I'm getting results from pouchDB that I want to use as the data points in my series for apexCharts.
I'm getting the results and putting them in state, called maxCalories, and when logging in the console they are in this format:
So I want those 7 numbers (all with the index name of caloriesBurned to be my data in the series for the chart but I'm currently getting NaN on the graph.
Here's the full code, how can I set these to the correct format to use them in the chart data?
import React, { Component } from "react";
import Chart from "react-apexcharts";
import DB from '../../db';
import * as moment from 'moment';
class TrendsComponent extends Component {
constructor(props) {
super(props);
this.state = {
maxCalories: '',
calorieRecord: {
caloriesConsumed: '',
caloriesBurned: '',
createdAt: this.newestDate,
updatedAt: undefined
},
caloriesDB: new DB('calorie-records'),
calories: {},
calorieElements: null,
options: {
},
chart: {
toolbar: {
show:false
},
id: "basic-bar"
},
xaxis: {
categories: ['3/20', '3/21', '3/22', '3/23', '3/24', '3/25','3/26']
}
},
series: [
{
name: "Trend (tracked)",
data: {this.maxCalories}
}
]
};
}
componentDidMount(){
this.setMax();
}
setMax = () => {
this.state.caloriesDB.db.find({
selector: {
$and: [
{_id: {"$gte": null}},
{caloriesBurned: {$exists: true}},
{createdAt: {$exists: true}}
]
},
fields: ['caloriesBurned', 'createdAt'],
sort: [{'_id':'desc'}],
limit: 7
}).then(result => {
console.log('max');
console.log(result);
const newDocs = result.docs;
this.setState({
maxCalories: newDocs.map(docs => docs)
});
console.log('maxCalories');
console.log(this.state.maxCalories);
}).catch((err) =>{
console.log(err);
});
}
render() {
return (
<div className="mixed-chart">
<Chart
options={this.state.options}
series={this.state.series}
type="area"
stacked="true"
width="700"
/>
</div>
);
}
}
export default TrendsComponent;
I had the same problem in my project. And I spent a lot of time in looking for solution. So here what I get:
const FinacialResultChart = (props) => {
const options = {
chart: {
toolbar: {
show: false
},
animations: {
enabled: false
}
},
stroke: {
curve: "smooth",
dashArray: [0, 8],
width: [4, 2]
},
grid: {
borderColor: props.labelColor
},
legend: {
show: false
},
colors: [props.dangerLight, props.strokeColor],
fill: {
type: "gradient",
gradient: {
shade: "dark",
inverseColors: false,
gradientToColors: [props.primary, props.strokeColor],
shadeIntensity: 1,
type: "horizontal",
opacityFrom: 1,
opacityTo: 1,
stops: [0, 100, 100, 100]
}
},
markers: {
size: 0,
hover: {
size: 5
}
},
xaxis: {
labels: {
style: {
colors: props.strokeColor
}
},
axisTicks: {
show: false
},
categories: [
"Январь",
"Февраль",
"Март",
"Апрель",
"Май",
"Июнь",
"Июль",
"Август",
"Сентябрь",
"Октябрь",
"Ноябрь",
"Декабрь"
],
axisBorder: {
show: false
},
tickPlacement: "on"
},
yaxis: {
tickAmount: 5,
labels: {
style: {
color: props.strokeColor
}
}
},
tooltip: {
x: { show: false }
}
}
const data = [
{
name: "Итоговый результат",
data: props.userData.traidingMonth
}
]
return (
<Chart
options={options}
series={data}
type="line"
height={280}
/>
)
}
export default FinacialResultChart
So you need to change your class to const, and push all your props (api data for example) into your children chart component. In chart options you can get the chart data with props.data

Categories

Resources