Add rows to the datatable-Error loading dependencies - plotly-dash

I want to create an app that a user can upload CSV files and it will show a data table that the user can edit, add columns and add rows. There are also two dropdowns that contain the value of the columns of the data table. But I get Error loading dependencies after I run the code. Can anyone teach me how to fix this error?
Below is the code:
import base64
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
from dash.exceptions import PreventUpdate
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
app.layout = html.Div([
dcc.Upload(
id='datatable-upload',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%', 'height': '60px', 'lineHeight': '60px',
'borderWidth': '1px', 'borderStyle': 'dashed',
'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px'
},
),
html.Div([
dcc.Input(
id='adding-rows-name',
placeholder='Enter a column name...',
value='',
style={'padding': 10}
),
html.Button('Add Column', id='adding-rows-button', n_clicks=0)
], style={'height': 50}),
html.Div(id='output-data-upload'),
html.Button('Add Row', id='editing-rows-button', n_clicks=0),
dcc.Dropdown(
id='data_selector1',
options=[
{'label': '', 'value': ''}
],
value=[]
),
dcc.Dropdown(
id='data_selector2',
options=[
{'label': '', 'value': ''}
],
value=[]
),
])
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
if 'csv' in filename:
# Assume that the user uploaded a CSV file
return pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
return pd.read_excel(io.BytesIO(decoded))
#app.callback(Output('output-data-upload', 'children'),
[Input('datatable-upload', 'contents')],
[State('datatable-upload', 'filename')])
def update_output(contents, filename):
if contents is None:
return []
df = parse_contents(contents, filename)
return html.Div([
dash_table.DataTable(
id='table',
style_data={
'whiteSpace': 'normal',
'height': 'auto'
},
style_table={'overflowX': 'scroll',
'maxHeight': '300',
'overflowY': 'scroll'},
style_cell={
'minWidth': '150px', 'maxWidth': '180px',
'whiteSpace': 'normal',
'textAlign': 'left'
},
style_header={
'fontWeight': 'bold',
},
fixed_rows={ 'headers': True, 'data': 0 },
columns=[{"name": i, "id": i, 'deletable': True, 'renamable': True} for i in df.columns],
data=df.to_dict("records"),
row_deletable=True,
filter_action="native",
sort_action="native",
sort_mode='multi',
editable=True,
)
])
#The code will work if I remove this function
#app.callback(
Output('table', 'data'),
[Input('editing-rows-button', 'n_clicks')],
[State('table', 'data'),
State('table', 'columns')])
def add_row(n_clicks, rows, columns):
if n_clicks > 0:
rows.append({i['id']: '' for i in columns})
return rows
#app.callback(
Output('table', 'columns'),
[Input('adding-rows-button', 'n_clicks')],
[State('adding-rows-name', 'value'),
State('table', 'columns')])
def update_columns(n_clicks, value, existing_columns):
if n_clicks > 0:
existing_columns.append({
'id': value, 'name': value,
'renamable': True, 'deletable': True
})
return existing_columns
#app.callback(Output('data_selector1', 'options'),
[Input('table', 'data')])
def update_dropdown(rows):
if rows is None:
raise PreventUpdate
df = pd.DataFrame(rows)
print('updating menus')
columns = df.columns
col_labels = [{'label': k, 'value': k} for k in columns]
return col_labels
#app.callback(Output('data_selector2', 'options'),
[Input('table', 'data')])
def update_dropdown2(rows):
if rows is None:
raise PreventUpdate
df = pd.DataFrame(rows)
print('updating menus')
columns = df.columns
col_labels = [{'label': k, 'value': k} for k in columns]
return col_labels
if __name__ == '__main__':
app.run_server(debug=False)
The code will work if I remove the add rows to the data table function.

Related

How to change a column in MySQL database based on user input on a ReactNative app?

