Developers can use these components to create functionalities such as UI controls, interactions, gestures, animations, and a lot more. Each open-source UI component can have its own unique style and different levels of support for modifications and implementation. However, if you pair the framework with some JavaScript plugins, the possibilities could be endless.
Popular New Releases in User Interface
vue
react
18.0.0 (March 29, 2022)
bootstrap
4.6.1
react-native
0.68.1
create-react-app
v5.0.1
Popular Libraries in User Interface
by vuejs javascript
192954 MIT
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
by facebook javascript
186685 MIT
A declarative, efficient, and flexible JavaScript library for building user interfaces.
by twbs javascript
156587 MIT
The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
by facebook javascript
102222 NOASSERTION
A framework for building native applications using React
by facebook javascript
94434 MIT
Set up a modern web app by running one command.
by vercel javascript
85621 MIT
The React Framework
by mrdoob javascript
80965 MIT
JavaScript 3D Library.
by mui-org javascript
75241 MIT
MUI (formerly Material-UI) is the React UI library you always wanted. Follow your own design system, or start with Material Design.
by animate-css css
74293 NOASSERTION
🍿 A cross-browser library of CSS animations. As easy to use as an easy thing.
Trending New libraries in User Interface
by vitejs typescript
40832 MIT
Next generation frontend tooling. It's fast!
by withfig typescript
16522 MIT
Fig adds autocomplete to your terminal.
by facebookexperimental javascript
16419 MIT
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
by type-challenges typescript
16090 MIT
Collection of TypeScript type challenges with online judge
by tailwindlabs javascript
14454 MIT
A set of free MIT-licensed high-quality SVG icons for UI development.
by tailwindlabs typescript
14223 MIT
Completely unstyled, fully accessible UI components, designed to integrate beautifully with Tailwind CSS.
by remotion-dev typescript
12674 NOASSERTION
🎥 Create videos programmatically in React
by pavlobu typescript
12515 AGPL-3.0
Deskreen turns any device with a web browser into a secondary screen for your computer
by rustdesk rust
11657 GPL-3.0
Yet another remote desktop software
Top Authors in User Interface
1
188 Libraries
196712
2
184 Libraries
48576
3
183 Libraries
5728
4
102 Libraries
3425
5
100 Libraries
8163
6
99 Libraries
21316
7
98 Libraries
24945
8
92 Libraries
5387
9
88 Libraries
272
10
85 Libraries
119528
1
188 Libraries
196712
2
184 Libraries
48576
3
183 Libraries
5728
4
102 Libraries
3425
5
100 Libraries
8163
6
99 Libraries
21316
7
98 Libraries
24945
8
92 Libraries
5387
9
88 Libraries
272
10
85 Libraries
119528
Trending Kits in User Interface
Gulp-typescript is a plugin which allows you to convert your Typescript code into JavaScript. It can serve as an alternative to TypeScript compiler.
This kandi kit for Candy Crush (one of the most popular games), has been rewritten using the Phaser HTML5 game engine along with Typescript language. AngularJs is also used for creating game directives, so they can be easily included in the angular app.
Gulp is a streaming build system which can run tasks in sequence or parallel. Gulp-typescript is a plugin which allows you to convert your Typescript code into JavaScript. It can also serve as an alternative to TypeScript compiler if you don’t want all the features it provides (like support for external modules, rich IDE support). Gulp-concat is used to concatenate files together. Gulp-clean-css is used to remove comments from your CSS code.
The most important part of building a game like Candy Crush is to have a solid workflow. We have used TypeScript, Gulp and Webpack and built a fully-functional Candy Crush game. We'll be using TypeScript, Gulp and Webpack to build a fully-functional Candy Crush game. kandi kit provides you with a fully deployable Candy Crush app. Source code included so that you can customize it for your requirement.
Troubleshooting
- While running batch file, if you encounter Windows protection alert, select More info --> Run anyway
- During kit installer, if you encounter Windows security alert, click Allow
- While executing 'start http://localhost:3000 && gulp start' command, if you encounter browser-sync issue, go to default-config.js file, which will be under node_modules\browser-sync\dist directory and set property open to false without any quotes.
- While running batch file, if you encounter npm not recognized error, re-run the batch file.
- If you face any issues while running the candy crush app, reduce the node version to 10.24.1
For a detailed tutorial on installing & executing the solution as well as learning resources including training & certification opportunities, please visit the OpenWeaver Community
Development Environment
Visual Studio Code is a source-code editor made by Microsoft for Windows, Linux, and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git.
Runtime Environment
Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser.
JavaScript Libraries
The following libraries provide flexibility to automate slow, and redundant workflows efficiently.
Support
If you need help using this kit, you may reach us at the OpenWeaver Community.
Google maps is a powerful and complex application. To integrate it into the React app “google-map-react” package is used. Any React component on Google Maps can be rendered by this package, which is a component written atop a tiny portion of the Google Maps API. It is actively maintained and simple enough to use. It is entirely isomorphic. Even without the Google Maps API being loaded, it can render map components in the browser. Every item on the map may be hovered using an internal, adjustable hover algorithm.
Since google-map-react allows the user to render any React component on the map, a specific component can be designed that shows a pin icon and text. One can use Iconify library (a collection of free SVG icons) for the icons.
One should be aware of a few prerequisites for the purpose:
- JavaScript ES6
- Searching for Location in Google Map
- React.js library
To know more about the integration of Google Maps, refer to the code given below.
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Open the terminal from IDE.
- npm start to run the file.
Note: Create your own API KEY and paste it in the place of 'YOUR_API_KEY' in the code snippet.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for "how to embed an exact place in google map in Reactjs" in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
Using this solution, we are able to embed an place in google map with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to embed an exact place in google map in Reactjs.
Dependent Libraries
You can also search for any dependent library on kandi like 'react'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
A color picker is another application of react that enables the users to pick colors from a palette or a color wheel. In online applications, color pickers are frequently used for tasks like choosing a text color, a background color, or a color for a graphical element. React color picker components are provided by several libraries, including react-color and react-color-picker.
- react-color-picker: This library provides components that enable the users to include a color- choosing interface in their application.
- react-color: A wide range of color picker components, including SketchPicker, ChromePicker, and HuePicker, are included in this library.
react-color is a more comprehensive library that includes a variety of color picker components with different styles unlike react-color-picker, which is a much simpler library, including a single-color picker component, and customization options are provided by props. There are several more props available for modifying the default color, the format of the selected color, and the layout of the color picker, among other aspects of the ColorPicker component's look and performance.
For more information about customizing color picker in React, refer to the code given below
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and Styled-components library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm i styled-components.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js) and refer demo for styles.css file.
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'create color picker in react' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Styled-components version-6.0.0.
Using this solution, we are able to customize color picker in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to customize color picker in React.
Dependent Library
You can also search for any dependent libraries on kandi like 'react' and 'styled-components'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Use the react-player or video-react libraries to integrate a YouTube video into a React project. React Player allows you to embed audio and video players.
It supports various media kinds and sources, including YouTube, Vimeo, SoundCloud, and local files, and offers a straightforward, programmable interface for playing media files. Another library for playing audio and video in React applications is called Video-React. It offers comparable user experience for manipulating audio and video players in your React components and is built on top of the well-known video.js package. Like React Player, Video-react offers support for various media formats and sources. With a large user base and vibrant developer communities, React Player and Video-react are well-liked choices for integrating audio and video features into React apps. Consider each library's features and options, the level of customization and control you require, and the compatibility and integration with other tools and libraries you are using when choosing which library to employ in your project.
Here is an example of how you embed a YouTube video into a React project:
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and ReactPlayer libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install react-player.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Remove the first line(import statement).
- Import React library by using the command -> import React from 'react';
- Import ReactPlayer library by using the command -> import ReactPlayer from 'react-player';
- Replace ReactVideo as ReactPlayer which is present inside the div tag.
- Open the terminal from IDE.
- npm start to run the file.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'youtube video on react page' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- ReactPlayer version: current.
Using this solution, we are able to create an youtube video on react page with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to create an youtube video on react page.
Dependent Libraries
You can also search for any dependent libraries on kandi like 'react' and 'react-player'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
JavaScript libraries are collections of pre-written code that can be used to create web applications. They provide functions, features, and resources.
It makes the development process faster and easier They often create dynamic, interactive experiences on websites and applications. JavaScript libraries are used for various tasks, such as DOM manipulation, AJAX requests, data analysis and visualization, client-side storage, and more. It includes Creating Interactive Tours, Enhancing Customer Experience, Creating Interactive Tutorials, and Improving User Onboarding.
Let us look at some of these famous libraries.
webpack
- Offers advanced features such as code-splitting, hot module replacement (HMR), tree-shaking, and dynamic loading.
- Provides plugins and loaders that can be used to customize how code is transformed and bundled.
- Allows to combine multiple modules into a single bundle.
mocha
- Provides an asynchronous testing interface.
- Supports a wide variety of testing styles with its flexible syntax.
- Allows developers to create custom test interfaces and reporters.
intro.js
- Supports auto-scroll and scroll-hijacking.
- Allows developers to create custom tours in any language.
- Provides a modern and lightweight interface, with a minimalistic design.
bower
- Supports versioning and resolution of dependencies.
- Provides command line interface making it easy to instantly search, install, and manage packages in a project.
- Allows to manage both front-end and back-end packages.
grunt
- Provides wide range of plugins and third-party integrations.
- Provides built-in support for popular frameworks and libraries.
- Allows developers to easily configure and create tasks for automating common development workflows.
knockout
- Provides an easy-to-use two-way data-binding system.
- Provides a powerful templating system that makes it easy to display complex data structures.
- Provides a declarative binding syntax that simplifies linking the data to the HTML elements on the page.
shepherd
- Allows developers to create step-by-step product tours and walkthroughs intuitively.
- Provides options for targeting specific users, including localization and different themes.
- Supports integration with other libraries and frameworks, such as React and Vue.
mixitup
- Provides built-in support for powerful animation effects.
- Allows developers to create custom sorting and filtering rules.
- Supports integration with external API's, allowing pulling in data from other sources.
hopscotch
- Is highly accessible, i.e., it is easy for people with disabilities to use.
- Offers comprehensive documentation, making it easy for developers to get up and running quickly.
- Is device-agnostic, meaning it works across different devices and browsers.
joyride
- Provides a built-in feature called “Progress Indicator,” which allows the user to see their progress through the tour.
- A built-in analytics system provides valuable insights into how users interact with the tour.
- Allows developers to easily add triggers and custom CSS to enhance the user experience.
3D graphics are becoming increasingly important, enabling developers to build immersive and interactive user experiences.
JavaScript has evolved as a popular language for creating such events. These libraries enable a wide range of applications, including gaming, e-commerce, education, and more, and content from Three.js, widely regarded as the industry standard for browser-based 3D graphics, to Babylon.js, which provides a powerful game engine and physics system, to PlayCanvas, which enables collaborative, browser-based game development.
Here are 8 of the best JavaScript 3D libraries 2023 developers can use for an immersive 3D experience.
Three.js:
- Shows 3D-printed object previews.
- Helps create virtual concerts and events.
- Helpful in product animations for marketing.
Babylon.js:
- Helps in product design and prototyping.
- Helps do virtual makeup try-on.
- Allows 3D printing model creation and optimization.
cesium:
- Helpful in real-time traffic monitoring and visualization.
- Helps in weather and environmental monitoring.
- Helps monitor geospatial data and provides its analysis and visualization.
Whs.js:
- Helps create interactive virtual art galleries.
- Shows 3D product catalogs and configurators for fashion.
- Helps in virtual reality amusement park rides.
Cannon.js:
- Helps with physics-based interactive educational videos.
- Helps create interactive roller coaster and amusement park ride simulations.
- Allows collaborative remote prototyping for mechanical engineering.
Physics.js:
- Creates interactive kinetic art installations.
- Helps create physics-based educational games for kids.
- Helps create interactive science museum exhibits.
PlayCanvas-ar:
- Helps in collaborative remote design and prototyping.
- Helps do 3D product customization and personalization.
- Has immersive language learning simulations.
Turbulenz_jslib:
- Helps in interactive educational simulations for mathematics and statistics.
- Creates virtual reality art galleries.
- Allows immersive virtual reality movie theaters.
We can create any animation with suitable libraries or combinations of libraries that are well-known for their functionalities using Python Animation Libraries. For developers looking for options with less complex code with maximum customization options, users can customize their plots and designs depending on their preferences.
Choosing a suitable library plays a key role in any machine learning or data science project, and we should do it properly to avoid other related issues which may arise. Some libraries offer an interactive plot to attract playing with the graph and visualize it uniquely. It will allow you to edit videos, create animations, and create a map or geological animations where we can analyze the geological data.
Here is the list of handpicked 18 best Python Animation Libraries in 2023 which will help you with your animation requirements:
manim - 3b1b
- Is a Python library for creating mathematical animations and educational videos that Grant Sanderson develops.
- Is an open source library that allows users to create high-quality animations which visualize mathematical concepts like animations of graphs, functions, fractals, and more.
- Uses Python code for creating animations which we can export to animated GIFs or video files.
PythonRobotics
- Is a Python library for implementing different robotics simulations, visualizations, and algorithms.
- Offers various resources and tools for robotics developers, like algorithms for path planning, localization, motion control, mapping, and many more.
- Includes simulation environments like 2D and 3D simulators, that will allow developers to test their algorithms in virtual environments before deploying them on real robots.
matplotlib
- Is a comprehensive library for creating animated, interactive visualizations and static in Python.
- Produces publication-quality figures in different interactive environments and hardcopy formats across platforms.
- Can be used in Python Scripts, web application servers, various graphical user interface toolkits, and Python/IPython shells.
manim - ManimCommunity
- Is an animation engine for explanatory math videos used for programmatically creating precise animations.
- Includes various tools for creating animations like support for vector graphics, 3D objects, and complex mathematical equations.
- Also includes features for creating animations with custom fonts, styles, and colors.
plotly.py
- Is a Python library used to create interactive data visualizations, built on the plotly JavaScript library that allows developers to create various interactive plots.
- Is designed to be easy to use and includes different resources and tools for creating high-quality visualizations.
- Includes support for complex data structures like pandas DataFrames and offers various customization options for fonts, styles, and colors.
seaborn
- Is a Python data visualization library based on Matplotlib, offering a high-level interface to create attractive and informative statistical graphics.
- Offers various plotting functions for visualizing various data types like continuous data, data distribution, and categorial data.
- Its the ability to create visually appealing plots with minimal effort and supports the customization of plot elements like axes, titles, legends, and labels.
moviepy
- Is a Python library for video editing, concatenations, cutting, video composting, title insertions, creation of custom effects, and video processing.
- Has the ability to add audio to video clips easily and offers various filters and audio effects like changing pitch and speed, adding sound effects, and adjusting volume.
- Includes support for creating animations like moving text, images, and shapes and allows users to export their video clips to different file formats.
termtosvg
- Is a Python library that allows users to record terminal sessions and save them as SVG animations.
- Produces clean-looking and lightweight still frames embeddable on the project page or animations.
- Includes support for recording multiple terminal sessions, allowing users to control the size and speed of the resulting animation.
altair
- Is a declarative statistical visualization library that can help you spend more time understanding your data and its meaning.
- Offers a simple syntax for creating different visualizations, like line charts, histograms, scatterplots, and bar charts.
- Its declarative syntax lets user's express visualizations as a series of high-level mappings between visual and data properties like color, size, and position.
PathPlanning
- Is a Python library used for path and motion planning applications designed to be accessible to beginners and experts with a straightforward API.
- Offers various algorithms for computing collision-free paths for drones, mobile robots, and manipulators in 2D and 3D environments.
- Also offers tools for trajectory generation, motion control, and obstacle avoidance and supports simulation and visualization of robot motion.
alive-progress
- Is a Python library for displaying spinners and progress bars in command-line applications designed to offer a customizable way of showing progress indicators for long-running processes or tasks.
- Supports for pausing and resuming progress indicators, nested spinners, and progress bars.
- Designed to be intuitive and simple with various default settings and a straightforward API for customizing the behavior and appearance of spinners and progress bars.
asciimatics
- Is a package for helping people create full-screen text UIs on any platform and offers a single cross-platform Python class to do all the low-level console functions.
- Includes cursor positioning, mouse input, screen scraping, colored/styled text, detecting and handling if the console resizes, and keyboard input like Unicode support.
- Is a Python library for creating text-based animations and user interfaces in the terminal.
pygal
- Is a Python library for creating interactive Scalable Vector Graphics (SVG) graphs and charts.
- Offers various tools for generating customizable charts, graphs, and high-quality for use in presentations, reports, and web applications.
- Includes built-in support for data/time axis labeling, responsive design, and integration with web frameworks and interactive charts elements.
GANimation
- Is a Python implementation of the GANimation research project, which offers various tools for generating animations from still images using Generative Adversarial Networks (GANs).
- Includes tools for augmenting and preprocessing input data, customizable GAN training parameters and architecture, and support for evaluating and visualizing GAN models.
- Offers various tools for fine-tuning GAN models and generating high-quality animations for various applications.
deep-motion-editing
- Offers advanced and fundamental functions to work with 3D character animations in deep learning with Pytorch.
- Is a Python implementation of the research project of the same name, which offers tools for editing the motion of human characters in video sequences using deep learning methods.
- Its ability to generate realistic, high-quality animations for various applications offers tools for fine-tuning the deep learning model and editing the generated motions to achieve the desired results.
geoplotlib
- Is a Python library for creating geographical maps and visualizations and offers an easy-to-use interface for creating maps with different data types, like polygons, heatmaps, lines, and points.
- Includes support for different tile providers and map projections, customizable styling options for data layers like size, transparency, and color.
- Designed for creating interactive maps and visualizations and is suitable for various applications like data analysis, presentation, and exploration.
Linux-Fake-Background-Webcam
- Is a Python library that will allow users to replace their webcam background with a custom video or image on Linux systems.
- Works by creating a virtual webcam device that can be selected as the input source in video conferencing applications, allowing users to appear as if they are in various environments and locations.
- Includes the ability to control the position and size of the custom background video or image and support for replacing the webcam background with a custom video or audio.
celluloid
- Is a Python library that offers a simple interface for creating visualizations and animations in Matplotlib
- Designed to make it easy for users to create animations without having to write to deal with low-level details and complex code.
- Includes a simple interface for adding and updating data in the animation, the ability to save the animation as an MP4 or GIF video file, and support for customizing the animation style and appearance.
FAQ
What are the best data visualizations for Python animation libraries?
The Python Animation libraries create amazing visuals that can move and change. Here are the best data visualization libraries:
- Matplotlib
- Bokeh
- Plotly
- Pygal
- Plotnine
- Seaborn
- Holoviews
Which animation library is most used by Python coders today?
Matplotlib is a powerful 2D plotting library. It supports various visualizations. It is used in the scientific and data analysis communities. The 'FuncAnimation' class provides its animation capabilities. It allows coders to create dynamic and interactive visualizations. Its popularity is due to its advanced development, clear documentation, and reliability. Other higher-level visualization libraries use it as the backend.
How can I create explanatory math videos using a Python animation library?
You can use a Python Animation library to make math videos that show concepts visually. You should follow the below steps:
- Choose a Python animation library
- Plan your content
- Write the Python code
- Animate with time
- Narrate or annotate
- Export the video
- Edit and visualize
- Share your video
What does the code for a basic Python animation look like?
You can make a simple animation in Python with different libraries. Many people like using the matplotlib library. Matplotlib, a strong Python library, can make plots and do basic animations.
Here's an example of a basic Python animation using matplotlib:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Function to update the plot in each animation frame
def update(frame):
# Clear the previous plot
plt.cla()
# Generate some data points for the animation
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x + 2*np.pi*frame/100)
# Plot the data
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Basic Python Animation')
plt.grid(True)
# Create a blank figure
fig, ax = plt.subplots()
# Create the animation with the update function, 100 frames, and 100ms delay between frames
animation = FuncAnimation(fig, update, frames=100, interval=100)
# If you want to save the animation as a video file, you can use the following line:
# animation.save('basic_animation.mp4', writer='ffmpeg', fps=30)
# Display the animation
plt.show()
This code creates a simple animation that displays a sine wave. The update function makes new data points and updates the plot in each animation frame. The FuncAnimation class controls the animation. It calls the update function many times with different frame values.
In this example, the animation has 100 frames with a delay of 100 milliseconds between frames.
To save the animation as a video file:
- Remove the comment from the animation.
- Save line.
- Make sure you have ffmpeg installed.
- Before running the code, ensure you have installed matplotlib in your Python setup. You can install it using pip install matplotlib.
Using an animation library, how can you make line charts with various colors in Python?
You can use different libraries in Python to make line charts with colors and animations. I will teach you how to use Matplotlib's FuncAnimation to animate graphs.
Here's a step-by-step guide:
#Install the required libraries (if you haven't already)
pip install matplotlib
# Import the necessary modules
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Generate your data: Create multiple datasets with different colors. For this example, let's consider two datasets, data1 and data2
x = np.linspace(0, 10, 100)
data1 = np.sin(x)
data2 = np.cos(x)
# Create a figure and an axis to plot the data
fig, ax = plt.subplots()
# Define the line objects for each dataset and set their properties
line1, = ax.plot([], [], color='red', label='Data 1')
line2, = ax.plot([], [], color='blue', label='Data 2')
# Define the initialization function for the animation
def init():
line1.set_data([], [])
line2.set_data([], [])
return line1, line2
# Define the update function for the animation
def update(frame):
line1.set_data(x[:frame], data1[:frame])
line2.set_data(x[:frame], data2[:frame])
return line1, line2
# Create the animation using FuncAnimation
frames = len(x)
animation = FuncAnimation(fig, update, frames=frames, init_func=init, blit=True)
# Display the animation or save it to a file (optional)
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Animated Line Chart with Different Colors')
plt.show()
This code makes a line chart that shows two datasets using different colors. You can customize the colors, data, and other properties per your requirements. To add more datasets, make new line objects and update their data in the update function.
Can FuncAnimation be used to animate 3D objects and 2D shapes in Python?
Yes, 'FuncAnimation' can animate both 3D objects and 2D shapes. But 'FuncAnimation' is a part of the Matplotlib library. It is primarily known for 2D plotting. Matplotlib's 3D plotting toolkit makes 3D objects, and visualizations come to life.
Are there any tips or tricks to improve creating animations with Python libraries?
To improve your animations, follow these helpful tips and tricks for efficient engineering. Here are some valuable tips to help you with it:
- Plan your animation
- Keep it simple
- Use subplots
- Choose the right library
- Optimize data processing
- Minimize redrawing
- Control animation speed
- Add labels and annotations
- User color thoughtfully
- Consider interactivity
- Test on a smaller subset
Can I find open-source projects to practice coding with a Python animation library?
Yes, there are many open-source projects available that use Python animation libraries. These resources help you practice animation libraries before starting your own project. Here are some places where you can find such projects:
- Matplotlib Examples Gallery
- GitHub Repositories
- Plotly Examples Gallery
- Kaggle Notebooks
- Bokeh Examples Gallery
- Data Science Blogs
- YouTube Tutorials
Flappy Bird is an arcade-style game. It was initially released as a mobile game while tapping the screen to make the bird fly. Later, the game's pc version was released, where the Bird will be controlled using the up key or the space bar. If Bird hits on the pipes or the screen edges, the game ends, and the player needs to restart. Flappy Bird can fly the Bird as far as you can without hitting a pipe. The player is tasked with navigating Faby through pairs of pipes with equally sized gaps placed at random heights. Try to play as long as possible, score as many points as you can!. Following are the steps to be followed for build Flappy Bird Game, 1. Graphics Setup 2. Game Logic 3. Creating Input Controls 4. Generating Sound effects & Display Scores 5. Multi-player
Multi-player
Flappy bird is a single-player game, but it's possible to have multiplayer by using below libraries. Players will play on their game field one who gets more scores will win the game.
Graphic Designs & Game logic
Graphic designs are used in a flappy game to build an image of the player (bird), background, pipe, base and for displaying messages. Game logic and Graphic designs are build by using below libraries.
Creating Input Controls
Key mapper is an open-source library that allows users to use a key or combination of keys to perform a specific action(fly), which can be used for navigating.
Sound effects & Scores
Sound effects are used while the bird hits the pipe, generating scores for every move of a bird and a Game over by sfb & FlapPyBird libraries . Using flairfly library, scores can be calculated by the number of pipes crossed.
The primary technologies for creating Web pages are HTML and CSS. HTML provides the page structure while CSS handles the visual layout.
HTML, which stands for "Hypertext Markup Language.", forms the foundation for defining the arrangement and content of web pages. HTML operates by utilizing a series of tags that mark specific elements within a page. CSS, which stands for Cascading Style Sheets, is a language employed for creating stylesheets that govern the arrangement and design of HTML documents.
This kit has some simple-to-use exercise in HTML/CSS to help someone new to Web Development to learn how to program in HTML/CSS and get started with their journey.
For a detailed tutorial on installing & executing the solution as well as learning resources including training & certification opportunities, please visit the OpenWeaver Community
Knowledge Resources for basics
Kit Solution Source
Support
If you need help using this kit, you may reach us at the OpenWeaver Community.
Dynamic Forms are nothing but one of the crucial parts of a web app. It plays a vital role in collecting data or information about the users. Developers are responsible to validate those input data in the form fields in order to provide a good user experience.
There are two types of forms inputs in React,
- Uncontrolled Component
- Controlled Component
To add multiple input fields dynamically in JavaScript,
- Creating a copy of a field group to be used as a template.
- Getting the container of the input fields.
- Set input fields id is based on the total number of form groups in the parent.
- addinput() - make sure this method adds to the button.
- At the end insert the input form before the end of the parent form.
The main purpose of the forms is to collect the required information or data in a meaningful fashion and logically for communication and pass to another entity. It is advisable to have a JavaScript function that handles the form submission and also has access to the form's user data. The traditional way to do this technique is called 'controlled components'. The benefits of forms are increased efficiency of employees and reduced volume of work. Instead of manually putting the data into the databases, we can automate the process by directing the data from the forms to the databases.
Here is an example of how you can add form fields dynamically in ReactJS:
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and Reactstrap libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm i reactstrap.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in index.js file(remove the earlier code from index.js).
- Open the terminal from IDE.
- npm start to run the file.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'how to add form fields dynamically in reactjs' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Reactstrap version-9.0.2.
Using this solution, we are able to add form fields dynamically in reactjs with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to add form fields dynamically in reactjs.
Dependent Libraries
You can also search for any dependent libraries on kandi like 'react' and 'reactstrap'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Bar graphs are pictorial representations of data. They display numerical or categorical data. The data in bar charts are represented as vertical or horizontal bars, where the bar's length depicts the measure of data. Bar charts are mostly used in Sales Management, Inventory Management or to compare frequencies, etc. We can use an array or a list of data items as the source for creating a bar chart.
For creating a bar chart in React, we use React-charts. They include:
- Chart
- Series Type Components
- Curve Functions
- Position Constants
- Grouping Constants
A standard and highly adaptable data model proposed on arrays of series and arrays of datums is used by React Charts. To materialize this structure, you may directly use data accessors or the model defaults.
- Series: It is a collection of related data points
- Datums: Datums is a set of react components used for display and input of attributes
For more information about bar charts using react-charts in ReactJS, refer to the code given below.
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we are using React, moment and React charts libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm i moment and npm i react-charts --force.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file.
- Command or remove the import statement of styles file.
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'Bar chart using react-charts in ReactJs' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Moment version-current.
- React-charts version-0.8.0.
Using this solution, we are able to create bar chart using react charts in reactjs with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to create bar chart using react charts in reactjs.
Dependent Library
You can also search for any dependent libraries on kandi like 'react', 'moment' and 'react-charts'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
A nested pie chart is a type of pie chart that uses many layers of nested rings to visualize and analyze data. It shows the relationship between parts of a whole or the composition of a particular group. The innermost circle represents the total sum of the data and each subsequent circle. It shows the proportion of the whole that each part contributes. For example, a nested pie chart can show the proportion of different types of fruit in a basket. It can also tell the proportion of students in a school by grade level.
We can visualize the different types of data with a nested pie chart are:
Numerical Data:
- Population by Age Group
- Expenditure by Category
- Budget Allocation by Department
- Annual Revenue by Region
- Cost of Living by City
Categorical Data:
- Brand Preferences by Gender
- Voter Turnout by Political Party
- Employee Satisfaction by Role
- Education Level by Country
- Job Satisfaction by Industry
Nested pie charts display hierarchical relationships between data in a visual form. The chart contains nested circles giving a circular statistical plot. It's where we can represent the plot from a level in the hierarchy. A different color represents each hierarchy level; the innermost circle is the highest.
Nested pie charts can create bar, pie, and line charts. The bar chart uses a hierarchical structure to compare many data points. It displays the relative proportions of each data point within the hierarchy. The line chart displays trends over time.
- X-Axis: The x-axis measures the categories, or groups, of data in a nested pie chart. It runs along the bottom of the chart and displays the labels for each data group.
- Y-Axis: The y-axis measures the size of each data group in a nested pie chart. It runs from the left side of the chart and displays the numerical values for each data group.
- Scale Axis: The scale axis helps measure each data group's relative size in a nested pie chart. It runs along the top or right side of the chart and displays the numerical values for each data group. Remembering that the scale axis should be consistent across all charts is important.
We can use different types of labels with a nested pie chart.
- Title Label: The title label identifies the chart and provides context for the data. It should explain the chart and give the reader an understanding of the data.
- Data Labels: Data labels identify the individual sections of the pie chart. These labels can be numerical values, percentages, or even words. The words that describe the values.
- Legend Labels: The legend labels identify the pie chart's different sections. These labels should explain what each section of the chart represents. They can be color-coded to identify the sections further.
Different types of layout options are available for a nested pie chart:
Stacked Layout:
The stacked layout shows the segments of the outer pie chart stacked on top. It offers a representation of the relative subcategory sizes within each main category.
Grouped Layout:
The grouped layout for a nested pie chart shows the segments of the outer pie chart grouped. It is useful for identifying the relationships between the subcategories as groupings. It makes comparing the relative subcategory sizes within each main category easier.
Nested Layout:
The nested layout for a nested pie chart shows the segments of the outer pie chart nested within each other. The nested segments make it easier to identify the size of each main category relative to the others. It is useful for identifying the relationships between the main and the subcategories.
For creating a nested pie chart:
Choose the right data type:
Gather the data needed to create the nested pie chart. This data should include the categories of information. It should also include the number of items in each category and the percentages of each category.
Design the chart correctly:
Once we gather the data and use a graphing program or software to create the chart, we set up the chart correctly, ensuring we nest the categories and label the data properly.
Add labels and axes:
Finally, add labels and axes to the chart to make it easier to understand. Be sure to label the category names, the numbers, and the percentages. Also, be sure to add a legend to the chart to explain the meanings of the colors.
We can use a nested pie chart to visualize data by following some points:
Determine the data you want to visualize and the most appropriate chart type. Nested pie charts are great for comparing categories within a whole. So, consider your research question when selecting the chart type. Choose a layout that conveys the data. Avoid using too many pies in one chart, as it can be hard to read. Instead, consider using many charts to differentiate the categories better. Add labels to each pie chart and the data points to identify the category or point in the chart. Make sure to add a title, legend, and other helpful information to the chart to make it easier to interpret. Use colors to differentiate the categories within the chart. Use a consistent color scheme throughout the chart and darker colors for categories. Consider adding a call-out box. It explains the differences between the categories within the chart. This will make it easier for viewers to understand the data.
A nested pie chart visualizes data. It allows the viewer to compare proportions and relationships. By nesting the pie charts, the viewer can identify if one variable is more or less important than another. This makes it quick to identify correlations and trends in the data. Additionally, the visual nature of the chart makes it easier to explain complex data sets.
Fig1: Preview of the Code.
Fig2: Preview of the output.
Code
In this solution, we are creating a nested pie chart using matplotlib.
Instructions
Follow the steps carefully to get the output easily.
- Install Jupyter Notebook on your computer.
- Open terminal and install the required libraries with following commands.
- Install numpy - pip install numpy.
- Install pandas - pip install pandas.
- Install matplotlib - pip install matplotlib.
- Copy the code using the "Copy" button above and paste it into your IDE's Python file.
- Remove the text from line number 17 to 28.
- Run the file.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for "Create a nested pie chart using matplotlib python" in kandi. You can try any such use case!
Dependent Libraries
If you do not have matplotlib or numpy that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the respective page in kandi.
You can search for any dependent library on kandi like matplotlib
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Python 3.9.6
- The solution is tested on matplotlib version 3.5.0
- The solution is tested on numpy version 1.21.4
- The solution is tested on pandas version 1.5.1
Using this solution, we are able to create a nested pie chart with matplotlib.
FAQ
What is a nested pie chart, and what are its applications?
A nested pie chart is a type of chart that uses many layers of concentric circles. It helps represent the relative value of different categories of data. It displays hierarchical data and compares parts of a whole. It can compare a variety of data sets. It can include the relative proportions of countries and the relative product sizes. Or it can include the relative components of an income.
How does a circular statistical plot differ from other kinds of plots?
A circular statistical plot is a circular graph showing relationships between variables. It differs from other plots because it uses angles instead of the typical x and y axes to display the data. This allows for efficient use of space and a more intuitive way of displaying the data. A circular statistical plot can show relationships between variables with a single graph.
Is it possible to create a donut chart using Python?
Yes, it is possible to create a donut chart using Python. Python offers various libraries, like Matplotlib, Seaborn, and Plotly. Additionally, several online resources help you create a donut chart. We can create a donut chart.
When should you use a bar chart over a nested pie chart for data visualization?
Bar is over nested pie charts when comparing values or emphasizing their differences. Bar charts make it easier to compare individual values or groups of values. They also enable viewers to see the data's range of values and trends.
What is the data intensity ratio when plotting with nested pie charts?
When plotting with nested pie charts, the data intensity ratio is 4:1. The inner circle should represent approximately 25% of the total data. It will be when the outer circle should represent the remaining 75%.
Are there any special libraries in Python that can help plot these charts?
Yes, several libraries in Python can help plot charts. Examples include Matplotlib, Plotly, Seaborn, Bokeh, and Pygal.
How do you create an outer circle when making a nested pie chart in Python?
To create an outer circle when making a nested pie chart in Python, you can use the Matplotlib library. You can use matplotlib.pyplot.pie() function and set the radius parameter to a value greater than 1. This will create an outer circle around the nested pie chart.
What tools can help Analyzing Data represented by Nested Pie Charts in Python?
- Matplotlib: Matplotlib helps create static, animated, and interactive visualizations. It is well-suited for analyzing data represented by nested pie charts. It allows users to customize their charts and add extra information.
- Seaborn: Seaborn is a Python data visualization library based on matplotlib. It provides an interface for creating interactive and publication-quality figures. It is useful for analyzing data from nested pie charts.
- Plotly: Plotly is an interactive and open-source data visualization library for Python. It provides an intuitive interface and powerful tools for creating and customizing figures. It is particularly well-suited for analyzing data represented by nested pie charts.
How do you use given data to create a Nested Pie Chart using Python?
We can create a nested Pie Chart with the help of the Matplotlib library. Here is an example of creating a Nested Pie Chart using the Matplotlib library:
- First, import the necessary libraries.
- Create the Nested Pie Chart using the Pie chart function.
- Load the data into a Pandas data frame.
- Finally, add a title and display the Nested Pie Chart.
Can I customize the ggplot2 library while making Nested Pie Chart in Python?
Customizing the ggplot2 library while making Nested Pie Charts in Python is possible. You can customize your charts to fit your needs using the customizing options. You can customize the underlying data structure. It can create custom functions to make your charts unique. It can be like labels, colors, sizes, and shapes.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Matplotlib is a popular Python 2D plotting library. It provides a powerful framework for creating animations using its `FuncAnimation` class. This functionality allows you to generate animated and interactive charts. It makes your visualizations more dynamic and engaging.
General steps to use FuncAnimation class:
- To begin, ensure you have Matplotlib installed with any necessary libraries. If you're using a virtual environment, create a new Python virtual environment. Then, we can install the required packages.
- Import the necessary libraries. Import `matplotlib.pyplot` as `plt` and `matplotlib.animation` as `animation`. Import other libraries for data manipulation specific to your project.
- Next, create the base graph or plot objects on which the animation will be built. For example, you can create a line plot, scatter plot, bar chart, or any other type of plot that suits your data. Set up the initial plot with empty data or any initial state you want for the animation.
- To define the animation, create a function animate. It will be invoked for each frame of the animation. The function should take a frame number argument, `frame,` which can update the plot for the next frame. Upgrade the plot objects based on the frame number inside the' animate' function. It creates the animation effect.
- To animate the plot, create an instance of the `FuncAnimation` class. Provide the figure object, the `animate` function, and any extra parameters required. This will create the actual animation object.
- Finally, display or save the resulting animation. If you want to display it, use the `plt.show()` function. If you prefer to save it as a file, use the `animation.save()` method with the appropriate writer.
Throughout the process, you have control over various aspects of the animation. You can customize the appearance of the animation to create sophisticated visualizations.
When working with large data, creating animations showcases time-series or time-dependent data. By adding motion to your plots, you can capture dynamic patterns. It changes that static charts may not convey.
The coding process for creating animations with Matplotlib is straightforward. It can be done in your preferred Python development environment. Jupyter Notebooks or integrated development environments can streamline the coding and testing process.
With its interactive and dynamic nature, animation functionality opens possibilities for various applications. It can be used for anything from physics simulations and art animations. It helps data visualizations that need an animated element.
Remember to consider the rendering backends and requirements specific to your project. For instance, if you create animated files, you have the necessary libraries installed. Adjust the code to match your desired output format and specifications.
How to Create animations in Matplotlib using the FuncAnimation class?
For making animated visualizations, Matplotlib's FuncAnimation class is a helpful resource. First, construct a figure and axis object. It helps plot your initial data before you can use FuncAnimation. The data in your plot is then updated by a function you write. This FuncAnimation function calls at predetermined intervals. It updates the data and provides a string of Artist objects representing the revised plot. You can refresh the information in your plot at predetermined intervals. It will provide the impression of motion or change over time.
The 'im' object in Matplotlib is an instance of the 'imshow' class used to display a 2D array as an image. The data shown in the image is updated for each animation frame using the set array method of the 'im' object.
We instruct FuncAnimation to update each frame rather than redrawing the full figure by returning from the animate function. Especially for large visualizations, this can lead to greater performance and smoother animations.
The FuncAnimation object contains the data required to produce and control the animation. It is returned by the create video function's return anim statement.
Preview of the output obtained when funcAnimation class is used.
Code
The im object in Matplotlib is an instance of the imshow class that is used to display a 2D array as an image. The data shown in the image is updated for each frame of the animation using the set array method of the im object.
We are instructing FuncAnimation to update only the im object on each frame rather than redrawing the full figure by returning im from the animate function. Especially for large and complicated visualisations, this can lead to greater performance and smoother animations.
The FuncAnimation object, which contains all the data required to produce and control the animation, is returned by the create video function's return anim statement.
Follow the steps carefully to get the output easily.
- Install Visual Studio Code in your computer.
- Install the required library by using the following commands
pip install matplotlib
pip install numpy
- If your system is not reflecting the installation, try running the above command by opening windows powershell as administrator.
- Open the folder in the code editor, copy and paste the above kandi code snippet in the python file.
- Remove the first line of the code.
- Run the code using the run command.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for "Create animations in Matplotlib using the FuncAnimation class" in kandi. You can try any such use case!
Dependent Libraries
If you do not have numpy and matplotlib that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the pages in kandi.
You can search for any dependent library on kandi like matplotlib.
Environment tested
- This code had been tested using python version 3.8.0
- numpy version 1.24.2 has been used.
- matplotlib version 3.7.1 has been used.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
FAQ
1. What is the Python 2D plotting library, and how can it be used to create animated and interactive charts?
The 2D plotting library provides a comprehensive set of functions. It helps in creating static and dynamic visualizations. It can create animated and interactive charts by leveraging the `FuncAnimation` class. It allows you to update plots for each frame and create engaging visual experiences.
2. How do I create an animated line plot with the Python 2D plotting library?
To create an animated line plot using the Python 2D plotting library (Matplotlib):
import matplotlib.pyplot as plt;
plt.plot(x, y);
plt.show()
Replace `x` and `y' with the appropriate data for the line plot and execute the code to display the animated line plot.
3. What is the animation framework of matplotlib, and what are its uses?
The animation framework provides functionality to create animated visualizations. It updates plot elements over time. It allows for the creation of dynamic and interactive charts. It enables the representation of time-dependent data, simulations, and other scenarios. It is where motion enhances data understanding, engagement, and storytelling.
4. What arguments does the animation function accept to work with matplotlib?
The `animation.FuncAnimation` function in Matplotlib accepts the following arguments:
- `fig`: The figure object or figure number to which the animation will be associated.
- `func`: The function that will be called for each animation frame.
- `frames`: The total number of frames in the animation.
- `init_func` (optional): A function that initializes the animation before the frames are drawn.
- `interval` (optional): The delay between frames in milliseconds.
- `repeat` (optional): Boolean value indicating whether the animation should repeat.
- `blit` (optional): Boolean value indicating whether to use blitting for faster updates.
5. Is there any Python module that needs to be imported for animating objects in matplotlib?
Yes, for animating objects, you need to import the matplotlib.animation module. This module provides the necessary classes and functions. It helps create and control animations within Matplotlib.
Fetching JSON array data from an API using React can be used in various contexts where you need to retrieve and display data from an external API in a React application. Some examples might include the following:
- a dashboard or reporting tool that makes use of a REST API to present data
- An application for data visualization or charting that shows current or past data
- An application for social networking or messaging that shows user data
- a retail or e-commerce website that displays product information or inventory from an API
You can use the fetch function, a built-in function for making HTTP queries, or a library like Axios to complete the request to fetch data from a JSON array from an API in a React application.
This pre-written code snippet will show you how to fetch data from a JSON file easily and consume it in your React project.
Steps-
- Declare a state in React to hold API data
- To retrieve API data and store the result, use a JS function
- On page load, add useEffect to the fetch API
Here's an example of how you might implement this:
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and Axios library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install axios.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Import libraries.
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'display data from jsonplaceholder api using react'in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Axios library version-0.26.1.
Using this solution, we are able to fetch Json array data from API using React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to fetch Json array data from API using React.
Dependent Library
You can also search for any libraries on kandi like 'react' and 'axios'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Pagination refers to breaking up a list of things into multiple pages that can be accessed via navigation links on a website or application. Pagination is a common technique for organizing and making it simpler to browse through displays containing vast numbers of objects.
Pagination can be implemented in several ways, such as client-side or server-side pagination. Client-side pagination requires loading all the data and then breaking it into pages on the client side. In contrast, server-side pagination includes requesting the server to obtain a specific data page. Pagination can be implemented in web applications using various components and libraries, such as the React Ultimate-Pagination component. A JavaScript package called React Ultimate-Pagination is used for pagination in React apps. It offers a pagination component that is adaptable, adjustable, and simple to add to a React app.
Here is how you can set up react ultimate pagination component using react pagination libraries.
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and React-ultimate-pagination libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm i react-ultimate-pagination.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in index.js file(remove the earlier code from index.js).
- Add export default statement at end of the code(like 'export default App;').
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'implementing pagination in react' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- React-Ultimate-Pagination version-current
Using this solution, we are able to set-up react ultimate pagination component with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to set-up react ultimate pagination component.
Dependent Libraries
You can also search for any dependent libraries on kandi like 'react' and 'react-ultimate-pagination'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
We can change the font color based on the background color in react by few different ways:
- We can use a library that offers practical functions, including color contrast and brightness, to choose the best font color based on the background color.
- We may manually determine the contrast ratio between the background color and the text’s color. If the contrast ratio is below a certain threshold, you can choose a different font color to improve the contrast and readability of the text. This can be done by using a library ‘contrast.js.’
- contrast.js: This is a library that helps in measuring the contrast between two colors. The contrast ratio gauges how simple it is to see text against a specific background color.
- We can use CSS ‘color’ function.
- color: This function allows you to use operations like lightening, darkening, and mixing to provide a color value that is generated from one or more other colors.
For more information about changing font color based on the background color in React, refer to the code given below
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and styled-component library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in index.js file(remove the earlier code from index.js) and refer demo for additional one file called style.js file.
- Add export default statement at end of the code(like 'export default App;').
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'change the font color based on background color in React' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Styled-components version-6.0.0.
Using this solution, we are able to change the font color based on background color in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to change the font color based on background color in React.
Dependent Library
You can also search for any dependent libraries on kandi like 'react' and 'styled-component'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
To create pie charts in a React application, you can use the react-highcharts library, which provides a React wrapper for the Highcharts library. Pie charts are a common way to present a brief composition summary or comparison. They continue to be a popular option for tiny datasets, even though they can be more challenging to read than column charts.
Highcharts is a popular library for creating interactive charts and graphs on the web. To create pie charts in a React application, you can use the react-highcharts library, which provides a React wrapper for the Highcharts library. There are several different charts available on Highcharts. Examples include bar charts, pie charts, line charts, spline charts, area charts, and so forth. Pies in highcharts can also be hollow, known as a donut chart. Additionally, this pie features an inside chart, creating a hierarchical picture. Pie chart with clickable individual slices that display more specific information.
Here is an example of how you can include a pie chart with ReactJS in your application:
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install --save highcharts
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in index.js file(remove the earlier code from index.js).
- Open the terminal from IDE.
- npm start to run the file.
Also you can refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for "Pie Charts in Reactjs" in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Highcharts version-16.0.2.
Using this solution, we are able to view pie charts in Reactjs with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to view pie charts in Reactjs.
Dependent Libraries
You can also search for any dependency on kandi like 'react' and 'highcharts'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Hooks in React are essential functions of JavaScript that we often use to separate the reusable part of a program from some of the more common components.
- useState in React can be defined as a hook that will allow you to have local/state variables to functional components (i.e.the, more common components). React uses callback functions to push the resourceful functions away so they will not execute on every render.
React does not allow us to use the callback function directly in the useState hook. For this purpose, we use a third hook called “useEffect.” It accepts two arguments:
- the first one is “<function>”
- and the second one is “<dependency>”
Dependency is an optional argument. Once all the changes are made in DOM (Document Object Model), the useEffect hook invokes the callback function if any value in the dependencies array has been altered. To use a callback function with useState, we use useEffect to hook those checks if there is any change in the dependencies array and then call the function.
Here is an example of how to use callback with useState hook in react;
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and use-state-with-callback.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install use-state-with-callback.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- There are two code snippets both are almost same you can use any one.
- Import React and use-state-with-callback libraries.
- Add export default statement at end of the code(like 'export default SomeOtherComponent;').
- Open the terminal from IDE.
- npm start to run the file.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'how to use callback with usestate hook in react' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- useState-with-callback version-3.0.2.
Using this solution, we are able to use callback with usestate hook in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to use callback with usestate hook in React.
Dependent Libraries
You can also search for any dependent library on kandi like 'react' and 'useState-with-callback'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
React can be used passing data from a parent component to a child component in various contexts where you must share data between components in a React application.
There are several ways you can pass data from a parent component to a child component in React. Here are a few options:
- Pass the data as props: You can transfer data as props from the parent component to the child component (short for "properties"). When rendering the child component, you can provide the data from the parent component as an attribute, and the child component can access the data as a prop.
- Use the context API: Instead of manually passing props at each level, you may utilize the context API to convey data through the component tree.
- Use a state management library: To store and communicate data throughout your application, you can use a state management library like Redux or MobX. Using these libraries, you can retrieve your data from any program component and store it in a global store.
Your approach will rely on your unique requirements and application design.
Using React, the following code shows how to pass data as props from a parent component to a child component:
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and React-uikit-button libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install react-uikit-button --save.
- Open the folder in IDE.
- Copy the code using "copy" button above then create a file in the name of parent.js and paste it in parent.js file.(refer demo for additional files).
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'how to pass data from parent to child component using ReactJs' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- React-uikit-button version: current.
Using this solution, we are able to pass the data from parent to child component using ReactJs with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to pass the data from parent to child component using ReactJs.
Dependent Libraries
You can also search for any dependent libraries on kandi like 'react' and 'react-uikit-button'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Infinite Scrolling is nothing but a listing page design approach that loads content continuously as the user scrolls up and down and it eliminates the need for pagination breaking content up into multiple pages.
One of the simplest ways to use a library like react-infinite-scroll-component and this library provides a component that will trigger an event when the user scrolls to the bottom of the page. We can then use this event to load more content or information. Using built-in functions that React provides is also another way to implement this operation. Infinite scroll engages the users by boosting their performance and keeping viewers on the page for as long as possible. Users don't want to wait for pages to load because infinite scrolling can provide a better experience for the users. For example, the first page is only loaded at the time we entered the first time but the next page is loaded as soon as the user scrolls down through content or information.
React also has some built-in methods that we can use to implement an infinite scroll. In those built-in methods, componentDidUpdate is the first method. Then Rect calls this method after its updated a component. We can use this method to check if the user has scrolled to the bottom of the content or page and if so, load more data.
Here is an example of how you can implement Infinite Scrolling in a scrollable component on the page:
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and Infinitescroll libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install infinite-scroll.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Import libraries.
- Open the terminal from IDE.
- npm start to run the file.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for ''implementing infinitescroll in react' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- InfiniteScroll version-current.
Using this solution, we are able to create infinitescroll in a scrollable component on a page in react with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to create infinitescroll in a scrollable component on a page in react.
Dependent Library
You can also search for any dependent libraries on kandi like 'react' and 'infinitescroll'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Trending Discussions on User Interface
Why Metamask if web3.js can interact directly with ganache?
Is it possible to save several values to a button?
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
How to dynamically define Headers and Settings for UWP NavigationView's menu, using C++/winRT?
With Stripe API, How To Get session_id of Checkout Session That Created a payment_intent Object, From payment_intent.succeeded Webhook
Is it safe to store, access and HTMLElement objects directly inside an object, vs. relying on CSS selectors?
How to increase height of jQueryUI selectmenu?
Is a work manager good for these situations?
Data exchange between websocket clients and server
Register all inputs inside a multi-page data table
QUESTION
Why Metamask if web3.js can interact directly with ganache?
Asked 2022-Mar-30 at 17:55I am new to blockchain app development, I saw a project where ganache accounts are imported into Metamask, then web3.js is used to access and print those accounts and balances on Frontend (user interface).
If web3.js can directly access ganache blockchain accounts and balances, why do we need Metamask in between?
ANSWER
Answered 2022-Feb-08 at 09:11If web3.js can directly acccess ganache blockchain accounts and balances, why we need metamask in between?
In this case, you don't need MetaMask to sign the transaction, as the node (Ganache) holds your private key.
But in a public environment (testnets and mainnet), the node doesn't hold your private key, so you'd need to sign the transaction using MetaMask (or any other tool that holds the private key).
QUESTION
Is it possible to save several values to a button?
Asked 2022-Mar-08 at 02:57Traditionally buttons are designed to save only ONE single value, eg:
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6
For instance, in the above HTML
code, when a user clicks on the Primary button, an alert with the word Love will pop up!
For (UI/UX)User Interface/Experience purposes, I need to design a button that can hold several values and NOT just one value. This is because I plan on coupling a click event to the button to send/post all stored values.
The much desired code would be something like the code below:
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6<button type="button" value="Love", value2="Love",
7value3="Love" onclick="fetchValue(this)"> Primary </button>
8
Is there someone who might know how to resolve this or even a better solution to my problem?
Thanks in advance
ANSWER
Answered 2022-Mar-07 at 15:34You can use data
attributes for additional values.
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6<button type="button" value="Love", value2="Love",
7value3="Love" onclick="fetchValue(this)"> Primary </button>
8function fetchValue(_button){
9 alert(`${_button.value} ${_button.dataset.value2}`);
10}
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6<button type="button" value="Love", value2="Love",
7value3="Love" onclick="fetchValue(this)"> Primary </button>
8function fetchValue(_button){
9 alert(`${_button.value} ${_button.dataset.value2}`);
10}<button type="button" value="Love" data-value2="you" onclick="fetchValue(this)"> Primary </button>
QUESTION
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
Asked 2022-Feb-13 at 16:57I am taking an uploaded image from the user and then sending it to a YOLO model which then returns me an image.
I want to store that returned image in my Local Directory and then display it on the user interface.
This is the Code of views.py
that takes in an image and sends it to the Yolo Model,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13
This is the function of YOLO Model that uses OpenCV to read the image (Image is sent as argument to the function) and then returns that image,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79
On this line,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79filePathName = fs.save(fileObj.name + "_result", img)
80
I am getting this following error,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79filePathName = fs.save(fileObj.name + "_result", img)
80'numpy.ndarray' object has no attribute 'read'
81
I am not sure how can I resolve this. I tried searching how can I store OpenCV Modified file usnig FileSystemStorage but found nothing of help. Can anyone help me regarding this?
ANSWER
Answered 2022-Feb-13 at 16:57You can use the imwrite
function of cv2
library to store your files in the local directory, i.e.,
In your case, simply do this,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79filePathName = fs.save(fileObj.name + "_result", img)
80'numpy.ndarray' object has no attribute 'read'
81img = detect_image(testimage)
82cv2.imwrite(fileObj.name+"_result.jpg", img=img)
83
QUESTION
How to dynamically define Headers and Settings for UWP NavigationView's menu, using C++/winRT?
Asked 2022-Feb-02 at 17:01I'm working on a cross-platform project in C++ generating the UI dynamically, and I am struggling with C++/winRT UWP NavigationView on two problems:
- When defining a NavigationViewItemHeader, the resulting header title doesn't show in the navigation menu, the space remains empty,
- When trying to update the SettingsItem of the navigation menu, the value of the Settings navigation item is nullptr as returned by SettingsItem().
Here is the code I wrote for generating the menu from a list of items managed independently from the host (e.g. Windows):
1bool
2CANavigationView::UpdateHostView( void )
3{
4 TNavigationItemPtr item;
5 TIndex index;
6
7 if( _hostViewUpdateNeeded == false )
8 return false;
9
10 Windows::UI::Xaml::Controls::NavigationViewItemBase hItem( nullptr );
11 Windows::UI::Xaml::Controls::TextBlock hText( nullptr );
12 winrt::hstring hTag;
13
14 // Remove all navigation items from the current host view:
15 _hostNavigationView.MenuItems().Clear();
16 _hostNavigationView.IsSettingsVisible( false );
17
18 // Build the navigation menu items:
19 for( index = 0; index < _navigationItems.CountOfItems(); index++ )
20 {
21 item = * _navigationItems.GetItemAtIndex( index );
22
23 if( item->identifier == kSettingsItem )
24 {
25 _hostNavigationView.IsSettingsVisible( true );
26 hText = Windows::UI::Xaml::Controls::TextBlock();
27 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
28 hText.Text( hTag );
29// Issue #1 : cannot access to the Settings item
30// _hostNavigationView.SettingsItem().as< Windows::UI::Xaml::Controls::NavigationViewItem >().Content( hText );
31// SettingsItem() returns nullptr...
32 }
33 else
34 {
35 switch( item->type )
36 {
37 case eNavigationHeader:
38 hItem = Windows::UI::Xaml::Controls::NavigationViewItemHeader();
39 hText = Windows::UI::Xaml::Controls::TextBlock();
40 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
41 hText.Text( hTag );
42// Issue #2: The header's title is not displayed
43 hItem.Content( hText );
44 _hostNavigationView.MenuItems().Append( hItem );
45 break;
46
47 case eNavigationSeparator:
48 hItem = Windows::UI::Xaml::Controls::NavigationViewItemSeparator();
49 _hostNavigationView.MenuItems().Append( hItem );
50 break;
51
52 case eNavigationItem:
53 hItem = Windows::UI::Xaml::Controls::NavigationViewItem();
54 CSString::ConvertToUIString( CAUIElement::GetStringFromUIIdentifier( item->identifier ), & hTag );
55 hItem.Tag( winrt::box_value( hTag ) );
56 hText = Windows::UI::Xaml::Controls::TextBlock();
57 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
58 hText.Text( hTag );
59 hItem.Content( hText );
60 hItem.as< Windows::UI::Xaml::Controls::NavigationViewItem>().Icon( GetHostIcon( item->icon ) );
61 _hostNavigationView.MenuItems().Append( hItem );
62 break;
63
64 default:
65 break;
66 }
67 }
68 }
69
70 _hostViewUpdateNeeded = false;
71
72 return true;
73}
74
As I'm using my own string format (I'm stuck in old C++ standards...) and I18N support, I need to first convert the UTF8 string to the host (here Windows) before setting the value of the text block, using the hTag variable of type hstring. In debugging mode, the text is well transcoded in the hstring format...
What is puzzling me is the fact that both NavigationSeparator and NavigationItem cases are working fine, in line with the official Microsoft documentation (including the Tag for menu event handling and Icon setting for NavigationViewItem).
I understand this is not the "mainstream XAML way" of working on UWP user interface but so far the approach is working well on other UI elements.
Here is a screenshot of the navigation view with the empty spaces for the headers:
Also, in the example above, I logged the number of menu items in the host navigation view (_hostNavigationView.MenuItems().Size()) and got 7 as a result, which is correct...
At last, here's the detailed log I'm generating in DEBUG mode:
1bool
2CANavigationView::UpdateHostView( void )
3{
4 TNavigationItemPtr item;
5 TIndex index;
6
7 if( _hostViewUpdateNeeded == false )
8 return false;
9
10 Windows::UI::Xaml::Controls::NavigationViewItemBase hItem( nullptr );
11 Windows::UI::Xaml::Controls::TextBlock hText( nullptr );
12 winrt::hstring hTag;
13
14 // Remove all navigation items from the current host view:
15 _hostNavigationView.MenuItems().Clear();
16 _hostNavigationView.IsSettingsVisible( false );
17
18 // Build the navigation menu items:
19 for( index = 0; index < _navigationItems.CountOfItems(); index++ )
20 {
21 item = * _navigationItems.GetItemAtIndex( index );
22
23 if( item->identifier == kSettingsItem )
24 {
25 _hostNavigationView.IsSettingsVisible( true );
26 hText = Windows::UI::Xaml::Controls::TextBlock();
27 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
28 hText.Text( hTag );
29// Issue #1 : cannot access to the Settings item
30// _hostNavigationView.SettingsItem().as< Windows::UI::Xaml::Controls::NavigationViewItem >().Content( hText );
31// SettingsItem() returns nullptr...
32 }
33 else
34 {
35 switch( item->type )
36 {
37 case eNavigationHeader:
38 hItem = Windows::UI::Xaml::Controls::NavigationViewItemHeader();
39 hText = Windows::UI::Xaml::Controls::TextBlock();
40 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
41 hText.Text( hTag );
42// Issue #2: The header's title is not displayed
43 hItem.Content( hText );
44 _hostNavigationView.MenuItems().Append( hItem );
45 break;
46
47 case eNavigationSeparator:
48 hItem = Windows::UI::Xaml::Controls::NavigationViewItemSeparator();
49 _hostNavigationView.MenuItems().Append( hItem );
50 break;
51
52 case eNavigationItem:
53 hItem = Windows::UI::Xaml::Controls::NavigationViewItem();
54 CSString::ConvertToUIString( CAUIElement::GetStringFromUIIdentifier( item->identifier ), & hTag );
55 hItem.Tag( winrt::box_value( hTag ) );
56 hText = Windows::UI::Xaml::Controls::TextBlock();
57 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
58 hText.Text( hTag );
59 hItem.Content( hText );
60 hItem.as< Windows::UI::Xaml::Controls::NavigationViewItem>().Icon( GetHostIcon( item->icon ) );
61 _hostNavigationView.MenuItems().Append( hItem );
62 break;
63
64 default:
65 break;
66 }
67 }
68 }
69
70 _hostViewUpdateNeeded = false;
71
72 return true;
73}
74DBG-[000002686A230710]CANavigationView::UpdateDisplayedLanguage() {
75 DBG-[000002686A230710]CANavigationView::UpdateHostView() {
76 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 0, type 2
77 DBG-[000002686A230710]CANavigationView::UpdateHostView() Header case: Reference Library
78 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 1, type 1
79 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
80 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 2, type 1
81 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
82 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 3, type 1
83 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
84 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 4, type 3
85 DBG-[000002686A230710]CANavigationView::UpdateHostView() Separator case
86 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 5, type 2
87 DBG-[000002686A230710]CANavigationView::UpdateHostView() Header case: Project Library
88 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 6, type 1
89 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
90 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 7, type 1
91 DBG-[000002686A230710]CANavigationView::UpdateHostView() Settings case
92 DBG-[000002686A230710]CANavigationView::UpdateHostView() Value of SettingsItem(): 0000000000000000
93 DBG-[000002686A230710]CANavigationView::UpdateHostView() Count of menu items for the navigation view: 7 (8)
94 DBG-}
95DBG-}
96
Your help in solving those two issues would be greatly appreciated !
Best regards,
Arnaud
ANSWER
Answered 2022-Feb-02 at 11:34Dynamic Headers/Footers enable different grouping options in reports, such as "By Location" or "By Location By System": Note that the words "Report Definitions" are circled above. Although reports can have up to three Dynamic Headers/Footers, some reports only have one or two Dynamic Groups.
QUESTION
With Stripe API, How To Get session_id of Checkout Session That Created a payment_intent Object, From payment_intent.succeeded Webhook
Asked 2022-Jan-31 at 22:04I am working on developing and testing a Stripe integration, written in PHP, and it's working beautifully. I can create sessions, redirect to the checkout form, and when the payments are complete it sends an event to my webhhook script, which successfully processes the information about the payment going through.
When I create a session, I store the data about the form filled out on my site, in a database, and when the payment goes through, I store information in a different table, which is great.
The problem I'm having is that I don't know how to link up the information about the successful payment, with the session that generated it.
Linking up these data is essential to me, because I want to track which sessions actually result in successful payments, so that I can analyze the flow of the user interface and track conversion rates and analyze factors that lead to abandonment of the checkout session.
In some cases, it is easy to link these things up. For example, if there's only one session generated and one successful payment, associated with a given email in a given time-frame, I can just link them up. The problem is that I want to be able to deal with the (likely common) scenario where a person creates multiple sessions and abandons them. I cannot link the payment to the most recent session associated with the email, in this scenario, because it's possible that a single customer would create two sessions, but complete the payment on the first, earlier-created session.
I can't figure out how to access the session_id from the payment_intent object that is returned to my webhook. Some thoughts I have had about how to possibly approach this include:
- Listening for some other event in my webhook script, that occurs, that would possibly allow me to link the two records.
- Passing metadata to the session, such as a uniquely-generated ID, and then accessing that same metadata from the payment_intent object. However I cannot figure out from reading the Stripe documentation how metadata works and even if the metadata is passed from the session to the payment_intent object (the documentation does not explicitly state this or explain it, and the fact that the session_id is not passed makes me wonder if the metadata would be passed at all). I would prefer not to do this solution because it would require the additional step of generating a unique ID before generating the session, which would require more work on my end and also make my code more complex and involve more database calls and more potential steps that can go wrong (currently I am generating the session and then storing the information in response to the successful creation of the session), but I could tolerate it if there are really no better options.
I would like to follow "best practices" here, but it's not clear to me how Stripe intends people to link up or access the data, or if this is perhaps an oversight on their end.
If you give me example code I would prefer seeing it in PHP if possible but you don't need to show me any code at all; just giving me an abstract or general idea of how to accomplish this would be sufficient and I could come up with the coding details on my own.
ANSWER
Answered 2021-Nov-10 at 00:01The payment_intent.succeeded
event gives you the PaymentIntent ID. You can use the CheckoutSessions "list" endpoint [0] to get the CheckoutSession that used that PaymentIntent ID by passing the payment_method
parameter.
[0] https://stripe.com/docs/api/checkout/sessions/list#list_checkout_sessions-payment_intent
QUESTION
Is it safe to store, access and HTMLElement objects directly inside an object, vs. relying on CSS selectors?
Asked 2022-Jan-22 at 09:00I have a vanilla Javascript class that builds a bunch of HTML, essentially a collection of related HTMLElement objects that form the user interface for a component, and appends them to the HTML document. The class implements controller logic, responding to events, mutating some of the HTMLElements etc.
My gut instinct (coming from more backend development experience) is to store those HTMLElement objects inside my class, whether inside a key/value object or in an array, so my class can just access them directly through native properties whenever it's doing something with them. But everything I look at seems to follow the pattern of relying on document selectors (document.getElementById
, getElementsByClassName
, etc etc). I understand the general utility of that approach but it feels weird to have a class that creates objects, discards its own references to them, and then just looks them back up again when needed.
A simplified example would look like this:
1<html>
2<body>
3<script>
4/* Silly implementation of the "Concentration" memory match game.
5 This is just a S/O example but it should actually work =P
6 */
7
8class SymbolMatchGame {
9
10 constructor(symbolsArray) {
11 this.symbols = symbolsArray.concat(symbolsArray); // we want two of every item
12 this.allButtons = [];
13 this.lastButtonClicked = null;
14 }
15
16 shuffle() {
17 for (let i = this.symbols.length - 1; i > 0; i--) {
18 const j = Math.floor(Math.random() * (i + 1));
19 const temp = this.symbols[i];
20 this.symbols[i] = this.symbols[j];
21 this.symbols[j] = temp;
22 }
23 }
24
25 build(parentElement) {
26 document.body.innerHTML = '';
27 this.shuffle();
28 const rowSize = Math.floor(Math.sqrt(this.symbols.length));
29 for (let i = 0; i < this.symbols.length; i++) {
30 const button = document.createElement('input');
31 button.type = 'button';
32 button.setAttribute('secret-value', this.symbols[i]);
33 button.value = ' ';
34 button.onclick = (event) => this.turnOver(event);
35 this.allButtons.push(button);
36 document.body.appendChild(button);
37 if ((i+1) % rowSize === 0) {
38 const lineBreak = document.createElement('br');
39 document.body.appendChild(lineBreak);
40 }
41 }
42 }
43
44 turnOver(event) {
45 const button = event.target;
46 if (this.lastButtonClicked === null) {
47 this.allButtons.forEach(button => button.value = button.disabled ? button.value : ' ');
48 this.lastButtonClicked = button;
49 } else if (button === this.lastButtonClicked) {
50 button.value = ' ';
51 this.lastButtonClicked = null;
52 } else {
53 if (button.getAttribute('secret-value') === this.lastButtonClicked.getAttribute('secret-value')) {
54 console.log('Match found!');
55 button.disabled = true;
56 this.lastButtonClicked.disabled = true;
57 } else {
58 console.log('No match!');
59 }
60 this.lastButtonClicked = null;
61 }
62 button.value = button.getAttribute('secret-value');
63 if (this.gameIsSolved()) {
64 alert('You did it! Game will reset.')
65 this.build();
66 }
67 }
68
69 gameIsSolved() {
70 const remainingButtons = game.allButtons.filter(button => !button.disabled)
71 return remainingButtons.length === 0;
72 }
73
74}
75
76const alphabetArray = Array.from(Array(8).keys()).map(k => String.fromCharCode(k+65));
77game = new SymbolMatchGame(alphabetArray);
78game.build();
79</script>
80</body>
81</html>
82
(Note: I'm not expecting you to examine this code in detail; just illustrating what I mean when I talk about storing element references in the class and accessing them directly instead of via document.get*
lookups)
I don't want this to be a style/"best practice" question that isn't appropriate for S/O, so I'm more looking for concrete information about whether my approach actually works the way I think it does. My question: what are the implications or side effects of what I'm doing? Is storing references to created elements inside my class instead of of a "just in time" document.get*
lookup every time I want to access or modify them unsafe in some way, prone to side effects or stale references, or otherwise lacking implicit guarantees about document state, that might break things on me?
ANSWER
Answered 2022-Jan-22 at 09:00In general, you should always cache DOM elements when they're needed later, were you using OOP or not. DOM is huge, and fetching elements continuously from it is really time-consuming. This stands for the properties of the elements too. Creating a JS variable or a property to an object is cheap, and accessing it later is lightning-fast compared to DOM queries.
Many of the properties of the elements are deep in the prototype chain, they're often getters, which might execute a lot of hidden DOM traversing, and reading specific DOM values forces layout recalculation in the middle of JS execution. All this makes DOM usage slow. Instead, create a simplified JavaScript model of the page, and store all the needed elements and values to the model whenever possible.
A big part of OOP is just keeping up states, that's the key of the model too. In the model you keep up the state of the view, and access the DOM only when you need to change the view. Such a model will prevent a lot of "layout trashing", and it allows you to bind data to elements without actually revealing it in the global namespace (ex. Map object is a great tool for this). Nothing beats good encapsulation when you've security concerns, it's an effective way ex. to prevent self-XSS. Additionally, a good model is reusable, you can use it where ever the functionality is needed, the end-user just parametrizes the model when taken into use. That way the model is almost independent from the used markup too, and can also be developed independently (see also Separation of concerns).
A caveat of storing DOM elements into object properties (or into JS variables in general) is, that it's an easy way to create memory leaks. Such model objects are usually having long life-time, and if elements are removed from the DOM, the references from the object have to be deleted as well in order to get the removed elements being garbage-collected.
In practice this means, that you've to provide methods for removing elements, and only those methods should be used to delete elements. Additionally to the element removal, the methods should update the model object, and remove all the unused element references from the object.
It's notable, that when having methods handling existing elements, and specifically when creating new elements, it's easy to create variables which are stored in closures. When such a stored variable contains references to elements, they can't be removed from the memory even with the aforementioned removing methods. The only way is to avoid creating these closures from the beginning, which might be a bit easier with OOP compared to other paradigms (by avoiding variables and creating the elements directly to the properties of the objects).
As a sidenote, document.getElementsBy*
methods are the worst possible way to get references to DOM elements. The idea of the live collection of the elements sounds nice, but the way how those are implemented, ruins the good idea.
QUESTION
How to increase height of jQueryUI selectmenu?
Asked 2022-Jan-04 at 13:00How can I increase the height of a select menu styled with jQuery's user interface? I want to increase the height of the actual element, not the height of the dropdown menu of options that appears when you click it (there are a few answers on the site already for that). Basically, I want the menu to look squared, almost like a button instead.
I tried setting the height at the moment of applying the UI to the element in javascript. However, any height value I use seems to be ignored:
1$(document).ready(function() {
2
3 let testSelect = document.createElement('select');
4 let firstOption = document.createElement('option');
5 firstOption.text = 'blablablabla...';
6 firstOption.defaultSelected = true;
7 testSelect.appendChild(firstOption);
8
9 document.getElementById('testDiv').appendChild(testSelect);
10 $(testSelect).selectmenu({height: '50%'}); // no matter what value of height I use, the menu does not change
11
12 testButton = document.createElement('button');
13 testButton.innerHTML = 'Like this example button';
14 $(testButton).button();
15 document.getElementById('testDiv').appendChild(testButton); // I want the select menu to look similar to a button like this
16
17});
1$(document).ready(function() {
2
3 let testSelect = document.createElement('select');
4 let firstOption = document.createElement('option');
5 firstOption.text = 'blablablabla...';
6 firstOption.defaultSelected = true;
7 testSelect.appendChild(firstOption);
8
9 document.getElementById('testDiv').appendChild(testSelect);
10 $(testSelect).selectmenu({height: '50%'}); // no matter what value of height I use, the menu does not change
11
12 testButton = document.createElement('button');
13 testButton.innerHTML = 'Like this example button';
14 $(testButton).button();
15 document.getElementById('testDiv').appendChild(testButton); // I want the select menu to look similar to a button like this
16
17});<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
18<script type="text/javascript" src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
19<link rel="stylesheet" href="http://code.jquery.com/ui/1.13.0/themes/redmond/jquery-ui.css">
20
21<div id="testDiv" style="width:100px; height:100px;"></div>
ANSWER
Answered 2022-Jan-04 at 13:00you forget to use .css()
function to add the css of height. add .css(height:100px)
and then you will get your height
QUESTION
Is a work manager good for these situations?
Asked 2022-Jan-02 at 00:08I'm developing some features that need to run in the background with a UI update like creating a file from the input stream and notifying the user after it's finished
After trying the work manager for this task. It works well, but is it a good option in your opinion?
Note: I am very interested in updating the user interface during the process and as you know async task deprecated
ANSWER
Answered 2022-Jan-02 at 00:08Yes. Initially, WorkManager
was a library for managing defferable background work. Now however, WorkManager
is a recommended solution for any persistent work, that is, the work that must be completed - no matter if the application process is stopped, or even the device is rebooted. From version 2.3.0-alpha01
, WorkManager
provides first-class support for setting and observing intermediate progress for workers. Updatig the user interface is exactly what this feature can be used for.
For me the easiest way to reason about WorkManager is an extension of your app scopes:
Activity
Scope - the works lives untilonDestroy
lifecycle eventViewModel
Scope - the works lives as long as ViewModel. If you navigate away - the work is stoppedApplication
Scope (eg. Coroutine'sGlobalScope
) - the work lives as long as applcation process. If the user ends the app process in task manager or the system kills it - the work is lostWorkManager
- the work survives process death and device reboot. It is persisted with help of Room DB under the hood, so that you can continue the work after your application process was restarted.
QUESTION
Data exchange between websocket clients and server
Asked 2021-Dec-20 at 01:50I have a system that has a fastAPI server, a python client implemented on Raspberry and Javascript clients for the user interface. Data is sent from python client to server then forwarded to Js client and vice versa. I established the connection between the server and each type of client but when sending from a client-side to the server, it just send back to that client and the rest ones receive nothing. What is the proper way to deal with this problem? Hope for your help. Thanks.
ANSWER
Answered 2021-Dec-20 at 01:50The problem with websocket is it doesn't support broadcasting. You can store somewhere list of connected clients and iterate over them to send a message
1CLIENTS = set()
2async def broadcast():
3 while True:
4 await asyncio.gather(
5 *[ws.send("woof") for ws in CLIENTS],
6 return_exceptions=False,
7 )
8 await asyncio.sleep(2)
9
10asyncio.create_task(broadcast())
11
12async def handler(websocket, path):
13 CLIENTS.add(websocket)
14 try:
15 async for msg in websocket:
16 pass
17 finally:
18 CLIENTS.remove(websocket)
19
20start_server = websockets.serve(handler, ...)
21
22asyncio.get_event_loop().run_until_complete(start_server)
23asyncio.get_event_loop().run_forever()
24
QUESTION
Register all inputs inside a multi-page data table
Asked 2021-Dec-17 at 16:15I have a datatable in which I've added checkboxes for my users to select various options. Unfortunately, the only inputs that shiny seems to see are ones that have been displayed in the table. So if I have multiple pages, I'm only able to see the first 10 inputs.
In the example below, I've printed all of the inputs that I can see registered above the datatable object. At the moment, I only see the first 10 inputs (A - J). I'd like to be able to see all 26 when the table first loads (without having to toggle through the pages).
In my actual application, I have multiple columns of checkboxes, so row selection wouldn't be sufficient. Any tips or suggestions on how to register all 26 inputs at once?
1library(shiny)
2library(DT)
3
4shinyInput <- function (FUN, id_base, suffix, label = "", ...)
5{
6 inputId <- paste0(id_base, suffix)
7 args <- list(...)
8 args <- c(list(label = label), args)
9 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
10 rv <- character(length(inputId))
11 for (i in seq_along(rv)) {
12 this_arg <- lapply(args, `[`, i)
13 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
14 rv[i] <- as.character(ctrl)
15 }
16 rv
17}
18
19X <- data.frame(id = LETTERS,
20 selected = sample(c(TRUE, FALSE),
21 size = length(LETTERS),
22 replace = TRUE))
23
24X$IsSelected <-
25 shinyInput(
26 shiny::checkboxInput,
27 id_base = "new_input_",
28 suffix = X$id,
29 value = X$selected
30 )
31
32shinyApp(
33 ui = fluidPage(
34 verbatimTextOutput("value_check"),
35 textOutput("input_a_value"),
36 DT::dataTableOutput("dt")
37 ),
38
39 server = shinyServer(function(input, output, session){
40
41 Data <- reactiveValues(
42 X = X
43 )
44
45 output$value_check <-
46 renderPrint({
47 sort(names(input))
48 })
49
50 output$dt <-
51 DT::renderDataTable({
52
53
54 DT::datatable(X,
55 selection = "none",
56 escape = FALSE,
57 filter = "top",
58 #rownames = FALSE,
59 class = "compact cell-border",
60 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
61 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
62 })
63 })
64)
65
This next example is a bit more complex, but illustrates a bit more of the motivation for the question. It seems the biggest issue is that I would like to utilize buttons such as "select all." Additionally, I'm not processing any actions immediately when a box is interacted with. Instead, the user makes their selections, and the selections are not saved until the "Save Selections" button is clicked.
What is happening is I click on the "Select All" button, and it checks all of the boxes for inputs that have been drawn already. If I've only viewed the first page of the table, it updates only those inputs, and none of the inputs on the next few pages. This is really the behavior I need to change.
1library(shiny)
2library(DT)
3
4shinyInput <- function (FUN, id_base, suffix, label = "", ...)
5{
6 inputId <- paste0(id_base, suffix)
7 args <- list(...)
8 args <- c(list(label = label), args)
9 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
10 rv <- character(length(inputId))
11 for (i in seq_along(rv)) {
12 this_arg <- lapply(args, `[`, i)
13 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
14 rv[i] <- as.character(ctrl)
15 }
16 rv
17}
18
19X <- data.frame(id = LETTERS,
20 selected = sample(c(TRUE, FALSE),
21 size = length(LETTERS),
22 replace = TRUE))
23
24X$IsSelected <-
25 shinyInput(
26 shiny::checkboxInput,
27 id_base = "new_input_",
28 suffix = X$id,
29 value = X$selected
30 )
31
32shinyApp(
33 ui = fluidPage(
34 verbatimTextOutput("value_check"),
35 textOutput("input_a_value"),
36 DT::dataTableOutput("dt")
37 ),
38
39 server = shinyServer(function(input, output, session){
40
41 Data <- reactiveValues(
42 X = X
43 )
44
45 output$value_check <-
46 renderPrint({
47 sort(names(input))
48 })
49
50 output$dt <-
51 DT::renderDataTable({
52
53
54 DT::datatable(X,
55 selection = "none",
56 escape = FALSE,
57 filter = "top",
58 #rownames = FALSE,
59 class = "compact cell-border",
60 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
61 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
62 })
63 })
64)
65# Set up environment ------------------------------------------------
66library(shiny)
67library(DT)
68library(magrittr)
69
70# Example of data coming from the database. -------------------------
71
72set.seed(pi^2)
73
74SourceData <-
75 data.frame(sample_id = 1:25,
76 is_selected = sample(c(TRUE, FALSE), 25, replace = TRUE))
77
78
79# Support Functions -------------------------------------------------
80# These would exist, for example, in an internal package
81
82shinyInput <- function (FUN, id_base, suffix, label = "", ...)
83{
84 inputId <- paste0(id_base, suffix)
85 args <- list(...)
86 args <- c(list(label = label), args)
87 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
88 rv <- character(length(inputId))
89 for (i in seq_along(rv)) {
90 this_arg <- lapply(args, `[`, i)
91 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
92 rv[i] <- as.character(ctrl)
93 }
94 rv
95}
96
97prepareDataForDisplay <- function(Data){
98 Data$is_selected <-
99 shinyInput(shiny::checkboxInput,
100 id_base = "is_selected_",
101 suffix = Data$sample_id,
102 value = Data$is_selected)
103
104 Data
105}
106
107# User Interface ----------------------------------------------------
108
109ui <-
110 fluidPage(
111 verbatimTextOutput("value_check"),
112
113 actionButton(inputId = "btn_saveSelection",
114 label = "Save Selection"),
115 actionButton(inputId = "btn_selectAll",
116 label = "Select All"),
117 actionButton(inputId = "btn_unselectAll",
118 label = "Unselect All"),
119 actionButton(inputId = "btn_restoreDefault",
120 label = "Restore Default (select odd only)"),
121
122 DT::dataTableOutput("dt")
123 )
124
125# Server ------------------------------------------------------------
126
127server <-
128 shinyServer(function(input, output, session){
129
130 # Event Observers -----------------------------------------------
131
132 observeEvent(
133 input$btn_selectAll,
134 {
135 check_input <- names(input)[grepl("is_selected_", names(input))]
136
137 lapply(check_input,
138 function(ci){
139 updateCheckboxInput(session = session,
140 inputId = ci,
141 value = TRUE)
142 })
143 }
144 )
145
146 observeEvent(
147 input$btn_unselectAll,
148 {
149 check_input <- names(input)[grepl("is_selected_", names(input))]
150
151 lapply(check_input,
152 function(ci){
153 updateCheckboxInput(session = session,
154 inputId = ci,
155 value = FALSE)
156 })
157 }
158 )
159
160 observeEvent(
161 input$btn_restoreDefault,
162 {
163 check_input <- names(input)[grepl("is_selected_", names(input))]
164
165 lapply(check_input,
166 function(ci){
167 id <- as.numeric(sub("is_selected_", "", ci))
168
169 updateCheckboxInput(session = session,
170 inputId = ci,
171 value = id %% 2 == 1)
172 })
173 }
174 )
175
176 observeEvent(
177 input$btn_saveSelection,
178 {
179 check_input <- names(input)[grepl("is_selected_", names(input))]
180
181 id <- as.numeric(sub("is_selected_", "", check_input))
182
183 for (i in seq_along(check_input)){
184 SourceData$is_selected[SourceData$sample_id == id[i]] <-
185 input[[check_input[i]]]
186 }
187
188 # At this point, I would also save changes to the remote database.
189
190 DT::replaceData(proxy = dt_proxy,
191 data = prepareDataForDisplay(SourceData))
192 }
193 )
194
195 # Output elements -----------------------------------------------
196
197 output$value_check <-
198 renderPrint({
199 sort(names(input))
200 })
201
202 output$dt <-
203 DT::renderDataTable({
204 SourceData %>%
205 prepareDataForDisplay() %>%
206 DT::datatable(selection = "none",
207 escape = FALSE,
208 filter = "top",
209 class = "compact cell-border",
210 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
211 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
212 })
213
214 dt_proxy <- DT::dataTableProxy("dt")
215
216 })
217
218# Run the application -----------------------------------------------
219
220shinyApp(
221 ui = ui,
222 server = server
223)
224
ANSWER
Answered 2021-Dec-17 at 16:15Here is a workaround based on your addendum (not sure if you need the changes regarding btn_restoreDefault
and btn_saveSelection
), but the general procedure should be clear:
1library(shiny)
2library(DT)
3
4shinyInput <- function (FUN, id_base, suffix, label = "", ...)
5{
6 inputId <- paste0(id_base, suffix)
7 args <- list(...)
8 args <- c(list(label = label), args)
9 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
10 rv <- character(length(inputId))
11 for (i in seq_along(rv)) {
12 this_arg <- lapply(args, `[`, i)
13 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
14 rv[i] <- as.character(ctrl)
15 }
16 rv
17}
18
19X <- data.frame(id = LETTERS,
20 selected = sample(c(TRUE, FALSE),
21 size = length(LETTERS),
22 replace = TRUE))
23
24X$IsSelected <-
25 shinyInput(
26 shiny::checkboxInput,
27 id_base = "new_input_",
28 suffix = X$id,
29 value = X$selected
30 )
31
32shinyApp(
33 ui = fluidPage(
34 verbatimTextOutput("value_check"),
35 textOutput("input_a_value"),
36 DT::dataTableOutput("dt")
37 ),
38
39 server = shinyServer(function(input, output, session){
40
41 Data <- reactiveValues(
42 X = X
43 )
44
45 output$value_check <-
46 renderPrint({
47 sort(names(input))
48 })
49
50 output$dt <-
51 DT::renderDataTable({
52
53
54 DT::datatable(X,
55 selection = "none",
56 escape = FALSE,
57 filter = "top",
58 #rownames = FALSE,
59 class = "compact cell-border",
60 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
61 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
62 })
63 })
64)
65# Set up environment ------------------------------------------------
66library(shiny)
67library(DT)
68library(magrittr)
69
70# Example of data coming from the database. -------------------------
71
72set.seed(pi^2)
73
74SourceData <-
75 data.frame(sample_id = 1:25,
76 is_selected = sample(c(TRUE, FALSE), 25, replace = TRUE))
77
78
79# Support Functions -------------------------------------------------
80# These would exist, for example, in an internal package
81
82shinyInput <- function (FUN, id_base, suffix, label = "", ...)
83{
84 inputId <- paste0(id_base, suffix)
85 args <- list(...)
86 args <- c(list(label = label), args)
87 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
88 rv <- character(length(inputId))
89 for (i in seq_along(rv)) {
90 this_arg <- lapply(args, `[`, i)
91 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
92 rv[i] <- as.character(ctrl)
93 }
94 rv
95}
96
97prepareDataForDisplay <- function(Data){
98 Data$is_selected <-
99 shinyInput(shiny::checkboxInput,
100 id_base = "is_selected_",
101 suffix = Data$sample_id,
102 value = Data$is_selected)
103
104 Data
105}
106
107# User Interface ----------------------------------------------------
108
109ui <-
110 fluidPage(
111 verbatimTextOutput("value_check"),
112
113 actionButton(inputId = "btn_saveSelection",
114 label = "Save Selection"),
115 actionButton(inputId = "btn_selectAll",
116 label = "Select All"),
117 actionButton(inputId = "btn_unselectAll",
118 label = "Unselect All"),
119 actionButton(inputId = "btn_restoreDefault",
120 label = "Restore Default (select odd only)"),
121
122 DT::dataTableOutput("dt")
123 )
124
125# Server ------------------------------------------------------------
126
127server <-
128 shinyServer(function(input, output, session){
129
130 # Event Observers -----------------------------------------------
131
132 observeEvent(
133 input$btn_selectAll,
134 {
135 check_input <- names(input)[grepl("is_selected_", names(input))]
136
137 lapply(check_input,
138 function(ci){
139 updateCheckboxInput(session = session,
140 inputId = ci,
141 value = TRUE)
142 })
143 }
144 )
145
146 observeEvent(
147 input$btn_unselectAll,
148 {
149 check_input <- names(input)[grepl("is_selected_", names(input))]
150
151 lapply(check_input,
152 function(ci){
153 updateCheckboxInput(session = session,
154 inputId = ci,
155 value = FALSE)
156 })
157 }
158 )
159
160 observeEvent(
161 input$btn_restoreDefault,
162 {
163 check_input <- names(input)[grepl("is_selected_", names(input))]
164
165 lapply(check_input,
166 function(ci){
167 id <- as.numeric(sub("is_selected_", "", ci))
168
169 updateCheckboxInput(session = session,
170 inputId = ci,
171 value = id %% 2 == 1)
172 })
173 }
174 )
175
176 observeEvent(
177 input$btn_saveSelection,
178 {
179 check_input <- names(input)[grepl("is_selected_", names(input))]
180
181 id <- as.numeric(sub("is_selected_", "", check_input))
182
183 for (i in seq_along(check_input)){
184 SourceData$is_selected[SourceData$sample_id == id[i]] <-
185 input[[check_input[i]]]
186 }
187
188 # At this point, I would also save changes to the remote database.
189
190 DT::replaceData(proxy = dt_proxy,
191 data = prepareDataForDisplay(SourceData))
192 }
193 )
194
195 # Output elements -----------------------------------------------
196
197 output$value_check <-
198 renderPrint({
199 sort(names(input))
200 })
201
202 output$dt <-
203 DT::renderDataTable({
204 SourceData %>%
205 prepareDataForDisplay() %>%
206 DT::datatable(selection = "none",
207 escape = FALSE,
208 filter = "top",
209 class = "compact cell-border",
210 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
211 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
212 })
213
214 dt_proxy <- DT::dataTableProxy("dt")
215
216 })
217
218# Run the application -----------------------------------------------
219
220shinyApp(
221 ui = ui,
222 server = server
223)
224# Set up environment ------------------------------------------------
225library(shiny)
226library(DT)
227library(magrittr)
228
229# Example of data coming from the database. -------------------------
230
231set.seed(pi^2)
232
233SourceData <-
234 data.frame(sample_id = 1:25,
235 is_selected = sample(c(TRUE, FALSE), 25, replace = TRUE))
236
237
238# Support Functions -------------------------------------------------
239# These would exist, for example, in an internal package
240
241shinyInput <- function (FUN, id_base, suffix, label = "", ...)
242{
243 inputId <- paste0(id_base, suffix)
244 args <- list(...)
245 args <- c(list(label = label), args)
246 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
247 rv <- character(length(inputId))
248 for (i in seq_along(rv)) {
249 this_arg <- lapply(args, `[`, i)
250 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
251 rv[i] <- as.character(ctrl)
252 }
253 rv
254}
255
256prepareDataForDisplay <- function(Data){
257 Data$is_selected <-
258 shinyInput(shiny::checkboxInput,
259 id_base = "is_selected_",
260 suffix = Data$sample_id,
261 value = Data$is_selected)
262
263 Data
264}
265
266# User Interface ----------------------------------------------------
267
268ui <-
269 fluidPage(
270 verbatimTextOutput("value_check"),
271
272 actionButton(inputId = "btn_saveSelection",
273 label = "Save Selection"),
274 actionButton(inputId = "btn_selectAll",
275 label = "Select All"),
276 actionButton(inputId = "btn_unselectAll",
277 label = "Unselect All"),
278 actionButton(inputId = "btn_restoreDefault",
279 label = "Restore Default (select odd only)"),
280
281 DT::dataTableOutput("dt")
282 )
283
284# Server ------------------------------------------------------------
285
286server <-
287 shinyServer(function(input, output, session){
288
289 # Event Observers -----------------------------------------------
290
291 observeEvent(
292 input$btn_selectAll,
293 {
294 TmpData <- SourceData
295 TmpData$is_selected <- TRUE
296 replaceData(dt_proxy, prepareDataForDisplay(TmpData))
297 }
298 )
299
300 observeEvent(
301 input$btn_unselectAll,
302 {
303 TmpData <- SourceData
304 TmpData$is_selected <- FALSE
305 replaceData(dt_proxy, prepareDataForDisplay(TmpData))
306 }
307 )
308
309 observeEvent(
310 input$btn_restoreDefault,
311 {
312 replaceData(dt_proxy, prepareDataForDisplay(SourceData))
313 }
314 )
315
316 observeEvent(
317 input$btn_saveSelection,
318 {
319
320 check_input <- names(input)[grepl("is_selected_", names(input))]
321
322 id <- as.numeric(sub("is_selected_", "", check_input))
323
324 TmpData <- SourceData
325
326 for (i in seq_along(check_input)){
327 TmpData$is_selected[TmpData$sample_id == id[i]] <-
328 input[[check_input[i]]]
329 }
330
331 # At this point, I would also save changes to the remote database.
332
333 DT::replaceData(proxy = dt_proxy,
334 data = prepareDataForDisplay(TmpData))
335 }
336 )
337
338 # Output elements -----------------------------------------------
339
340 output$value_check <-
341 renderPrint({
342 sort(names(input))
343 })
344
345 output$dt <-
346 DT::renderDataTable({
347 SourceData %>%
348 prepareDataForDisplay() %>%
349 DT::datatable(selection = "none",
350 escape = FALSE,
351 filter = "top",
352 class = "compact cell-border",
353 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
354 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
355 })
356
357 dt_proxy <- DT::dataTableProxy("dt")
358
359 })
360
361# Run the application -----------------------------------------------
362
363shinyApp(
364 ui = ui,
365 server = server
366)
367
Community Discussions contain sources that include Stack Exchange Network