I have created a MySQL database for my React Native app and I have a table named 'schedule' in the database:
Structure of 'schedule'
React Native app user enters a smart blind level (a number from 1 to 100) for one of the time values in the table, but since I don't know which time value is being entered I am confused as to how should I change that particular column in the table using React Native states.
For example, if a user enters 0000 for time and the corresponding blind open percentage 96, I want to change the state of time0000 to 0.96. This is proving a bit challenging.
Here's my code for the screen:
import React, { Component, useState } from "react";
import {
Text,
View,
SafeAreaView,
Platform,
StyleSheet,
TouchableOpacity,
ScrollView,
Image,
RefreshControl,
DynamicColorIOS,
TextInput,
Button,
button,
Alert,
} from "react-native";
import colors from "../config/colors";
function ScheduleInsert({ navigation }) {
const [scheduleID, setScheduleID] = useState(4);
const [time0000, setTime0000] = useState(33);
const [time1000, setTime1000] = useState(999);
const [time2000, setTime2000] = useState(999);
const [time3000, setTime3000] = useState(999);
const [time4000, setTime4000] = useState(999);
const [userID, setUserID] = useState(global.userID);
const [time1, setTime1] = useState("");
const [time2, setTime2] = useState("");
const [time3, setTime3] = useState("");
const handleChange = (timeInput, textInput) => {
let string1 = "setTime" + timeInput.toString();
string1(Number(textInput) / 100);
};
const InsertSchedule = () => {
var InsertAPIURL = "http://localhost:8080/api/scheduleWrite.php";
var headers = {
Accept: "application/json",
"Content-Type": "application/json",
};
var data = {
scheduleID: scheduleID,
time0000: time0000,
time1000: time1000,
time2000: time2000,
time3000: time3000,
time4000: time4000,
userID: userID,
};
console.log(JSON.stringify(data));
fetch(InsertAPIURL, {
method: "POST",
headers: headers,
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((response) => {
Alert.alert("You have successfully added the schedule!");
})
.catch((error) => {
Alert.alert("Error" + error);
});
};
return (
<View style={styles.container}>
<TextInput
placeholder={"Time 1 (2400Hr format. For example, 1300 for 1pm)"}
placeholderTextColor={colors.darkorange}
keyboardType={"numeric"}
style={styles.textStyle}
maxLength={4}
onChangeText={(text) => setTime1(Number(text))}
/>
<TextInput
placeholder={"Blind Open Percentage 1"}
placeholderTextColor={colors.darkorange}
keyboardType={"numeric"}
style={styles.textStyle}
maxLength={2}
onChangeText={(text) => handleChange(time1, text)}
/>
<TextInput
placeholder={"Time 2"}
placeholderTextColor={colors.darkorange}
keyboardType={"numeric"}
maxLength={4}
style={styles.textStyle}
/>
<TextInput
placeholder={"Blind Open Percentage 2"}
placeholderTextColor={colors.darkorange}
keyboardType={"numeric"}
maxLength={2}
style={styles.textStyle}
/>
<TextInput
placeholder={"Time 3"}
placeholderTextColor={colors.darkorange}
keyboardType={"numeric"}
maxLength={4}
style={styles.textStyle}
/>
<TextInput
placeholder={"Blind Open Percentage 3"}
placeholderTextColor={colors.darkorange}
keyboardType={"numeric"}
maxLength={2}
style={styles.textStyle}
/>
<Button title={"Save Schedule"} onPress={() => InsertSchedule()} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.white,
alignItems: "center",
justifyContent: "center",
},
ViewStyle: {
flex: 1,
padding: 20,
marginTop: 10,
},
textStyle: {
borderBottomWidth: 1,
borderBottomColor: "red",
marginBottom: 20,
},
});
export default ScheduleInsert;
I created this handleChange function in order to save customer's time input and then use React Native states to change the required MySQL column, but it's just not working as I get told that "setTime0000" for instance is not a function which makes sense, but I don't know how else to change my state of time0000 based on the user input.
By the way, I am able to write the default data into the database successfully, so my API is working fine.
Any help is appreciated!

React Quill is not aligning the html file I get from API

I am new to React-Quill and I am using it to edit an HTML template. I already have custom API which I created using spark post. Now I need to get that HTML file into this editor and then user can edit the template and save it.
When I get the HTML data and pass it into editor, some of the alignments, background colors and image size are different than the original HTML.
Can anyone please provide me a solution how I can improve this?
This is my expected HTML template.
.
.
.
This is what I got from React-Quill.
I want to get the preview as the first image.
This is my current code.
import ReactQuill from 'react-quill';
import { PreviewProps } from 'app/event/emails/emailModal/preview/Preview.types';
import { useLocale } from 'hooks/useLocale/useLocale';
import { Heading, Loader, Typography } from 'ui/atoms';
import 'react-quill/dist/quill.snow.css';
import { useStyles } from './Preview.styles';
export const Preview = ({ title, previewData }: PreviewProps) => {
const classes = useStyles();
const { formatMessage } = useLocale();
if (!previewData) {
return <Loader className={classes.loader} />;
}
const modules = {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }],
[{ align: '' }, { align: 'center' }, { align: 'right' }, { align: 'justify' }],
['link', 'image'],
],
};
const formats = [
'header',
'font',
'size',
'bold',
'italic',
'underline',
'strike',
'blockquote',
'list',
'bullet',
'indent',
'link',
'image',
'color',
'size',
'video',
'align',
'background',
'direction',
'code-block',
'code',
];
return (
<>
<div className={classes.container}>
<Heading variant="h4" bold className={classes.title}>
{formatMessage({ id: 'event.emails.preview.title' })}
</Heading>
<Typography variant="h5" className={classes.subtitle}>
{title}
</Typography>
</div>
<ReactQuill theme="snow" modules={modules} formats={formats} value={previewData.html || ''}>
<div className="text-editor" />
</ReactQuill>
</>
);
};
Anyone please help me to get this correctly. Thank you in advance.

How to enable responsiveness to Plotly-Dash app within an Iframe?

I have created a dash app, that is hosted to serve on the Heroku server. The dash app is completely responsive. If I access it on a mobile, iPad, desktop,.. the plot size auto-scales and fits the width of the window. This is perfect. However, embedding this dash app URL in an iframe of my website, the plot's responsiveness is lost. It does not autoscale to fit the width of the iframe.
How to ensure that the iframe and the plot responsively auto-scales to fit the width of the window?
My dash app: https://isb-hpi.herokuapp.com/
My iframe code:
<div class="iframe-container">
<iframe class="responsive-iframe" src="https://isb-hpi.herokuapp.com/"></iframe>
</div>
My CSS:
.iframe-container {
position: relative;
overflow: hidden;
width: 100%;
padding-top: 45%;
}
.responsive-iframe {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 100%;
height: 100%;
}
code to construct plot:
from warnings import showwarning
import pandas as pd
import numpy as np
import os
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
config = {'responsive': True}
figq1 = px.line(dfq1, x="month", y="final_Index", color="Bedroom",template='presentation', line_shape='spline', labels={"Bedroom": "Type"}, category_orders={"Bedroom":['1bhk', '2bhk', '3bhk']})
figq1.update_traces(line=dict(width=1))
figq1.add_trace(
go.Scatter(
x=dfqa1.month,
y=dfqa1.final_Index,
mode="lines",
line=go.scatter.Line(color="gray", width=2),
showlegend=True, name='all')
)
figq1.update_layout(width=750,height=500, autosize=True)
figq1.update_layout(
xaxis=dict(
rangeslider=dict(
visible=True,
thickness=.05
),
type="date"
)
)
figq1.update_layout(
xaxis_title="Time", yaxis_title="final_Index",legend_title="",
font=dict(
family="Courier New, monospace",
size=11,
color="RebeccaPurple"
), legend=dict(
orientation="h",
yanchor="bottom",
y=1.05,
xanchor="right",
x=1
)
)
figq1.update_yaxes(
title=' '
)
figq1.layout.legend.itemsizing = 'constant'
figq1.layout._config= config
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
server=app.server
app.css.append_css({
'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})
server=app.server
tabs_styles = {'zIndex': 99, 'display': 'inlineBlock', 'height': '4vh', 'width': '12vw',
'position': 'fixed', "background": "#323130", 'top': '12.5vh', 'left': '7.5vw',
'border': 'grey', 'border-radius': '4px'}
tab_style = {
"background": "#323130",
'text-transform': 'uppercase',
'color': 'white',
'border': '#A9A9A9',
'font-size': '9px',
'font-weight': 600,
'align-items': 'center',
'justify-content': 'center',
'border-radius': '4px',
'padding':'6px'
}
tab_selected_style = {
"background": "#A9A9A9",
'text-transform': 'uppercase',
'color': 'white',
'font-size': '9px',
'font-weight': 600,
'align-items': 'center',
'justify-content': 'center',
'border-radius': '4px',
'padding':'6px'
}
app.layout = html.Div([
dcc.Tabs(id='tabs-example', value='tab-1', children=[
dcc.Tab(label='India', value='tab-1',style=tab_style, selected_style=tab_selected_style),
html.Div(id='tabs-example-content')
])
#app.callback(Output('tabs-example-content', 'children'),
Input('tabs-example', 'value'))
def render_content(tab):
if tab == 'tab-1':
return html.Div([
html.Div([
html.Div([
dcc.Graph(id='g2', figure=figq1)
], className="row", style={
'width': 750,
"display": "block",
"margin-left": "auto",
"margin-right": "auto",
}),
], className="row")
])
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
Edit:
When building dash apps with responsive layouts,
always use:
config = {'responsive': True}
autosize=True
Never set the width and height explicitly as you can see in my code to construct the plot.

How to use TranslateService while externalizing an array of string [Angular]

I don't know much about externalizing. I was creating a month picker in Angular. In my typesccript file I had an array of months with hard-coded names:
arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
My senior told me to externalize them in a separate json file so that they can be easily modified later if required. Now I'll show you my code.
monthpicker.component.ts
import { Component, OnInit } from '#angular/core';
import { TranslateService } from '#ngx-translate/core';
#Component({
...
})
export class MonthpickerComponent implements OnInit {
constructor(private translate: TranslateService){
}
//arr = ['Jan', 'Feb', ... 'Nov', 'Dec'];
monthArray = []; /* USING A DIFFERENT EMPTY ARRAY INSTEAD*/
translateCard(): void {
this.translate
.get([
'Months.January',
'Months.February',
...
'Months.December'
])
.subscribe(translations => {
this.monthArray.push(translations['Months.January']);
this.monthArray.push(translations['Months.February']);
...
this.monthArray.push(translations['Months.December']);
});
console.log(this.monthArray);
}
ngOnInit(): void {
this.translateCard();
}
/* CODE TO READ MONTH NAMES AND RENDER IN HTML*/
n = 4;
matrix: any = Array.from({ length: Math.ceil(this.monthArray.length / this.n) }, (_, i) => i).map(i =>
this.monthArray.slice(i * this.n, i * this.n + this.n).map(x => ({
monthName: x,
isSelected: false
}))
);
...
}
monthpicker.component.html
<div *ngFor="let row of matrix" class="my-table">
<span *ngFor="let x of row">
<span class="month-name">
{{ x.monthName }}
</span>
</span>
</div>
And here en-US.json
{
"Months": {
"January": "Jan",
"February": "Feb",
...
"October": "Oct",
"November": "Nov",
"December": "Dec"
}
}
This is all the code I have. There is not even a single error or warning on console. In fact console.log(this.monthArray[]) is also printing all the months correctly. But on the front-end my month-picker panel is absolutely blank. Nothing is coming up. I think my call is asynchronous here:
ngOnInit(): void {
this.translateCard();
}
I tried safely use translate.instant() and many other solutions but still it is blank. Please correct me whats wrong with my implementation.
After subscription you need to populate the matrix array since monthArray will be populated asynchronously. Make the following change:
translateCard(): void {
this.translate
.get([
'Months.January',
'Months.February',
...
'Months.December'
])
.subscribe(translations => {
this.monthArray.push(translations['Months.January']);
this.monthArray.push(translations['Months.February']);
...
this.monthArray.push(translations['Months.December']);
// populate matrix
this.matrix = Array.from({ length: Math.ceil(this.monthArray.length /
this.n) }, (_, i) => i).map(i =>
this.monthArray.slice(i * this.n, i * this.n + this.n).map(x => ({
monthName: x,
isSelected: false
}))
);
});
}

area chart fill-opacity issue in c3js and angular 2

I have created a line chart using c3.js and angular 2.But i am getting a unwanted black area in line chart.It's working more likely chart with filled area.I am trying to override it's css property..."fill-opacity". but it's not working.Give me a solution.enter image description here
Due to c3 lib CSS is missing. CSS file for C3 chart .
https://rawgit.com/masayuki0812/c3/master/c3.css.
copy past css into your bar-chart.component.css and add encapsulation in decorator as shown in e.g.
It will definitely work :->
import { Component, ViewEncapsulation, OnInit } from '#angular/core';
import * as c3 from 'c3';
import * as d3 from 'd3';
#Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css'], //copy and paste css here
encapsulation: ViewEncapsulation.None //add this line in your component
})
export class BarChartComponent implements OnInit {
jsonData : any[] = [];
jsonKeys : any = {};
jsonAxis : any = {};
constructor() { }
ngOnInit() {
this.jsonData = [
{name: 'www.site1.com', upload: 200, download: 150, total: 400},
{name: 'www.site2.com', upload: 100, download: 300, total: 400},
{name: 'www.site3.com', upload: 300, download: 200, total: 500},
{name: 'www.site4.com', upload: 400, download: 100, total: 500},
];
this.jsonKeys = {
x: 'name', // it's possible to specify 'x' when category axis
value: ['upload', 'download'],
};
this.jsonAxis = {
x : {
type : 'category'
}
};
let chart = c3.generate({
bindto: '#chart',
data: {
json: this.jsonData,
keys: this.jsonKeys,
},
axis: this.jsonAxis,
});
}
}