title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to create an array containing non-repeating elements in JavaScript ? - GeeksforGeeks
30 Nov, 2020 The following are the two approaches to generate an array containing n number of non-repeating random numbers. Using do-while loop and includes() function.Using a set and checking with its size. Using do-while loop and includes() function. Using a set and checking with its size. Using do-while loop and includes() function: Here, includes() function checks if an element is present in the array or not. Filename: index.js JavaScript // You can take this value from userconst n = 5 // Initial empty arrayconst arr = []; // Null checkif (n == 0) { console.log(null)} do { // Generating random number const randomNumber = Math .floor(Math.random() * 100) + 1 // Pushing into the array only // if the array does not contain it if (!arr.includes(randomNumber)) { arr.push(randomNumber); } } while (arr.length < n); // Printing the array elementsconsole.log(arr) Run the index.js file using the following command: node index.js Output: [ 49, 99, 27, 86, 69 ] Time complexity: O(n2) Using a set and checking with its size: Remember that a set does not allow duplicate elements. Filename: index.js JavaScript // You can take this value from userconst n = 5 // Initial empty arrayconst arr = []; // Null Checkif (n == 0) { console.log(null)} let randomnumbers = new Set, ans; // We keep adding elements till// size of set is equal to n while (randomnumbers.size < n) { // Generating random number // and adding it randomnumbers.add(Math.floor( Math.random() * 100) + 1);} // Copying set elements into // the result arrayans = [...randomnumbers]; // Printing the arrayconsole.log(ans) Run the index.js file using the following command: node index.js Output: [ 52, 32, 50, 59, 95 ] Time complexity: O(n) JavaScript-Misc Picked Technical Scripter 2020 JavaScript Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24934, "s": 24906, "text": "\n30 Nov, 2020" }, { "code": null, "e": 25045, "s": 24934, "text": "The following are the two approaches to generate an array containing n number of non-repeating random numbers." }, { "code": null, "e": 25129, "s": 25045, "text": "Using do-while loop and includes() function.Using a set and checking with its size." }, { "code": null, "e": 25174, "s": 25129, "text": "Using do-while loop and includes() function." }, { "code": null, "e": 25214, "s": 25174, "text": "Using a set and checking with its size." }, { "code": null, "e": 25338, "s": 25214, "text": "Using do-while loop and includes() function: Here, includes() function checks if an element is present in the array or not." }, { "code": null, "e": 25357, "s": 25338, "text": "Filename: index.js" }, { "code": null, "e": 25368, "s": 25357, "text": "JavaScript" }, { "code": "// You can take this value from userconst n = 5 // Initial empty arrayconst arr = []; // Null checkif (n == 0) { console.log(null)} do { // Generating random number const randomNumber = Math .floor(Math.random() * 100) + 1 // Pushing into the array only // if the array does not contain it if (!arr.includes(randomNumber)) { arr.push(randomNumber); } } while (arr.length < n); // Printing the array elementsconsole.log(arr)", "e": 25835, "s": 25368, "text": null }, { "code": null, "e": 25886, "s": 25835, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 25900, "s": 25886, "text": "node index.js" }, { "code": null, "e": 25908, "s": 25900, "text": "Output:" }, { "code": null, "e": 25931, "s": 25908, "text": "[ 49, 99, 27, 86, 69 ]" }, { "code": null, "e": 25949, "s": 25931, "text": "Time complexity: " }, { "code": null, "e": 25955, "s": 25949, "text": "O(n2)" }, { "code": null, "e": 26050, "s": 25955, "text": "Using a set and checking with its size: Remember that a set does not allow duplicate elements." }, { "code": null, "e": 26069, "s": 26050, "text": "Filename: index.js" }, { "code": null, "e": 26080, "s": 26069, "text": "JavaScript" }, { "code": "// You can take this value from userconst n = 5 // Initial empty arrayconst arr = []; // Null Checkif (n == 0) { console.log(null)} let randomnumbers = new Set, ans; // We keep adding elements till// size of set is equal to n while (randomnumbers.size < n) { // Generating random number // and adding it randomnumbers.add(Math.floor( Math.random() * 100) + 1);} // Copying set elements into // the result arrayans = [...randomnumbers]; // Printing the arrayconsole.log(ans)", "e": 26582, "s": 26080, "text": null }, { "code": null, "e": 26633, "s": 26582, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 26647, "s": 26633, "text": "node index.js" }, { "code": null, "e": 26655, "s": 26647, "text": "Output:" }, { "code": null, "e": 26678, "s": 26655, "text": "[ 52, 32, 50, 59, 95 ]" }, { "code": null, "e": 26695, "s": 26678, "text": "Time complexity:" }, { "code": null, "e": 26700, "s": 26695, "text": "O(n)" }, { "code": null, "e": 26716, "s": 26700, "text": "JavaScript-Misc" }, { "code": null, "e": 26723, "s": 26716, "text": "Picked" }, { "code": null, "e": 26747, "s": 26723, "text": "Technical Scripter 2020" }, { "code": null, "e": 26758, "s": 26747, "text": "JavaScript" }, { "code": null, "e": 26777, "s": 26758, "text": "Technical Scripter" }, { "code": null, "e": 26794, "s": 26777, "text": "Web Technologies" }, { "code": null, "e": 26821, "s": 26794, "text": "Web technologies Questions" }, { "code": null, "e": 26919, "s": 26821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26928, "s": 26919, "text": "Comments" }, { "code": null, "e": 26941, "s": 26928, "text": "Old Comments" }, { "code": null, "e": 27002, "s": 26941, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27043, "s": 27002, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27097, "s": 27043, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27137, "s": 27097, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27199, "s": 27137, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27255, "s": 27199, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27288, "s": 27255, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27350, "s": 27288, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27393, "s": 27350, "text": "How to fetch data from an API in ReactJS ?" } ]
Simple Calculator App using Flutter - GeeksforGeeks
04 Oct, 2021 Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. In this article we will build a Simple Calculator App that can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input. Making this app will give you a good revision of flutter and dart basics. Concepts covered are: Showing Widgets on the screen. Gridview.builder Function writing If and else in dart Follow the below steps to implement the simple calculator. Let’s get started. Open the Terminal /Command-prompt. Change Directory to your choice and run flutter create calculatorApp. Open the calculatorApp in VS Code or Android Studio. In the Lib folder, there is a main.dart file already present. And now in the same folder create a new file named buttons.dart. Starting with main.dart file. Create MyApp class and make it StatelessWidget. Add an array of buttons to be displayed. Set the background-color, text-color, functionality onTapped to the buttons. Write a function to calculate the Answers Dart import 'package:flutter/material.dart';import 'buttons.dart';import 'package:math_expressions/math_expressions.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: HomePage(), ); // MaterialApp }} class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { var userInput = ''; var answer = ''; // Array of button final List<String> buttons = [ 'C', '+/-', '%', 'DEL', '7', '8', '9', '/', '4', '5', '6', 'x', '1', '2', '3', '-', '0', '.', '=', '+', ]; @override Widget build(BuildContext context) { return Scaffold( appBar: new AppBar( title: new Text("Calculator"), ), //AppBar backgroundColor: Colors.white38, body: Column( children: <Widget>[ Expanded( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( padding: EdgeInsets.all(20), alignment: Alignment.centerRight, child: Text( userInput, style: TextStyle(fontSize: 18, color: Colors.white), ), ), Container( padding: EdgeInsets.all(15), alignment: Alignment.centerRight, child: Text( answer, style: TextStyle( fontSize: 30, color: Colors.white, fontWeight: FontWeight.bold), ), ) ]), ), ), Expanded( flex: 3, child: Container( child: GridView.builder( itemCount: buttons.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4), itemBuilder: (BuildContext context, int index) { // Clear Button if (index == 0) { return MyButton( buttontapped: () { setState(() { userInput = ''; answer = '0'; }); }, buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // +/- button else if (index == 1) { return MyButton( buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // % Button else if (index == 2) { return MyButton( buttontapped: () { setState(() { userInput += buttons[index]; }); }, buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // Delete Button else if (index == 3) { return MyButton( buttontapped: () { setState(() { userInput = userInput.substring(0, userInput.length - 1); }); }, buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // Equal_to Button else if (index == 18) { return MyButton( buttontapped: () { setState(() { equalPressed(); }); }, buttonText: buttons[index], color: Colors.orange[700], textColor: Colors.white, ); } // other buttons else { return MyButton( buttontapped: () { setState(() { userInput += buttons[index]; }); }, buttonText: buttons[index], color: isOperator(buttons[index]) ? Colors.blueAccent : Colors.white, textColor: isOperator(buttons[index]) ? Colors.white : Colors.black, ); } }), // GridView.builder ), ), ], ), ); } bool isOperator(String x) { if (x == '/' || x == 'x' || x == '-' || x == '+' || x == '=') { return true; } return false; } // function to calculate the input operation void equalPressed() { String finaluserinput = userInput; finaluserinput = userInput.replaceAll('x', '*'); Parser p = Parser(); Expression exp = p.parse(finaluserinput); ContextModel cm = ContextModel(); double eval = exp.evaluate(EvaluationType.REAL, cm); answer = eval.toString(); }} In Flutter main.dart file is the entry point from which the code starts to executing. In the main.dart file firstly material design package has been imported in addition to math_expressions and buttons.dart file. Then a function runApp has been created with parameter as MyApp. After the declaration of class MyApp which is a stateless widget, the state of class MyApp has been laid out. In buttons.dart which is already imported in main.dart file we are declaring variables that will be used throughout the program using a constructor. The color, text color, button text, and the functionality of the button on tapped will be implemented in main.dart file Dart import 'package:flutter/material.dart'; // creating Stateless Widget for buttonsclass MyButton extends StatelessWidget { // declaring variables final color; final textColor; final String buttonText; final buttontapped; //Constructor MyButton({this.color, this.textColor, this.buttonText, this.buttontapped}); @override Widget build(BuildContext context) { return GestureDetector( onTap: buttontapped, child: Padding( padding: const EdgeInsets.all(0.2), child: ClipRRect( // borderRadius: BorderRadius.circular(25), child: Container( color: color, child: Center( child: Text( buttonText, style: TextStyle( color: textColor, fontSize: 25, fontWeight: FontWeight.bold, ), ), ), ), ), ), ); }} To make the process easier we are using math_expressions: ^2.0.0 package which is imported in main.dart file to handle all the calculations and run time error exceptions. Adding math_expressions : ^2.0.0 dependency Output: ruhelaa48 android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Flutter - Flexible Widget ListView Class in Flutter Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Format Dates in Flutter
[ { "code": null, "e": 23643, "s": 23615, "text": "\n04 Oct, 2021" }, { "code": null, "e": 24033, "s": 23643, "text": "Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. In this article we will build a Simple Calculator App that can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input. Making this app will give you a good revision of flutter and dart basics. Concepts covered are:" }, { "code": null, "e": 24064, "s": 24033, "text": "Showing Widgets on the screen." }, { "code": null, "e": 24081, "s": 24064, "text": "Gridview.builder" }, { "code": null, "e": 24098, "s": 24081, "text": "Function writing" }, { "code": null, "e": 24118, "s": 24098, "text": "If and else in dart" }, { "code": null, "e": 24196, "s": 24118, "text": "Follow the below steps to implement the simple calculator. Let’s get started." }, { "code": null, "e": 24354, "s": 24196, "text": "Open the Terminal /Command-prompt. Change Directory to your choice and run flutter create calculatorApp. Open the calculatorApp in VS Code or Android Studio." }, { "code": null, "e": 24719, "s": 24354, "text": "In the Lib folder, there is a main.dart file already present. And now in the same folder create a new file named buttons.dart. Starting with main.dart file. Create MyApp class and make it StatelessWidget. Add an array of buttons to be displayed. Set the background-color, text-color, functionality onTapped to the buttons. Write a function to calculate the Answers" }, { "code": null, "e": 24724, "s": 24719, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'buttons.dart';import 'package:math_expressions/math_expressions.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: HomePage(), ); // MaterialApp }} class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { var userInput = ''; var answer = ''; // Array of button final List<String> buttons = [ 'C', '+/-', '%', 'DEL', '7', '8', '9', '/', '4', '5', '6', 'x', '1', '2', '3', '-', '0', '.', '=', '+', ]; @override Widget build(BuildContext context) { return Scaffold( appBar: new AppBar( title: new Text(\"Calculator\"), ), //AppBar backgroundColor: Colors.white38, body: Column( children: <Widget>[ Expanded( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( padding: EdgeInsets.all(20), alignment: Alignment.centerRight, child: Text( userInput, style: TextStyle(fontSize: 18, color: Colors.white), ), ), Container( padding: EdgeInsets.all(15), alignment: Alignment.centerRight, child: Text( answer, style: TextStyle( fontSize: 30, color: Colors.white, fontWeight: FontWeight.bold), ), ) ]), ), ), Expanded( flex: 3, child: Container( child: GridView.builder( itemCount: buttons.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4), itemBuilder: (BuildContext context, int index) { // Clear Button if (index == 0) { return MyButton( buttontapped: () { setState(() { userInput = ''; answer = '0'; }); }, buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // +/- button else if (index == 1) { return MyButton( buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // % Button else if (index == 2) { return MyButton( buttontapped: () { setState(() { userInput += buttons[index]; }); }, buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // Delete Button else if (index == 3) { return MyButton( buttontapped: () { setState(() { userInput = userInput.substring(0, userInput.length - 1); }); }, buttonText: buttons[index], color: Colors.blue[50], textColor: Colors.black, ); } // Equal_to Button else if (index == 18) { return MyButton( buttontapped: () { setState(() { equalPressed(); }); }, buttonText: buttons[index], color: Colors.orange[700], textColor: Colors.white, ); } // other buttons else { return MyButton( buttontapped: () { setState(() { userInput += buttons[index]; }); }, buttonText: buttons[index], color: isOperator(buttons[index]) ? Colors.blueAccent : Colors.white, textColor: isOperator(buttons[index]) ? Colors.white : Colors.black, ); } }), // GridView.builder ), ), ], ), ); } bool isOperator(String x) { if (x == '/' || x == 'x' || x == '-' || x == '+' || x == '=') { return true; } return false; } // function to calculate the input operation void equalPressed() { String finaluserinput = userInput; finaluserinput = userInput.replaceAll('x', '*'); Parser p = Parser(); Expression exp = p.parse(finaluserinput); ContextModel cm = ContextModel(); double eval = exp.evaluate(EvaluationType.REAL, cm); answer = eval.toString(); }}", "e": 30674, "s": 24724, "text": null }, { "code": null, "e": 31064, "s": 30674, "text": "In Flutter main.dart file is the entry point from which the code starts to executing. In the main.dart file firstly material design package has been imported in addition to math_expressions and buttons.dart file. Then a function runApp has been created with parameter as MyApp. After the declaration of class MyApp which is a stateless widget, the state of class MyApp has been laid out. " }, { "code": null, "e": 31334, "s": 31064, "text": "In buttons.dart which is already imported in main.dart file we are declaring variables that will be used throughout the program using a constructor. The color, text color, button text, and the functionality of the button on tapped will be implemented in main.dart file " }, { "code": null, "e": 31339, "s": 31334, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; // creating Stateless Widget for buttonsclass MyButton extends StatelessWidget { // declaring variables final color; final textColor; final String buttonText; final buttontapped; //Constructor MyButton({this.color, this.textColor, this.buttonText, this.buttontapped}); @override Widget build(BuildContext context) { return GestureDetector( onTap: buttontapped, child: Padding( padding: const EdgeInsets.all(0.2), child: ClipRRect( // borderRadius: BorderRadius.circular(25), child: Container( color: color, child: Center( child: Text( buttonText, style: TextStyle( color: textColor, fontSize: 25, fontWeight: FontWeight.bold, ), ), ), ), ), ), ); }}", "e": 32268, "s": 31339, "text": null }, { "code": null, "e": 32441, "s": 32268, "text": "To make the process easier we are using math_expressions: ^2.0.0 package which is imported in main.dart file to handle all the calculations and run time error exceptions. " }, { "code": null, "e": 32485, "s": 32441, "text": "Adding math_expressions : ^2.0.0 dependency" }, { "code": null, "e": 32495, "s": 32485, "text": "Output: " }, { "code": null, "e": 32507, "s": 32497, "text": "ruhelaa48" }, { "code": null, "e": 32515, "s": 32507, "text": "android" }, { "code": null, "e": 32523, "s": 32515, "text": "Flutter" }, { "code": null, "e": 32528, "s": 32523, "text": "Dart" }, { "code": null, "e": 32536, "s": 32528, "text": "Flutter" }, { "code": null, "e": 32634, "s": 32536, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32643, "s": 32634, "text": "Comments" }, { "code": null, "e": 32656, "s": 32643, "text": "Old Comments" }, { "code": null, "e": 32695, "s": 32656, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32721, "s": 32695, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 32747, "s": 32721, "text": "ListView Class in Flutter" }, { "code": null, "e": 32770, "s": 32747, "text": "Flutter - Stack Widget" }, { "code": null, "e": 32815, "s": 32770, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 32854, "s": 32815, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32871, "s": 32854, "text": "Flutter Tutorial" }, { "code": null, "e": 32897, "s": 32871, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 32920, "s": 32897, "text": "Flutter - Stack Widget" } ]
Introducing 3D ggplots with Rayshader (R) | by Carrie Lo | Towards Data Science
Rayshader is a powerful package in R supporting 2D and 3D data visualisation. What amazes me is its details of displaying the 3D plots and it provides lots of customisation. Most importantly, it allows you to directly transform the ggplot2 objects into 3D plot. In this demonstration, the Hong Kong population and housing price data are used. Pre-processed data and the R scripts are uploaded to my Github repo. Feel free to download and play around. rayshader rayshader is an open-source package for producing 2D and 3D data visualizations in R. rayshader uses elevation data in a base R matrix and a combination of raytracing, spherical texture mapping, overlays, and ambient occlusion to generate beautiful topographic 2D and 3D maps. In addition to maps, rayshader also allows the user to translate ggplot2 objects into beautiful 3D data visualizations. The models can be rotated and examined interactively or the camera movement can be scripted to create animations. Scenes can also be rendered using a high-quality pathtracer, rayrender. The user can also create a cinematic depth of field post-processing effect to direct the user’s focus to important regions in the figure. The 3D models can also be exported to a 3D-printable format with a built-in STL export function. Generate a 2D map plot with ggplot2Transform the 2D plot into a 3D plot with rayshader Generate a 2D map plot with ggplot2 Transform the 2D plot into a 3D plot with rayshader Population Data.xlsx real_estate_master_df.csv Task 1: Generate a 2D map plot with ggplot2 library(sp)hkmap = readRDS("HKG_adm1.rds") # geo data of HK map# Preprocessingmap_data = data.frame(id=hkmap$ID_1, Code=hkmap$HASC_1, Eng_name=hkmap$NAME_1)map_data$Code = gsub('HK.', '', as.character(map_data$Code))map_data = merge(map_data, district_name, by = 'Eng_name')hkmapdf = fortify(hkmap)map_data = merge(hkmapdf, map_data, by="id")map_data = merge(map_data, population, by = "Chi_name")map_data$Population = as.numeric(map_data$Population)library(ggplot2)# Mapmap_bg = ggplot(map_data, aes(long, lat, group=group, fill = Population)) + geom_polygon() + # Shape scale_fill_gradient(limits=range(map_data$Population), low="#FFF3B0", high="#E09F3E") + layer(geom="path", stat="identity", position="identity", mapping=aes(x=long, y=lat, group=group, color=I('#FFFFFF'))) + theme(legend.position = "none", axis.line=element_blank(), axis.text.x=element_blank(), axis.title.x=element_blank(), axis.text.y=element_blank(), axis.title.y=element_blank(), axis.ticks=element_blank(), panel.background = element_blank()) # Clean Everythingmap_bg# Save as PNGxlim = ggplot_build(map_bg)$layout$panel_scales_x[[1]]$range$rangeylim = ggplot_build(map_bg)$layout$panel_scales_y[[1]]$range$rangeggsave('map_bg1.png', width = diff(xlim)*100, height = diff(ylim)*100, units = "cm") Step-by-step explanation: hkmap = readRDS("HKG_adm1.rds") # geo data of HK map To plot a map of any regions, you need to have the location data on hand. Please download the rds file from the Github repo first. library(ggplot2)# Mapmap_bg = ggplot(map_data, aes(long, lat, group=group, fill = Population)) + geom_polygon() + # Shape scale_fill_gradient(limits=range(map_data$Population), low="#FFF3B0", high="#E09F3E") + layer(geom="path", stat="identity", position="identity", mapping=aes(x=long, y=lat, group=group, color=I('#FFFFFF'))) ggplot2 is another wonderful package in R providing many kinds of charts like bar chart, pie chart, heat map ... you name it. In the script shown above, there are 2 main things done. On the line, scale_fill_gradient, the polygons shown in the map are filled by colour based on population data. Regions with darker colour means that they have a higher population. Then, layer gives a borderline to each region which is the white line shown. map_bg + theme(legend.position = "none", axis.line=element_blank(), axis.text.x=element_blank(), axis.title.x=element_blank(), axis.text.y=element_blank(), axis.title.y=element_blank(), axis.ticks=element_blank(), panel.background = element_blank()) # Clean Everythingmap_bg The reason for creating this plot is to prepare a background image for the 3D plot that we are going to work out in task 2. Thus, I remove all the gridlines, x-axis and y-axis by using theme. # Save as PNGxlim = ggplot_build(map_bg)$layout$panel_scales_x[[1]]$range$rangeylim = ggplot_build(map_bg)$layout$panel_scales_y[[1]]$range$rangeggsave(‘map_bg.png’, width = diff(xlim)*40, height = diff(ylim)*40, units = “cm”) Lastly, ggsave is used to export the map_bg with the right scale derived from the plot coordinates. Task 2: Transform the 2D plot into a 3D plot with rayshader Data of real_estate_master_df.csv are scraped from Hong Kong Property. # 2D Plotlibrary(ggplot2)library(grid)estate_price = ggplot(estate_df) + annotation_custom(rasterGrob(hk_map_bg, width=unit(1,"npc"), height=unit(1,"npc")), -Inf, Inf, -Inf, Inf) + xlim(xlim[1],xlim[2]) + # x-axis Mapping ylim(ylim[1],ylim[2]) + # y-axis Mapping geom_point(aes(x=Longitude, y=Latitude, color=apr_price),size=2) + scale_colour_gradient(name = '成交呎價(實)\n(HKD)', limits=range(estate_df$apr_price), low="#FCB9B2", high="#B23A48") + theme(axis.line=element_blank(), axis.text.x=element_blank(), axis.title.x=element_blank(), axis.text.y=element_blank(), axis.title.y=element_blank(), axis.ticks=element_blank(), panel.background = element_blank()) # Clean Everythingestate_price Step-by-step explanation: annotation_custom(rasterGrob(hk_map_bg, width=unit(1,"npc"), height=unit(1,"npc")), -Inf, Inf, -Inf, Inf) + xlim(xlim[1],xlim[2]) + # x-axis Mapping ylim(ylim[1],ylim[2]) + # y-axis Mapping annotation_custom is used to import the prepared map background image to the plot. xlim(xlim[1],xlim[2]) and ylim(ylim[1],ylim[2]) fix the x- and y-axis of the plot and make them the same as the map_bg. geom_point(aes(x=Longitude, y=Latitude, color=apr_price),size=2) + scale_colour_gradient(name = '成交呎價(實)\n(HKD)', limits=range(estate_df$apr_price), low="#FCB9B2", high="#B23A48") + geom_point adds the data points of estate price to the plot. scale_colour_gradient fills the data points with color based on the variable, “apr_price”, please note that the function used here is different from the one used in task 1. (scale_colour_gradient for geom_point, scale_fill_gradient for geom_polygon) # 3D Plotlibrary(rayshader)plot_gg(estate_price, multicore = TRUE, width = diff(xlim)*10 ,height=diff(ylim)*10, fov = 70, scale = 300)# Close Windowsrgl.close() The script to convert the 2D plot to a 3D plot is very simple. The 3D plot is shown in the rgl window. However, remember to close the window after viewing the plot. As the output of the rgl window will not be erased, so the next plot will be overlapped with the previous plot. Hope you enjoy my article =) To know more about using rayshader, please go to the official website of rayshader. If you find my article useful, please endorse my skills on my linkedIn page to encourage me to write more articles. Originally published on cydalytics.blogspot.com
[ { "code": null, "e": 434, "s": 172, "text": "Rayshader is a powerful package in R supporting 2D and 3D data visualisation. What amazes me is its details of displaying the 3D plots and it provides lots of customisation. Most importantly, it allows you to directly transform the ggplot2 objects into 3D plot." }, { "code": null, "e": 623, "s": 434, "text": "In this demonstration, the Hong Kong population and housing price data are used. Pre-processed data and the R scripts are uploaded to my Github repo. Feel free to download and play around." }, { "code": null, "e": 633, "s": 623, "text": "rayshader" }, { "code": null, "e": 1030, "s": 633, "text": "rayshader is an open-source package for producing 2D and 3D data visualizations in R. rayshader uses elevation data in a base R matrix and a combination of raytracing, spherical texture mapping, overlays, and ambient occlusion to generate beautiful topographic 2D and 3D maps. In addition to maps, rayshader also allows the user to translate ggplot2 objects into beautiful 3D data visualizations." }, { "code": null, "e": 1451, "s": 1030, "text": "The models can be rotated and examined interactively or the camera movement can be scripted to create animations. Scenes can also be rendered using a high-quality pathtracer, rayrender. The user can also create a cinematic depth of field post-processing effect to direct the user’s focus to important regions in the figure. The 3D models can also be exported to a 3D-printable format with a built-in STL export function." }, { "code": null, "e": 1538, "s": 1451, "text": "Generate a 2D map plot with ggplot2Transform the 2D plot into a 3D plot with rayshader" }, { "code": null, "e": 1574, "s": 1538, "text": "Generate a 2D map plot with ggplot2" }, { "code": null, "e": 1626, "s": 1574, "text": "Transform the 2D plot into a 3D plot with rayshader" }, { "code": null, "e": 1647, "s": 1626, "text": "Population Data.xlsx" }, { "code": null, "e": 1673, "s": 1647, "text": "real_estate_master_df.csv" }, { "code": null, "e": 1717, "s": 1673, "text": "Task 1: Generate a 2D map plot with ggplot2" }, { "code": null, "e": 3084, "s": 1717, "text": "library(sp)hkmap = readRDS(\"HKG_adm1.rds\") # geo data of HK map# Preprocessingmap_data = data.frame(id=hkmap$ID_1, Code=hkmap$HASC_1, Eng_name=hkmap$NAME_1)map_data$Code = gsub('HK.', '', as.character(map_data$Code))map_data = merge(map_data, district_name, by = 'Eng_name')hkmapdf = fortify(hkmap)map_data = merge(hkmapdf, map_data, by=\"id\")map_data = merge(map_data, population, by = \"Chi_name\")map_data$Population = as.numeric(map_data$Population)library(ggplot2)# Mapmap_bg = ggplot(map_data, aes(long, lat, group=group, fill = Population)) + geom_polygon() + # Shape scale_fill_gradient(limits=range(map_data$Population), low=\"#FFF3B0\", high=\"#E09F3E\") + layer(geom=\"path\", stat=\"identity\", position=\"identity\", mapping=aes(x=long, y=lat, group=group, color=I('#FFFFFF'))) + theme(legend.position = \"none\", axis.line=element_blank(), axis.text.x=element_blank(), axis.title.x=element_blank(), axis.text.y=element_blank(), axis.title.y=element_blank(), axis.ticks=element_blank(), panel.background = element_blank()) # Clean Everythingmap_bg# Save as PNGxlim = ggplot_build(map_bg)$layout$panel_scales_x[[1]]$range$rangeylim = ggplot_build(map_bg)$layout$panel_scales_y[[1]]$range$rangeggsave('map_bg1.png', width = diff(xlim)*100, height = diff(ylim)*100, units = \"cm\")" }, { "code": null, "e": 3110, "s": 3084, "text": "Step-by-step explanation:" }, { "code": null, "e": 3163, "s": 3110, "text": "hkmap = readRDS(\"HKG_adm1.rds\") # geo data of HK map" }, { "code": null, "e": 3294, "s": 3163, "text": "To plot a map of any regions, you need to have the location data on hand. Please download the rds file from the Github repo first." }, { "code": null, "e": 3674, "s": 3294, "text": "library(ggplot2)# Mapmap_bg = ggplot(map_data, aes(long, lat, group=group, fill = Population)) + geom_polygon() + # Shape scale_fill_gradient(limits=range(map_data$Population), low=\"#FFF3B0\", high=\"#E09F3E\") + layer(geom=\"path\", stat=\"identity\", position=\"identity\", mapping=aes(x=long, y=lat, group=group, color=I('#FFFFFF')))" }, { "code": null, "e": 4114, "s": 3674, "text": "ggplot2 is another wonderful package in R providing many kinds of charts like bar chart, pie chart, heat map ... you name it. In the script shown above, there are 2 main things done. On the line, scale_fill_gradient, the polygons shown in the map are filled by colour based on population data. Regions with darker colour means that they have a higher population. Then, layer gives a borderline to each region which is the white line shown." }, { "code": null, "e": 4429, "s": 4114, "text": "map_bg + theme(legend.position = \"none\", axis.line=element_blank(), axis.text.x=element_blank(), axis.title.x=element_blank(), axis.text.y=element_blank(), axis.title.y=element_blank(), axis.ticks=element_blank(), panel.background = element_blank()) # Clean Everythingmap_bg" }, { "code": null, "e": 4621, "s": 4429, "text": "The reason for creating this plot is to prepare a background image for the 3D plot that we are going to work out in task 2. Thus, I remove all the gridlines, x-axis and y-axis by using theme." }, { "code": null, "e": 4848, "s": 4621, "text": "# Save as PNGxlim = ggplot_build(map_bg)$layout$panel_scales_x[[1]]$range$rangeylim = ggplot_build(map_bg)$layout$panel_scales_y[[1]]$range$rangeggsave(‘map_bg.png’, width = diff(xlim)*40, height = diff(ylim)*40, units = “cm”)" }, { "code": null, "e": 4948, "s": 4848, "text": "Lastly, ggsave is used to export the map_bg with the right scale derived from the plot coordinates." }, { "code": null, "e": 5008, "s": 4948, "text": "Task 2: Transform the 2D plot into a 3D plot with rayshader" }, { "code": null, "e": 5079, "s": 5008, "text": "Data of real_estate_master_df.csv are scraped from Hong Kong Property." }, { "code": null, "e": 5909, "s": 5079, "text": "# 2D Plotlibrary(ggplot2)library(grid)estate_price = ggplot(estate_df) + annotation_custom(rasterGrob(hk_map_bg, width=unit(1,\"npc\"), height=unit(1,\"npc\")), -Inf, Inf, -Inf, Inf) + xlim(xlim[1],xlim[2]) + # x-axis Mapping ylim(ylim[1],ylim[2]) + # y-axis Mapping geom_point(aes(x=Longitude, y=Latitude, color=apr_price),size=2) + scale_colour_gradient(name = '成交呎價(實)\\n(HKD)', limits=range(estate_df$apr_price), low=\"#FCB9B2\", high=\"#B23A48\") + theme(axis.line=element_blank(), axis.text.x=element_blank(), axis.title.x=element_blank(), axis.text.y=element_blank(), axis.title.y=element_blank(), axis.ticks=element_blank(), panel.background = element_blank()) # Clean Everythingestate_price" }, { "code": null, "e": 5935, "s": 5909, "text": "Step-by-step explanation:" }, { "code": null, "e": 6181, "s": 5935, "text": " annotation_custom(rasterGrob(hk_map_bg, width=unit(1,\"npc\"), height=unit(1,\"npc\")), -Inf, Inf, -Inf, Inf) + xlim(xlim[1],xlim[2]) + # x-axis Mapping ylim(ylim[1],ylim[2]) + # y-axis Mapping" }, { "code": null, "e": 6384, "s": 6181, "text": "annotation_custom is used to import the prepared map background image to the plot. xlim(xlim[1],xlim[2]) and ylim(ylim[1],ylim[2]) fix the x- and y-axis of the plot and make them the same as the map_bg." }, { "code": null, "e": 6616, "s": 6384, "text": "geom_point(aes(x=Longitude, y=Latitude, color=apr_price),size=2) + scale_colour_gradient(name = '成交呎價(實)\\n(HKD)', limits=range(estate_df$apr_price), low=\"#FCB9B2\", high=\"#B23A48\") +" }, { "code": null, "e": 6677, "s": 6616, "text": "geom_point adds the data points of estate price to the plot." }, { "code": null, "e": 6927, "s": 6677, "text": "scale_colour_gradient fills the data points with color based on the variable, “apr_price”, please note that the function used here is different from the one used in task 1. (scale_colour_gradient for geom_point, scale_fill_gradient for geom_polygon)" }, { "code": null, "e": 7088, "s": 6927, "text": "# 3D Plotlibrary(rayshader)plot_gg(estate_price, multicore = TRUE, width = diff(xlim)*10 ,height=diff(ylim)*10, fov = 70, scale = 300)# Close Windowsrgl.close()" }, { "code": null, "e": 7365, "s": 7088, "text": "The script to convert the 2D plot to a 3D plot is very simple. The 3D plot is shown in the rgl window. However, remember to close the window after viewing the plot. As the output of the rgl window will not be erased, so the next plot will be overlapped with the previous plot." }, { "code": null, "e": 7394, "s": 7365, "text": "Hope you enjoy my article =)" }, { "code": null, "e": 7478, "s": 7394, "text": "To know more about using rayshader, please go to the official website of rayshader." }, { "code": null, "e": 7594, "s": 7478, "text": "If you find my article useful, please endorse my skills on my linkedIn page to encourage me to write more articles." } ]
Almost Prime Numbers - GeeksforGeeks
30 Sep, 2021 A k-Almost Prime Number is a number having exactly k prime factors (not necessarily distinct). For example, 2, 3, 5, 7, 11 ....(in fact all prime numbers) are 1-Almost Prime Numbers as they have only 1 prime factor (which is themselves). 4, 6, 9.... are 2-Almost Prime Numbers as they have exactly 2 prime factors (4 = 2*2, 6 = 2*3, 9 = 3*3) Similarly, 32 is a 5-Almost Prime Number (32 = 2*2*2*2*2) and so is 72 (2*2*2*3*3) All the 1-Almost Primes are called as Prime Numbers and all the 2-Almost Prime are called semi-primes.The task is to print first n numbers that are k prime. Examples: Input: k = 2, n = 5 Output: 4 6 9 10 14 4 has two prime factors, 2 x 2 6 has two prime factors, 2 x 3 Similarly, 9(3 x 3), 10(2 x 5) and 14(2 x 7) Input: k = 10, n = 2 Output: 1024 1536 1024 and 1536 are first two numbers with 10 prime factors. We iterate natural numbers and keep printing k-primes till the count of printed k-primes is less than or equal to n. To check if a number is k-prime, we find count of prime factors and if the count is k we consider the number as k-prime. Below is the implementation of the above approach : C++ Java Python3 C# PHP Javascript // Program to print first n numbers that are k-primes#include<bits/stdc++.h>using namespace std; // A function to count all prime factors of a given numberint countPrimeFactors(int n){ int count = 0; // Count the number of 2s that divide n while (n%2 == 0) { n = n/2; count++; } // n must be odd at this point. So we can skip one // element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, count i and divide n while (n%i == 0) { n = n/i; count++; } } // This condition is to handle the case when n is a // prime number greater than 2 if (n > 2) count++; return(count);} // A function to print the first n numbers that are// k-almost primes.void printKAlmostPrimes(int k, int n){ for (int i=1, num=2; i<=n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { printf("%d ", num); // Increment count of k-primes printed // so far i++; } } return;} /* Driver program to test above function */int main(){ int n = 10, k = 2; printf("First %d %d-almost prime numbers : \n", n, k); printKAlmostPrimes(k, n); return 0;} // Program to print first n numbers that// are k-primes import java.io.*; class GFG { // A function to count all prime factors // of a given number static int countPrimeFactors(int n) { int count = 0; // Count the number of 2s that divide n while (n % 2 == 0) { n = n / 2; count++; } // n must be odd at this point. So we // can skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, count i and // divide n while (n % i == 0) { n = n / i; count++; } } // This condition is to handle the case // when n is a prime number greater // than 2 if (n > 2) count++; return (count); } // A function to print the first n numbers // that are k-almost primes. static void printKAlmostPrimes(int k, int n) { for (int i = 1, num = 2; i <= n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { System.out.print(num + " "); // Increment count of k-primes // printed so far i++; } } return; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10, k = 2; System.out.println("First " + n + " " + k + "-almost prime numbers : "); printKAlmostPrimes(k, n); }} // This code is contributed by vt_m. # Python3 Program to print first# n numbers that are k-primesimport math # A function to count all prime# factors of a given numberdef countPrimeFactors(n): count = 0; # Count the number of # 2s that divide n while(n % 2 == 0): n = n / 2; count += 1; # n must be odd at this point. # So we can skip one # element (Note i = i +2) i = 3; while(i <= math.sqrt(n)): # While i divides n, # count i and divide n while (n % i == 0): n = n / i; count += 1; i = i + 2; # This condition is to handle # the case when n is a # prime number greater than 2 if (n > 2): count += 1; return(count); # A function to print the# first n numbers that are# k-almost primes.def printKAlmostPrimes(k, n): i = 1; num = 2 while(i <= n): # Print this number if # it is k-prime if (countPrimeFactors(num) == k): print(num, end = ""); print(" ", end = ""); # Increment count of # k-primes printed # so far i += 1; num += 1; return; # Driver Coden = 10;k = 2;print("First n k-almost prime numbers:");printKAlmostPrimes(k, n); # This code is contributed by mits // C# Program to print first n// numbers that are k-primesusing System; class GFG{ // A function to count all prime // factors of a given number static int countPrimeFactors(int n) { int count = 0; // Count the number of 2s that divide n while (n % 2 == 0) { n = n / 2; count++; } // n must be odd at this point. So we // can skip one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, count i and // divide n while (n % i == 0) { n = n / i; count++; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) count++; return (count); } // A function to print the first n // numbers that are k-almost primes. static void printKAlmostPrimes(int k, int n) { for (int i = 1, num = 2; i <= n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { Console.Write(num + " "); // Increment count of k-primes // printed so far i++; } } return; } // Driver code public static void Main() { int n = 10, k = 2; Console.WriteLine("First " + n + " " + k + "-almost prime numbers : "); printKAlmostPrimes(k, n); }} // This code is contributed by Nitin Mittal. <?php// PHP Program to print first// n numbers that are k-primes // A function to count all prime// factors of a given numberfunction countPrimeFactors($n){ $count = 0; // Count the number of // 2s that divide n while($n % 2 == 0) { $n = $n / 2; $count++; } // n must be odd at this point. // So we can skip one // element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { // While i divides n, // count i and divide n while ($n % $i == 0) { $n = $n/$i; $count++; } } // This condition is to handle // the case when n is a // prime number greater than 2 if ($n > 2) $count++; return($count);} // A function to print the// first n numbers that are// k-almost primes.function printKAlmostPrimes($k, $n){ for ($i = 1, $num = 2; $i <= $n; $num++) { // Print this number if // it is k-prime if (countPrimeFactors($num) == $k) { echo($num); echo(" "); // Increment count of // k-primes printed // so far $i++; } } return;} // Driver Code $n = 10; $k = 2; echo "First $n $k-almost prime numbers:\n"; printKAlmostPrimes($k, $n); // This code is contributed by nitin mittal.?> <script> // Javascript program to print first n numbers that// are k-primes // A function to count all prime factors // of a given number function countPrimeFactors(n) { let count = 0; // Count the number of 2s that divide n while (n % 2 == 0) { n = n / 2; count++; } // n must be odd at this point. So we // can skip one element (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, count i and // divide n while (n % i == 0) { n = n / i; count++; } } // This condition is to handle the case // when n is a prime number greater // than 2 if (n > 2) count++; return (count); } // A function to print the first n numbers // that are k-almost primes. function printKAlmostPrimes(k, n) { for (let i = 1, num = 2; i <= n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { document.write(num + " "); // Increment count of k-primes // printed so far i++; } } return; } // Driver Code let n = 10, k = 2; document.write("First " + n + " " + k + "-almost prime numbers : " + "<br/>"); printKAlmostPrimes(k, n); </script> First 10 2-almost prime numbers : 4 6 9 10 14 15 21 22 25 26 References: https://en.wikipedia.org/wiki/Almost_prime This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Mithun Kumar viv_007 splevel62 gabaa406 Prime Number Arrays Mathematical Arrays Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24429, "s": 24401, "text": "\n30 Sep, 2021" }, { "code": null, "e": 24524, "s": 24429, "text": "A k-Almost Prime Number is a number having exactly k prime factors (not necessarily distinct)." }, { "code": null, "e": 24537, "s": 24524, "text": "For example," }, { "code": null, "e": 24667, "s": 24537, "text": "2, 3, 5, 7, 11 ....(in fact all prime numbers) are 1-Almost Prime Numbers as they have only 1 prime factor (which is themselves)." }, { "code": null, "e": 24771, "s": 24667, "text": "4, 6, 9.... are 2-Almost Prime Numbers as they have exactly 2 prime factors (4 = 2*2, 6 = 2*3, 9 = 3*3)" }, { "code": null, "e": 24854, "s": 24771, "text": "Similarly, 32 is a 5-Almost Prime Number (32 = 2*2*2*2*2) and so is 72 (2*2*2*3*3)" }, { "code": null, "e": 25011, "s": 24854, "text": "All the 1-Almost Primes are called as Prime Numbers and all the 2-Almost Prime are called semi-primes.The task is to print first n numbers that are k prime." }, { "code": null, "e": 25022, "s": 25011, "text": "Examples: " }, { "code": null, "e": 25268, "s": 25022, "text": "Input: k = 2, n = 5\nOutput: 4 6 9 10 14\n4 has two prime factors, 2 x 2\n6 has two prime factors, 2 x 3\nSimilarly, 9(3 x 3), 10(2 x 5) and 14(2 x 7)\n\nInput: k = 10, n = 2\nOutput: 1024 1536\n1024 and 1536 are first two numbers with 10\nprime factors." }, { "code": null, "e": 25507, "s": 25268, "text": "We iterate natural numbers and keep printing k-primes till the count of printed k-primes is less than or equal to n. To check if a number is k-prime, we find count of prime factors and if the count is k we consider the number as k-prime. " }, { "code": null, "e": 25560, "s": 25507, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 25564, "s": 25560, "text": "C++" }, { "code": null, "e": 25569, "s": 25564, "text": "Java" }, { "code": null, "e": 25577, "s": 25569, "text": "Python3" }, { "code": null, "e": 25580, "s": 25577, "text": "C#" }, { "code": null, "e": 25584, "s": 25580, "text": "PHP" }, { "code": null, "e": 25595, "s": 25584, "text": "Javascript" }, { "code": "// Program to print first n numbers that are k-primes#include<bits/stdc++.h>using namespace std; // A function to count all prime factors of a given numberint countPrimeFactors(int n){ int count = 0; // Count the number of 2s that divide n while (n%2 == 0) { n = n/2; count++; } // n must be odd at this point. So we can skip one // element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, count i and divide n while (n%i == 0) { n = n/i; count++; } } // This condition is to handle the case when n is a // prime number greater than 2 if (n > 2) count++; return(count);} // A function to print the first n numbers that are// k-almost primes.void printKAlmostPrimes(int k, int n){ for (int i=1, num=2; i<=n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { printf(\"%d \", num); // Increment count of k-primes printed // so far i++; } } return;} /* Driver program to test above function */int main(){ int n = 10, k = 2; printf(\"First %d %d-almost prime numbers : \\n\", n, k); printKAlmostPrimes(k, n); return 0;}", "e": 26891, "s": 25595, "text": null }, { "code": "// Program to print first n numbers that// are k-primes import java.io.*; class GFG { // A function to count all prime factors // of a given number static int countPrimeFactors(int n) { int count = 0; // Count the number of 2s that divide n while (n % 2 == 0) { n = n / 2; count++; } // n must be odd at this point. So we // can skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, count i and // divide n while (n % i == 0) { n = n / i; count++; } } // This condition is to handle the case // when n is a prime number greater // than 2 if (n > 2) count++; return (count); } // A function to print the first n numbers // that are k-almost primes. static void printKAlmostPrimes(int k, int n) { for (int i = 1, num = 2; i <= n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { System.out.print(num + \" \"); // Increment count of k-primes // printed so far i++; } } return; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10, k = 2; System.out.println(\"First \" + n + \" \" + k + \"-almost prime numbers : \"); printKAlmostPrimes(k, n); }} // This code is contributed by vt_m.", "e": 28559, "s": 26891, "text": null }, { "code": "# Python3 Program to print first# n numbers that are k-primesimport math # A function to count all prime# factors of a given numberdef countPrimeFactors(n): count = 0; # Count the number of # 2s that divide n while(n % 2 == 0): n = n / 2; count += 1; # n must be odd at this point. # So we can skip one # element (Note i = i +2) i = 3; while(i <= math.sqrt(n)): # While i divides n, # count i and divide n while (n % i == 0): n = n / i; count += 1; i = i + 2; # This condition is to handle # the case when n is a # prime number greater than 2 if (n > 2): count += 1; return(count); # A function to print the# first n numbers that are# k-almost primes.def printKAlmostPrimes(k, n): i = 1; num = 2 while(i <= n): # Print this number if # it is k-prime if (countPrimeFactors(num) == k): print(num, end = \"\"); print(\" \", end = \"\"); # Increment count of # k-primes printed # so far i += 1; num += 1; return; # Driver Coden = 10;k = 2;print(\"First n k-almost prime numbers:\");printKAlmostPrimes(k, n); # This code is contributed by mits", "e": 29832, "s": 28559, "text": null }, { "code": "// C# Program to print first n// numbers that are k-primesusing System; class GFG{ // A function to count all prime // factors of a given number static int countPrimeFactors(int n) { int count = 0; // Count the number of 2s that divide n while (n % 2 == 0) { n = n / 2; count++; } // n must be odd at this point. So we // can skip one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, count i and // divide n while (n % i == 0) { n = n / i; count++; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) count++; return (count); } // A function to print the first n // numbers that are k-almost primes. static void printKAlmostPrimes(int k, int n) { for (int i = 1, num = 2; i <= n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { Console.Write(num + \" \"); // Increment count of k-primes // printed so far i++; } } return; } // Driver code public static void Main() { int n = 10, k = 2; Console.WriteLine(\"First \" + n + \" \" + k + \"-almost prime numbers : \"); printKAlmostPrimes(k, n); }} // This code is contributed by Nitin Mittal.", "e": 31483, "s": 29832, "text": null }, { "code": "<?php// PHP Program to print first// n numbers that are k-primes // A function to count all prime// factors of a given numberfunction countPrimeFactors($n){ $count = 0; // Count the number of // 2s that divide n while($n % 2 == 0) { $n = $n / 2; $count++; } // n must be odd at this point. // So we can skip one // element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { // While i divides n, // count i and divide n while ($n % $i == 0) { $n = $n/$i; $count++; } } // This condition is to handle // the case when n is a // prime number greater than 2 if ($n > 2) $count++; return($count);} // A function to print the// first n numbers that are// k-almost primes.function printKAlmostPrimes($k, $n){ for ($i = 1, $num = 2; $i <= $n; $num++) { // Print this number if // it is k-prime if (countPrimeFactors($num) == $k) { echo($num); echo(\" \"); // Increment count of // k-primes printed // so far $i++; } } return;} // Driver Code $n = 10; $k = 2; echo \"First $n $k-almost prime numbers:\\n\"; printKAlmostPrimes($k, $n); // This code is contributed by nitin mittal.?>", "e": 32842, "s": 31483, "text": null }, { "code": "<script> // Javascript program to print first n numbers that// are k-primes // A function to count all prime factors // of a given number function countPrimeFactors(n) { let count = 0; // Count the number of 2s that divide n while (n % 2 == 0) { n = n / 2; count++; } // n must be odd at this point. So we // can skip one element (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, count i and // divide n while (n % i == 0) { n = n / i; count++; } } // This condition is to handle the case // when n is a prime number greater // than 2 if (n > 2) count++; return (count); } // A function to print the first n numbers // that are k-almost primes. function printKAlmostPrimes(k, n) { for (let i = 1, num = 2; i <= n; num++) { // Print this number if it is k-prime if (countPrimeFactors(num) == k) { document.write(num + \" \"); // Increment count of k-primes // printed so far i++; } } return; } // Driver Code let n = 10, k = 2; document.write(\"First \" + n + \" \" + k + \"-almost prime numbers : \" + \"<br/>\"); printKAlmostPrimes(k, n); </script>", "e": 34398, "s": 32842, "text": null }, { "code": null, "e": 34461, "s": 34398, "text": "First 10 2-almost prime numbers : \n4 6 9 10 14 15 21 22 25 26 " }, { "code": null, "e": 34518, "s": 34461, "text": "References: https://en.wikipedia.org/wiki/Almost_prime " }, { "code": null, "e": 34913, "s": 34518, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34926, "s": 34913, "text": "nitin mittal" }, { "code": null, "e": 34939, "s": 34926, "text": "Mithun Kumar" }, { "code": null, "e": 34947, "s": 34939, "text": "viv_007" }, { "code": null, "e": 34957, "s": 34947, "text": "splevel62" }, { "code": null, "e": 34966, "s": 34957, "text": "gabaa406" }, { "code": null, "e": 34979, "s": 34966, "text": "Prime Number" }, { "code": null, "e": 34986, "s": 34979, "text": "Arrays" }, { "code": null, "e": 34999, "s": 34986, "text": "Mathematical" }, { "code": null, "e": 35006, "s": 34999, "text": "Arrays" }, { "code": null, "e": 35019, "s": 35006, "text": "Mathematical" }, { "code": null, "e": 35032, "s": 35019, "text": "Prime Number" }, { "code": null, "e": 35130, "s": 35032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35139, "s": 35130, "text": "Comments" }, { "code": null, "e": 35152, "s": 35139, "text": "Old Comments" }, { "code": null, "e": 35173, "s": 35152, "text": "Next Greater Element" }, { "code": null, "e": 35198, "s": 35173, "text": "Window Sliding Technique" }, { "code": null, "e": 35225, "s": 35198, "text": "Count pairs with given sum" }, { "code": null, "e": 35274, "s": 35225, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35312, "s": 35274, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35342, "s": 35312, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35402, "s": 35342, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35417, "s": 35402, "text": "C++ Data Types" }, { "code": null, "e": 35460, "s": 35417, "text": "Set in C++ Standard Template Library (STL)" } ]
Fortran - Numbers
Numbers in Fortran are represented by three intrinsic data types − Integer type Real type Complex type The integer types can hold only integer values. The following example extracts the largest value that could be hold in a usual four byte integer − program testingInt implicit none integer :: largeval print *, huge(largeval) end program testingInt When you compile and execute the above program it produces the following result − 2147483647 Please note that the huge() function gives the largest number that can be held by the specific integer data type. You can also specify the number of bytes using the kind specifier. The following example demonstrates this − program testingInt implicit none !two byte integer integer(kind = 2) :: shortval !four byte integer integer(kind = 4) :: longval !eight byte integer integer(kind = 8) :: verylongval !sixteen byte integer integer(kind = 16) :: veryverylongval !default integer integer :: defval print *, huge(shortval) print *, huge(longval) print *, huge(verylongval) print *, huge(veryverylongval) print *, huge(defval) end program testingInt When you compile and execute the above program it produces the following result − 32767 2147483647 9223372036854775807 170141183460469231731687303715884105727 2147483647 It stores the floating point numbers, such as 2.0, 3.1415, -100.876, etc. Traditionally there were two different real types : the default real type and double precision type. However, Fortran 90/95 provides more control over the precision of real and integer data types through the kind specifier, which we will study shortly. The following example shows the use of real data type − program division implicit none ! Define real variables real :: p, q, realRes ! Define integer variables integer :: i, j, intRes ! Assigning values p = 2.0 q = 3.0 i = 2 j = 3 ! floating point division realRes = p/q intRes = i/j print *, realRes print *, intRes end program division When you compile and execute the above program it produces the following result − 0.666666687 0 This is used for storing complex numbers. A complex number has two parts : the real part and the imaginary part. Two consecutive numeric storage units store these two parts. For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i The generic function cmplx() creates a complex number. It produces a result who’s real and imaginary parts are single precision, irrespective of the type of the input arguments. program createComplex implicit none integer :: i = 10 real :: x = 5.17 print *, cmplx(i, x) end program createComplex When you compile and execute the above program it produces the following result − (10.0000000, 5.17000008) The following program demonstrates complex number arithmetic − program ComplexArithmatic implicit none complex, parameter :: i = (0, 1) ! sqrt(-1) complex :: x, y, z x = (7, 8); y = (5, -7) write(*,*) i * x * y z = x + y print *, "z = x + y = ", z z = x - y print *, "z = x - y = ", z z = x * y print *, "z = x * y = ", z z = x / y print *, "z = x / y = ", z end program ComplexArithmatic When you compile and execute the above program it produces the following result − (9.00000000, 91.0000000) z = x + y = (12.0000000, 1.00000000) z = x - y = (2.00000000, 15.0000000) z = x * y = (91.0000000, -9.00000000) z = x / y = (-0.283783793, 1.20270276) The range on integer numbers, the precision and the size of floating point numbers depends on the number of bits allocated to the specific data type. The following table displays the number of bits and range for integers − The following table displays the number of bits, smallest and largest value, and the precision for real numbers. The following examples demonstrate this − program rangePrecision implicit none real:: x, y, z x = 1.5e+40 y = 3.73e+40 z = x * y print *, z end program rangePrecision When you compile and execute the above program it produces the following result − x = 1.5e+40 1 Error : Real constant overflows its kind at (1) main.f95:5.12: y = 3.73e+40 1 Error : Real constant overflows its kind at (1) Now let us use a smaller number − program rangePrecision implicit none real:: x, y, z x = 1.5e+20 y = 3.73e+20 z = x * y print *, z z = x/y print *, z end program rangePrecision When you compile and execute the above program it produces the following result − Infinity 0.402144760 Now let’s watch underflow − program rangePrecision implicit none real:: x, y, z x = 1.5e-30 y = 3.73e-60 z = x * y print *, z z = x/y print *, z end program rangePrecision When you compile and execute the above program it produces the following result − y = 3.73e-60 1 Warning : Real constant underflows its kind at (1) Executing the program.... $demo 0.00000000E+00 Infinity In scientific programming, one often needs to know the range and precision of data of the hardware platform on which the work is being done. The intrinsic function kind() allows you to query the details of the hardware’s data representations before running a program. program kindCheck implicit none integer :: i real :: r complex :: cp print *,' Integer ', kind(i) print *,' Real ', kind(r) print *,' Complex ', kind(cp) end program kindCheck When you compile and execute the above program it produces the following result − Integer 4 Real 4 Complex 4 You can also check the kind of all data types − program checkKind implicit none integer :: i real :: r character :: c logical :: lg complex :: cp print *,' Integer ', kind(i) print *,' Real ', kind(r) print *,' Complex ', kind(cp) print *,' Character ', kind(c) print *,' Logical ', kind(lg) end program checkKind When you compile and execute the above program it produces the following result − Integer 4 Real 4 Complex 4 Character 1 Logical 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2213, "s": 2146, "text": "Numbers in Fortran are represented by three intrinsic data types −" }, { "code": null, "e": 2226, "s": 2213, "text": "Integer type" }, { "code": null, "e": 2236, "s": 2226, "text": "Real type" }, { "code": null, "e": 2249, "s": 2236, "text": "Complex type" }, { "code": null, "e": 2396, "s": 2249, "text": "The integer types can hold only integer values. The following example extracts the largest value that could be hold in a usual four byte integer −" }, { "code": null, "e": 2507, "s": 2396, "text": "program testingInt\nimplicit none\n\n integer :: largeval\n print *, huge(largeval)\n \nend program testingInt" }, { "code": null, "e": 2589, "s": 2507, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 2601, "s": 2589, "text": "2147483647\n" }, { "code": null, "e": 2824, "s": 2601, "text": "Please note that the huge() function gives the largest number that can be held by the specific integer data type. You can also specify the number of bytes using the kind specifier. The following example demonstrates this −" }, { "code": null, "e": 3327, "s": 2824, "text": "program testingInt\nimplicit none\n\n !two byte integer\n integer(kind = 2) :: shortval\n \n !four byte integer\n integer(kind = 4) :: longval\n \n !eight byte integer\n integer(kind = 8) :: verylongval\n \n !sixteen byte integer\n integer(kind = 16) :: veryverylongval\n \n !default integer \n integer :: defval\n \n print *, huge(shortval)\n print *, huge(longval)\n print *, huge(verylongval)\n print *, huge(veryverylongval)\n print *, huge(defval)\n \nend program testingInt" }, { "code": null, "e": 3409, "s": 3327, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 3498, "s": 3409, "text": "32767\n2147483647\n9223372036854775807\n170141183460469231731687303715884105727\n2147483647\n" }, { "code": null, "e": 3572, "s": 3498, "text": "It stores the floating point numbers, such as 2.0, 3.1415, -100.876, etc." }, { "code": null, "e": 3673, "s": 3572, "text": "Traditionally there were two different real types : the default real type and double precision type." }, { "code": null, "e": 3825, "s": 3673, "text": "However, Fortran 90/95 provides more control over the precision of real and integer data types through the kind specifier, which we will study shortly." }, { "code": null, "e": 3881, "s": 3825, "text": "The following example shows the use of real data type −" }, { "code": null, "e": 4253, "s": 3881, "text": "program division \nimplicit none\n\n ! Define real variables \n real :: p, q, realRes \n \n ! Define integer variables \n integer :: i, j, intRes \n \n ! Assigning values \n p = 2.0 \n q = 3.0 \n i = 2 \n j = 3 \n \n ! floating point division\n realRes = p/q \n intRes = i/j\n \n print *, realRes\n print *, intRes\n \nend program division " }, { "code": null, "e": 4335, "s": 4253, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 4354, "s": 4335, "text": "0.666666687 \n0\n" }, { "code": null, "e": 4528, "s": 4354, "text": "This is used for storing complex numbers. A complex number has two parts : the real part and the imaginary part. Two consecutive numeric storage units store these two parts." }, { "code": null, "e": 4595, "s": 4528, "text": "For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i" }, { "code": null, "e": 4773, "s": 4595, "text": "The generic function cmplx() creates a complex number. It produces a result who’s real and imaginary parts are single precision, irrespective of the type of the input arguments." }, { "code": null, "e": 4905, "s": 4773, "text": "program createComplex\nimplicit none\n\n integer :: i = 10\n real :: x = 5.17\n print *, cmplx(i, x)\n \nend program createComplex" }, { "code": null, "e": 4987, "s": 4905, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 5013, "s": 4987, "text": "(10.0000000, 5.17000008)\n" }, { "code": null, "e": 5076, "s": 5013, "text": "The following program demonstrates complex number arithmetic −" }, { "code": null, "e": 5479, "s": 5076, "text": "program ComplexArithmatic\nimplicit none\n\n complex, parameter :: i = (0, 1) ! sqrt(-1) \n complex :: x, y, z \n \n x = (7, 8); \n y = (5, -7) \n write(*,*) i * x * y\n \n z = x + y\n print *, \"z = x + y = \", z\n \n z = x - y\n print *, \"z = x - y = \", z \n \n z = x * y\n print *, \"z = x * y = \", z \n \n z = x / y\n print *, \"z = x / y = \", z \n \nend program ComplexArithmatic" }, { "code": null, "e": 5561, "s": 5479, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 5738, "s": 5561, "text": "(9.00000000, 91.0000000)\nz = x + y = (12.0000000, 1.00000000)\nz = x - y = (2.00000000, 15.0000000)\nz = x * y = (91.0000000, -9.00000000)\nz = x / y = (-0.283783793, 1.20270276)\n" }, { "code": null, "e": 5888, "s": 5738, "text": "The range on integer numbers, the precision and the size of floating point numbers depends on the number of bits allocated to the specific data type." }, { "code": null, "e": 5961, "s": 5888, "text": "The following table displays the number of bits and range for integers −" }, { "code": null, "e": 6074, "s": 5961, "text": "The following table displays the number of bits, smallest and largest value, and the precision for real numbers." }, { "code": null, "e": 6116, "s": 6074, "text": "The following examples demonstrate this −" }, { "code": null, "e": 6262, "s": 6116, "text": "program rangePrecision\nimplicit none\n\n real:: x, y, z\n x = 1.5e+40\n y = 3.73e+40\n z = x * y \n print *, z\n \nend program rangePrecision" }, { "code": null, "e": 6344, "s": 6262, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 6507, "s": 6344, "text": "x = 1.5e+40\n 1\nError : Real constant overflows its kind at (1)\nmain.f95:5.12:\n\ny = 3.73e+40\n 1\nError : Real constant overflows its kind at (1)\n" }, { "code": null, "e": 6541, "s": 6507, "text": "Now let us use a smaller number −" }, { "code": null, "e": 6716, "s": 6541, "text": "program rangePrecision\nimplicit none\n\n real:: x, y, z\n x = 1.5e+20\n y = 3.73e+20\n z = x * y \n print *, z\n \n z = x/y\n print *, z\n \nend program rangePrecision" }, { "code": null, "e": 6798, "s": 6716, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 6823, "s": 6798, "text": "Infinity\n0.402144760 \n" }, { "code": null, "e": 6851, "s": 6823, "text": "Now let’s watch underflow −" }, { "code": null, "e": 7023, "s": 6851, "text": "program rangePrecision\nimplicit none\n\n real:: x, y, z\n x = 1.5e-30\n y = 3.73e-60\n z = x * y \n print *, z\n \n z = x/y\n print *, z\n\nend program rangePrecision" }, { "code": null, "e": 7105, "s": 7023, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 7242, "s": 7105, "text": "y = 3.73e-60\n 1\nWarning : Real constant underflows its kind at (1)\n\nExecuting the program....\n$demo \n\n0.00000000E+00\nInfinity\n" }, { "code": null, "e": 7383, "s": 7242, "text": "In scientific programming, one often needs to know the range and precision of data of the hardware platform on which the work is being done." }, { "code": null, "e": 7510, "s": 7383, "text": "The intrinsic function kind() allows you to query the details of the hardware’s data representations before running a program." }, { "code": null, "e": 7718, "s": 7510, "text": "program kindCheck\nimplicit none\n \n integer :: i \n real :: r \n complex :: cp \n print *,' Integer ', kind(i) \n print *,' Real ', kind(r) \n print *,' Complex ', kind(cp) \n \nend program kindCheck" }, { "code": null, "e": 7800, "s": 7718, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 7828, "s": 7800, "text": "Integer 4\nReal 4\nComplex 4\n" }, { "code": null, "e": 7876, "s": 7828, "text": "You can also check the kind of all data types −" }, { "code": null, "e": 8189, "s": 7876, "text": "program checkKind\nimplicit none\n\n integer :: i \n real :: r \n character :: c \n logical :: lg \n complex :: cp \n \n print *,' Integer ', kind(i) \n print *,' Real ', kind(r) \n print *,' Complex ', kind(cp)\n print *,' Character ', kind(c) \n print *,' Logical ', kind(lg)\n \nend program checkKind" }, { "code": null, "e": 8271, "s": 8189, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 8321, "s": 8271, "text": "Integer 4\nReal 4\nComplex 4\nCharacter 1\nLogical 4\n" }, { "code": null, "e": 8328, "s": 8321, "text": " Print" }, { "code": null, "e": 8339, "s": 8328, "text": " Add Notes" } ]
Intersect two lists in C#
Firstly, set two lists. List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 }; List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 }; Now, use the Intersect() method to get the intersection between two lists. IEnumerable<int> res = val1.AsQueryable().Intersect(val2); Live Demo using System; using System.Collections.Generic; using System.Linq; class Demo { static void Main() { List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 }; List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 }; IEnumerable<int> res = val1.AsQueryable().Intersect(val2); Console.WriteLine("Intersection of both the lists..."); foreach (int a in res) { Console.WriteLine(a); } } } Intersection of both the lists... 40 95 110
[ { "code": null, "e": 1086, "s": 1062, "text": "Firstly, set two lists." }, { "code": null, "e": 1215, "s": 1086, "text": "List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };\nList<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };" }, { "code": null, "e": 1290, "s": 1215, "text": "Now, use the Intersect() method to get the intersection between two lists." }, { "code": null, "e": 1349, "s": 1290, "text": "IEnumerable<int> res = val1.AsQueryable().Intersect(val2);" }, { "code": null, "e": 1360, "s": 1349, "text": " Live Demo" }, { "code": null, "e": 1810, "s": 1360, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Demo {\n static void Main() {\n List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };\n List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };\n IEnumerable<int> res = val1.AsQueryable().Intersect(val2);\n Console.WriteLine(\"Intersection of both the lists...\");\n foreach (int a in res) {\n Console.WriteLine(a);\n }\n }\n}" }, { "code": null, "e": 1854, "s": 1810, "text": "Intersection of both the lists...\n40\n95\n110" } ]
Calendar setTimeInMillis() Method in Java with Examples - GeeksforGeeks
06 Mar, 2019 The setTimeInMillis(long mill_sec) method in Calendar class is used to set Calendars time represented by this Calendar from the passed long value. Syntax: public void setTimeInMillis(long mill_sec) Parameters: The method takes one parameter mill_sec of long datat-type and refers to the given date that is to be set. Return Value: The method does not return any value. Below programs illustrate the working of setTimeInMillis() Method of Calendar class:Example 1: // Java code to illustrate// setTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) { // Creating calendar object Calendar calndr = Calendar.getInstance(); // Getting the time in milliseconds System.out.println("The Current" + " Time is: " + calndr.getTime()); // Changing time to 2000 milli-second calndr.setTimeInMillis(2000); // Displaying the new time System.out.println("After setting" + " Time: " + calndr.getTime()); }} The Current Time is: Fri Feb 22 08:00:54 UTC 2019 After setting Time: Thu Jan 01 00:00:02 UTC 1970 Example 2: // Java code to illustrate// setTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) { // Creating calendar object Calendar calndr = Calendar.getInstance(); // Getting the time in milliseconds System.out.println("The Current" + " Time is: " + calndr.getTime()); // Changing time to 8000 milli-second calndr.setTimeInMillis(8000); // Displaying the new time System.out.println("After setting" + " Time: " + calndr.getTime()); }} The Current Time is: Fri Feb 22 08:01:02 UTC 2019 After setting Time: Thu Jan 01 00:00:08 UTC 1970 Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long) Java - util package Java-Calendar Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java Internal Working of HashMap in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n06 Mar, 2019" }, { "code": null, "e": 25494, "s": 25347, "text": "The setTimeInMillis(long mill_sec) method in Calendar class is used to set Calendars time represented by this Calendar from the passed long value." }, { "code": null, "e": 25502, "s": 25494, "text": "Syntax:" }, { "code": null, "e": 25545, "s": 25502, "text": "public void setTimeInMillis(long mill_sec)" }, { "code": null, "e": 25664, "s": 25545, "text": "Parameters: The method takes one parameter mill_sec of long datat-type and refers to the given date that is to be set." }, { "code": null, "e": 25716, "s": 25664, "text": "Return Value: The method does not return any value." }, { "code": null, "e": 25811, "s": 25716, "text": "Below programs illustrate the working of setTimeInMillis() Method of Calendar class:Example 1:" }, { "code": "// Java code to illustrate// setTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) { // Creating calendar object Calendar calndr = Calendar.getInstance(); // Getting the time in milliseconds System.out.println(\"The Current\" + \" Time is: \" + calndr.getTime()); // Changing time to 2000 milli-second calndr.setTimeInMillis(2000); // Displaying the new time System.out.println(\"After setting\" + \" Time: \" + calndr.getTime()); }}", "e": 26475, "s": 25811, "text": null }, { "code": null, "e": 26575, "s": 26475, "text": "The Current Time is: Fri Feb 22 08:00:54 UTC 2019\nAfter setting Time: Thu Jan 01 00:00:02 UTC 1970\n" }, { "code": null, "e": 26586, "s": 26575, "text": "Example 2:" }, { "code": "// Java code to illustrate// setTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) { // Creating calendar object Calendar calndr = Calendar.getInstance(); // Getting the time in milliseconds System.out.println(\"The Current\" + \" Time is: \" + calndr.getTime()); // Changing time to 8000 milli-second calndr.setTimeInMillis(8000); // Displaying the new time System.out.println(\"After setting\" + \" Time: \" + calndr.getTime()); }}", "e": 27250, "s": 26586, "text": null }, { "code": null, "e": 27350, "s": 27250, "text": "The Current Time is: Fri Feb 22 08:01:02 UTC 2019\nAfter setting Time: Thu Jan 01 00:00:08 UTC 1970\n" }, { "code": null, "e": 27449, "s": 27350, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long)" }, { "code": null, "e": 27469, "s": 27449, "text": "Java - util package" }, { "code": null, "e": 27483, "s": 27469, "text": "Java-Calendar" }, { "code": null, "e": 27498, "s": 27483, "text": "Java-Functions" }, { "code": null, "e": 27503, "s": 27498, "text": "Java" }, { "code": null, "e": 27508, "s": 27503, "text": "Java" }, { "code": null, "e": 27606, "s": 27508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27621, "s": 27606, "text": "Stream In Java" }, { "code": null, "e": 27640, "s": 27621, "text": "Exceptions in Java" }, { "code": null, "e": 27661, "s": 27640, "text": "Constructors in Java" }, { "code": null, "e": 27691, "s": 27661, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27737, "s": 27691, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27754, "s": 27737, "text": "Generics in Java" }, { "code": null, "e": 27775, "s": 27754, "text": "Introduction to Java" }, { "code": null, "e": 27818, "s": 27775, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27840, "s": 27818, "text": "PriorityQueue in Java" } ]
C Program For Stock Buy Sell To Maximize Profit - GeeksforGeeks
30 Dec, 2021 Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem. Find the local minima and store it as starting index. If not exists, return.Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached. Find the local minima and store it as starting index. If not exists, return. Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index. Update the solution (Increment count of buy-sell pairs) Repeat the above steps if the end is not reached. C // Program to find best buying and // selling days#include <stdio.h> // Solution structurestruct Interval { int buy; int sell;}; // This function finds the buy and sell // schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at // least two days if (n == 1) return; // Count of solution pairs int count = 0; // Solution vector Interval sol[n / 2 + 1]; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the // limit is (n-2) as we are comparing // present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no // further solution possible if (i == n - 1) break; // Store the index of minima sol[count].buy = i++; // Find Local Maxima. Note that the // limit is (n-1) as we are comparing // to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima sol[count].sell = i - 1; // Increment count of buy/sell pairs count++; } // Print solution if (count == 0) printf( "There is no day when buying the stock will make profitn"); else { for (int i = 0; i < count; i++) printf( "Buy on day: %dt Sell on day: %dn", sol[i].buy, sol[i].sell); } return;} // Driver codeint main(){ // Stock prices on consecutive days int price[] = {100, 180, 260, 310, 40, 535, 695}; int n = sizeof(price) / sizeof(price[0]); // Function call stockBuySell(price, n); return 0;} Output: Buy on day: 0 Sell on day: 3 Buy on day: 4 Sell on day: 6 Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n) Please refer complete article on Stock Buy Sell to Maximize Profit for more details! Accolite Amazon Directi Flipkart Goldman Sachs Hike MakeMyTrip Microsoft Morgan Stanley Ola Cabs Oracle Paytm Pubmatic Quikr Samsung SAP Labs Sapient Swiggy Walmart Arrays C Programs Paytm Flipkart Morgan Stanley Accolite Amazon Microsoft Samsung Hike MakeMyTrip Ola Cabs Oracle Walmart Goldman Sachs Directi SAP Labs Quikr Pubmatic Sapient Swiggy Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File UDP Server-Client implementation in C
[ { "code": null, "e": 26151, "s": 26123, "text": "\n30 Dec, 2021" }, { "code": null, "e": 26393, "s": 26151, "text": "Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem. " }, { "code": null, "e": 26683, "s": 26393, "text": "Find the local minima and store it as starting index. If not exists, return.Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached." }, { "code": null, "e": 26760, "s": 26683, "text": "Find the local minima and store it as starting index. If not exists, return." }, { "code": null, "e": 26870, "s": 26760, "text": "Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index." }, { "code": null, "e": 26926, "s": 26870, "text": "Update the solution (Increment count of buy-sell pairs)" }, { "code": null, "e": 26976, "s": 26926, "text": "Repeat the above steps if the end is not reached." }, { "code": null, "e": 26978, "s": 26976, "text": "C" }, { "code": "// Program to find best buying and // selling days#include <stdio.h> // Solution structurestruct Interval { int buy; int sell;}; // This function finds the buy and sell // schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at // least two days if (n == 1) return; // Count of solution pairs int count = 0; // Solution vector Interval sol[n / 2 + 1]; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the // limit is (n-2) as we are comparing // present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no // further solution possible if (i == n - 1) break; // Store the index of minima sol[count].buy = i++; // Find Local Maxima. Note that the // limit is (n-1) as we are comparing // to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima sol[count].sell = i - 1; // Increment count of buy/sell pairs count++; } // Print solution if (count == 0) printf( \"There is no day when buying the stock will make profitn\"); else { for (int i = 0; i < count; i++) printf( \"Buy on day: %dt Sell on day: %dn\", sol[i].buy, sol[i].sell); } return;} // Driver codeint main(){ // Stock prices on consecutive days int price[] = {100, 180, 260, 310, 40, 535, 695}; int n = sizeof(price) / sizeof(price[0]); // Function call stockBuySell(price, n); return 0;}", "e": 28794, "s": 26978, "text": null }, { "code": null, "e": 28802, "s": 28794, "text": "Output:" }, { "code": null, "e": 28868, "s": 28802, "text": "Buy on day: 0 Sell on day: 3\nBuy on day: 4 Sell on day: 6" }, { "code": null, "e": 29020, "s": 28868, "text": "Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)" }, { "code": null, "e": 29105, "s": 29020, "text": "Please refer complete article on Stock Buy Sell to Maximize Profit for more details!" }, { "code": null, "e": 29114, "s": 29105, "text": "Accolite" }, { "code": null, "e": 29121, "s": 29114, "text": "Amazon" }, { "code": null, "e": 29129, "s": 29121, "text": "Directi" }, { "code": null, "e": 29138, "s": 29129, "text": "Flipkart" }, { "code": null, "e": 29152, "s": 29138, "text": "Goldman Sachs" }, { "code": null, "e": 29157, "s": 29152, "text": "Hike" }, { "code": null, "e": 29168, "s": 29157, "text": "MakeMyTrip" }, { "code": null, "e": 29178, "s": 29168, "text": "Microsoft" }, { "code": null, "e": 29193, "s": 29178, "text": "Morgan Stanley" }, { "code": null, "e": 29202, "s": 29193, "text": "Ola Cabs" }, { "code": null, "e": 29209, "s": 29202, "text": "Oracle" }, { "code": null, "e": 29215, "s": 29209, "text": "Paytm" }, { "code": null, "e": 29224, "s": 29215, "text": "Pubmatic" }, { "code": null, "e": 29230, "s": 29224, "text": "Quikr" }, { "code": null, "e": 29238, "s": 29230, "text": "Samsung" }, { "code": null, "e": 29247, "s": 29238, "text": "SAP Labs" }, { "code": null, "e": 29255, "s": 29247, "text": "Sapient" }, { "code": null, "e": 29262, "s": 29255, "text": "Swiggy" }, { "code": null, "e": 29270, "s": 29262, "text": "Walmart" }, { "code": null, "e": 29277, "s": 29270, "text": "Arrays" }, { "code": null, "e": 29288, "s": 29277, "text": "C Programs" }, { "code": null, "e": 29294, "s": 29288, "text": "Paytm" }, { "code": null, "e": 29303, "s": 29294, "text": "Flipkart" }, { "code": null, "e": 29318, "s": 29303, "text": "Morgan Stanley" }, { "code": null, "e": 29327, "s": 29318, "text": "Accolite" }, { "code": null, "e": 29334, "s": 29327, "text": "Amazon" }, { "code": null, "e": 29344, "s": 29334, "text": "Microsoft" }, { "code": null, "e": 29352, "s": 29344, "text": "Samsung" }, { "code": null, "e": 29357, "s": 29352, "text": "Hike" }, { "code": null, "e": 29368, "s": 29357, "text": "MakeMyTrip" }, { "code": null, "e": 29377, "s": 29368, "text": "Ola Cabs" }, { "code": null, "e": 29384, "s": 29377, "text": "Oracle" }, { "code": null, "e": 29392, "s": 29384, "text": "Walmart" }, { "code": null, "e": 29406, "s": 29392, "text": "Goldman Sachs" }, { "code": null, "e": 29414, "s": 29406, "text": "Directi" }, { "code": null, "e": 29423, "s": 29414, "text": "SAP Labs" }, { "code": null, "e": 29429, "s": 29423, "text": "Quikr" }, { "code": null, "e": 29438, "s": 29429, "text": "Pubmatic" }, { "code": null, "e": 29446, "s": 29438, "text": "Sapient" }, { "code": null, "e": 29453, "s": 29446, "text": "Swiggy" }, { "code": null, "e": 29460, "s": 29453, "text": "Arrays" }, { "code": null, "e": 29558, "s": 29460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29589, "s": 29558, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 29627, "s": 29589, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 29652, "s": 29627, "text": "Window Sliding Technique" }, { "code": null, "e": 29673, "s": 29652, "text": "Next Greater Element" }, { "code": null, "e": 29731, "s": 29673, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 29744, "s": 29731, "text": "Strings in C" }, { "code": null, "e": 29785, "s": 29744, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29820, "s": 29785, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 29861, "s": 29820, "text": "C Program to read contents of Whole File" } ]
Set Theory & Algebra - GeeksforGeeks
21 Jan, 2014 * a b c d a a b c d b b a d c c c d b a d d c a b Check for all:- a1 = a , a2 = a * a = a a3 = a2 * a = a * a = a a is not the generator since we are not able to express other members of the group in powers of a Check for c - c1 = c c2 = c * c = b c3 = c2 * c = b * c = d c4 = c2 * c2 = b * b = a We are able to generate all the members of the group from c , Hence c is the generator Similarly check for d If P, Q, R are subsets of the universal set U, then U Pc U Qc U Rc P U Qc U Rc Qc U Rc Consider an example set, S = (1,2,3) Equivalence property follows, reflexive, symmetric and transitive Largest ordered set are s x s = { (1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3) } which are 9 which equal to 3^2 = n^2 Smallest ordered set are { (1,1) (2,2) ( 3,3)} which are 3 and equals to n. number of elements. 2 can be written as 2 power 2. Number of partitioning of 2 = no. of non isomorphic abelian groups 2 can be partitioned as {(2),(1,1)} D C B A A partition is said to refine another partition if it splits the sets in the second partition to a larger number of sets. Corresponding Hasse diagram is Option C. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 31896, "s": 31868, "text": "\n21 Jan, 2014" }, { "code": null, "e": 31898, "s": 31896, "text": "*" }, { "code": null, "e": 31900, "s": 31898, "text": "a" }, { "code": null, "e": 31902, "s": 31900, "text": "b" }, { "code": null, "e": 31904, "s": 31902, "text": "c" }, { "code": null, "e": 31906, "s": 31904, "text": "d" }, { "code": null, "e": 31908, "s": 31906, "text": "a" }, { "code": null, "e": 31910, "s": 31908, "text": "a" }, { "code": null, "e": 31912, "s": 31910, "text": "b" }, { "code": null, "e": 31914, "s": 31912, "text": "c" }, { "code": null, "e": 31916, "s": 31914, "text": "d" }, { "code": null, "e": 31918, "s": 31916, "text": "b" }, { "code": null, "e": 31920, "s": 31918, "text": "b" }, { "code": null, "e": 31922, "s": 31920, "text": "a" }, { "code": null, "e": 31924, "s": 31922, "text": "d" }, { "code": null, "e": 31926, "s": 31924, "text": "c" }, { "code": null, "e": 31928, "s": 31926, "text": "c" }, { "code": null, "e": 31930, "s": 31928, "text": "c" }, { "code": null, "e": 31932, "s": 31930, "text": "d" }, { "code": null, "e": 31934, "s": 31932, "text": "b" }, { "code": null, "e": 31936, "s": 31934, "text": "a" }, { "code": null, "e": 31938, "s": 31936, "text": "d" }, { "code": null, "e": 31940, "s": 31938, "text": "d" }, { "code": null, "e": 31942, "s": 31940, "text": "c" }, { "code": null, "e": 31944, "s": 31942, "text": "a" }, { "code": null, "e": 31946, "s": 31944, "text": "b" }, { "code": null, "e": 32306, "s": 31946, "text": "Check for all:-\na1 = a ,\na2 = a * a = a\na3 = a2 * a = a * a = a\na is not the generator since we are not able to express \nother members of the group in powers of a\n\nCheck for c -\nc1 = c\nc2 = c * c = b\nc3 = c2 * c = b * c = d\nc4 = c2 * c2 = b * b = a\nWe are able to generate all the members of the group from c ,\nHence c is the generator\n\nSimilarly check for d\n" }, { "code": null, "e": 32359, "s": 32306, "text": "If P, Q, R are subsets of the universal set U, then " }, { "code": null, "e": 32366, "s": 32363, "text": "U " }, { "code": null, "e": 32380, "s": 32366, "text": "Pc U Qc U Rc " }, { "code": null, "e": 32393, "s": 32380, "text": "P U Qc U Rc " }, { "code": null, "e": 32402, "s": 32393, "text": "Qc U Rc " }, { "code": null, "e": 32733, "s": 32402, "text": "Consider an example set, S = (1,2,3)\n\nEquivalence property follows, reflexive, symmetric\nand transitive\n\nLargest ordered set are s x s = \n{ (1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) \n(3,3) } which are 9 which equal to 3^2 = n^2\n\nSmallest ordered set are { (1,1) (2,2) ( 3,3)}\nwhich are 3 and equals to n. number of elements." }, { "code": null, "e": 32897, "s": 32733, "text": "2 can be written as 2 power 2.\nNumber of partitioning of 2 = no. of non isomorphic\n abelian groups\n2 can be partitioned as {(2),(1,1)}" }, { "code": null, "e": 32900, "s": 32897, "text": "D " }, { "code": null, "e": 32903, "s": 32900, "text": "C " }, { "code": null, "e": 32906, "s": 32903, "text": "B " }, { "code": null, "e": 32909, "s": 32906, "text": "A " }, { "code": null, "e": 33073, "s": 32909, "text": "A partition is said to refine another partition if it splits the sets in the second partition to a larger number of sets. Corresponding Hasse diagram is Option C. " } ]
One-Way ANOVA
18 Apr, 2022 ANOVA is a parametric statistical technique that helps in finding out if there is a significant difference between the mean of three or more groups. It checks the impact of various factors by comparing groups (samples) on the basis of their respective mean. We can use this only when: the samples have a normal distribution. the samples are selected at random and should be independent of one another. all groups have equal standard deviations. One-Way ANOVA It is a type of hypothesis test where only one factor is considered. We use F-statistic to perform a one-way analysis of variance. Steps Involved Step 1 - Define the null and alternative hypothesis. H0 -> μ1 = μ2 = μ3 (where μ = mean) Ha -> At least one difference among the means. Step 2 - Find the degree of freedom between and within the groups. [Using Eq-1 and Eq-2] Then find total degree of freedom. [Using Eq-3] Eq-1 where k = number of groups. Eq-2 where n = number of samples in all groups combined. k = number of groups. Eq-3 For the next step, we need to understand what F-statistic is. F-value: It is defined as the ratio of the variance between samples to variance within samples. It is obtained while performing ANOVA test. Eq-4 shows the F-value formula for one-way ANOVA. Eq – 4 Step 3 - Refer the F-Distribution table and find Ftable using dfbetween and dfwithin. As per the given F-Distribution table, df1 = dfbetween df2 = dfwithin [use the given value of α while referring the table.] Step 4 - Find the mean of all samples in each group. Then use Eq-5 to find the Grand mean. (μGrand) Eq – 5 where, ∑G = sum of all sample values. n = number of samples. Step 5 - Find the sum of squares total using Eq-6 and sum of squares within using Eq-7. Then find sum of squares between using Eq-8. Eq-6 where, xi = ith sample Eq-7 where, xi = ith sample. μi = mean of ith group. Eq-8 Step 6 - Find the variance (μ2 or S2) between and within samples using Eq-9 and Eq-10. Eq-9 Eq-10 Step 7 - Find Fcalc using Eq-11. Eq-11 Interpreting the results if Fcalc < Ftable : Don't reject null hypothesis. μ1 = μ2 = μ3 if Fcalc > Ftable : Reject null hypothesis. Example Problem Consider the example given below to understand step by step how to perform this test. The marks of 3 subjects (out of 5) for a group of students is recorded. (as given in the table below) [Take α = 0.05] 2 2 1 4 3 2 2 4 5 Step 1 - Null hypothesis, H0 -> μE = μM = μS (where μ = mean) Alternate hypothesis, Ha -> At least one difference among the means of the 3 subjects. Step 2 - As per the table, k = 3 n = 9 dfbetween = 3 - 1 = 2 [Eq-1] dfwithin = 9 - 3 = 6 [Eq-2] dftotal = 2 + 6 = 8 [Eq-3] Step 3 - On referring to the F-Distribution table (link), using df1 = 2 and df2 = 6 at α = 0.05: we get, Ftable = 5.14 Step 4 - μe = (2 + 4 + 2)/3 = (8/3) = 2.67 μm = (2 + 3 + 4)/3 = (9/3) = 3.00 μs = (1 + 2 + 5)/3 = (8/3) = 2.67 μgrand = (8 + 8 + 9)/9 = (25/9) = 2.78 Step 5 - SStotal = (2 - 2.78)2 + (4 - 2.78)2 + (2 - 2.78)2 + (2 - 2.78)2 + (3 - 2.78)2 + (4 - 2.78)2 + (1 - 2.78)2 + (2 - 2.78)2 + (5 - 2.78)2 = 13.60 SSwithin = (2 - 2.67)2 + (4 - 2.67)2 + (2 - 2.67)2 + (2 - 3.00)2 + (3 - 3.00)2 + (4 - 3.00)2 + (1 - 2.67)2 + (2 - 2.67)2 + (5 - 2.67)2 = 13.34 SSbetween = 13.60 - 13.34 = 0.23 Step 6 - S2between = (0.23/2) = 0.12 S2within = (13.34/6) = 2.22 Step 7 - Fcalc = (0.12/2.22) = 0.05 Since, Fcalc < Ftable (0.05 < 5.14) we cannot reject the null hypothesis. Thus, we can say that the means of all three subjects is the same. One-way ANOVA compares three or more than three categorical groups to establish whether there is a difference between them. The fundamental strategy of ANOVA is to systematically examine variability within groups being compared and also examine variability among the groups being compared. For any doubt/query, comment below. sumitgumber28 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Support Vector Machine Algorithm Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI Python | Linear Regression using sklearn
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Apr, 2022" }, { "code": null, "e": 287, "s": 28, "text": "ANOVA is a parametric statistical technique that helps in finding out if there is a significant difference between the mean of three or more groups. It checks the impact of various factors by comparing groups (samples) on the basis of their respective mean. " }, { "code": null, "e": 315, "s": 287, "text": "We can use this only when: " }, { "code": null, "e": 355, "s": 315, "text": "the samples have a normal distribution." }, { "code": null, "e": 432, "s": 355, "text": "the samples are selected at random and should be independent of one another." }, { "code": null, "e": 475, "s": 432, "text": "all groups have equal standard deviations." }, { "code": null, "e": 489, "s": 475, "text": "One-Way ANOVA" }, { "code": null, "e": 621, "s": 489, "text": "It is a type of hypothesis test where only one factor is considered. We use F-statistic to perform a one-way analysis of variance. " }, { "code": null, "e": 636, "s": 621, "text": "Steps Involved" }, { "code": null, "e": 774, "s": 636, "text": "Step 1 - Define the null and alternative hypothesis. \n\nH0 -> μ1 = μ2 = μ3 (where μ = mean)\nHa -> At least one difference among the means." }, { "code": null, "e": 916, "s": 774, "text": "Step 2 - Find the degree of freedom between and within the groups. [Using Eq-1 and Eq-2]\n Then find total degree of freedom. [Using Eq-3]" }, { "code": null, "e": 921, "s": 916, "text": "Eq-1" }, { "code": null, "e": 950, "s": 921, "text": "where k = number of groups. " }, { "code": null, "e": 955, "s": 950, "text": "Eq-2" }, { "code": null, "e": 1031, "s": 955, "text": "where \nn = number of samples in all groups combined.\nk = number of groups. " }, { "code": null, "e": 1036, "s": 1031, "text": "Eq-3" }, { "code": null, "e": 1099, "s": 1036, "text": "For the next step, we need to understand what F-statistic is. " }, { "code": null, "e": 1289, "s": 1099, "text": "F-value: It is defined as the ratio of the variance between samples to variance within samples. It is obtained while performing ANOVA test. Eq-4 shows the F-value formula for one-way ANOVA." }, { "code": null, "e": 1296, "s": 1289, "text": "Eq – 4" }, { "code": null, "e": 1518, "s": 1296, "text": "Step 3 - Refer the F-Distribution table and find Ftable using dfbetween and dfwithin. \nAs per the given F-Distribution table, \n df1 = dfbetween\n df2 = dfwithin \n[use the given value of α while referring the table.]" }, { "code": null, "e": 1620, "s": 1518, "text": "Step 4 - Find the mean of all samples in each group. \n Then use Eq-5 to find the Grand mean. (μGrand)" }, { "code": null, "e": 1627, "s": 1620, "text": "Eq – 5" }, { "code": null, "e": 1688, "s": 1627, "text": "where,\n∑G = sum of all sample values.\nn = number of samples." }, { "code": null, "e": 1826, "s": 1688, "text": "Step 5 - Find the sum of squares total using Eq-6 and sum of squares within using Eq-7.\n Then find sum of squares between using Eq-8." }, { "code": null, "e": 1831, "s": 1826, "text": "Eq-6" }, { "code": null, "e": 1854, "s": 1831, "text": "where, xi = ith sample" }, { "code": null, "e": 1859, "s": 1854, "text": "Eq-7" }, { "code": null, "e": 1909, "s": 1859, "text": "where, \nxi = ith sample.\nμi = mean of ith group. " }, { "code": null, "e": 1914, "s": 1909, "text": "Eq-8" }, { "code": null, "e": 2001, "s": 1914, "text": "Step 6 - Find the variance (μ2 or S2) between and within samples using Eq-9 and Eq-10." }, { "code": null, "e": 2006, "s": 2001, "text": "Eq-9" }, { "code": null, "e": 2012, "s": 2006, "text": "Eq-10" }, { "code": null, "e": 2046, "s": 2012, "text": "Step 7 - Find Fcalc using Eq-11. " }, { "code": null, "e": 2052, "s": 2046, "text": "Eq-11" }, { "code": null, "e": 2077, "s": 2052, "text": "Interpreting the results" }, { "code": null, "e": 2201, "s": 2077, "text": "if Fcalc < Ftable :\n Don't reject null hypothesis.\n μ1 = μ2 = μ3\n \nif Fcalc > Ftable :\n Reject null hypothesis." }, { "code": null, "e": 2218, "s": 2201, "text": "Example Problem " }, { "code": null, "e": 2422, "s": 2218, "text": "Consider the example given below to understand step by step how to perform this test. The marks of 3 subjects (out of 5) for a group of students is recorded. (as given in the table below) [Take α = 0.05]" }, { "code": null, "e": 2424, "s": 2422, "text": "2" }, { "code": null, "e": 2426, "s": 2424, "text": "2" }, { "code": null, "e": 2428, "s": 2426, "text": "1" }, { "code": null, "e": 2430, "s": 2428, "text": "4" }, { "code": null, "e": 2432, "s": 2430, "text": "3" }, { "code": null, "e": 2434, "s": 2432, "text": "2" }, { "code": null, "e": 2436, "s": 2434, "text": "2" }, { "code": null, "e": 2438, "s": 2436, "text": "4" }, { "code": null, "e": 2440, "s": 2438, "text": "5" }, { "code": null, "e": 2594, "s": 2440, "text": "Step 1 -\nNull hypothesis, H0 -> μE = μM = μS (where μ = mean)\nAlternate hypothesis, Ha -> At least one difference among the means of the 3 subjects." }, { "code": null, "e": 2720, "s": 2594, "text": "Step 2 -\nAs per the table, \nk = 3\nn = 9\ndfbetween = 3 - 1 = 2 [Eq-1]\ndfwithin = 9 - 3 = 6 [Eq-2]\ndftotal = 2 + 6 = 8 [Eq-3]" }, { "code": null, "e": 2841, "s": 2720, "text": "Step 3 - On referring to the F-Distribution table (link), using df1 = 2 \n and df2 = 6 at α = 0.05: we get, Ftable = 5.14" }, { "code": null, "e": 3011, "s": 2841, "text": "Step 4 - μe = (2 + 4 + 2)/3 = (8/3) = 2.67\n μm = (2 + 3 + 4)/3 = (9/3) = 3.00\n μs = (1 + 2 + 5)/3 = (8/3) = 2.67\n \n μgrand = (8 + 8 + 9)/9 = (25/9) = 2.78" }, { "code": null, "e": 3435, "s": 3011, "text": "Step 5 - SStotal = (2 - 2.78)2 + (4 - 2.78)2 + (2 - 2.78)2 +\n (2 - 2.78)2 + (3 - 2.78)2 + (4 - 2.78)2 +\n (1 - 2.78)2 + (2 - 2.78)2 + (5 - 2.78)2 \n = 13.60\n \n SSwithin = (2 - 2.67)2 + (4 - 2.67)2 + (2 - 2.67)2 +\n (2 - 3.00)2 + (3 - 3.00)2 + (4 - 3.00)2 +\n (1 - 2.67)2 + (2 - 2.67)2 + (5 - 2.67)2 \n = 13.34\n \n SSbetween = 13.60 - 13.34 = 0.23" }, { "code": null, "e": 3506, "s": 3435, "text": "Step 6 - S2between = (0.23/2) = 0.12 \n S2within = (13.34/6) = 2.22" }, { "code": null, "e": 3543, "s": 3506, "text": "Step 7 - Fcalc = (0.12/2.22) = 0.05 " }, { "code": null, "e": 3622, "s": 3543, "text": "Since, Fcalc < Ftable (0.05 < 5.14)\n we cannot reject the null hypothesis. " }, { "code": null, "e": 3689, "s": 3622, "text": "Thus, we can say that the means of all three subjects is the same." }, { "code": null, "e": 4016, "s": 3689, "text": "One-way ANOVA compares three or more than three categorical groups to establish whether there is a difference between them. The fundamental strategy of ANOVA is to systematically examine variability within groups being compared and also examine variability among the groups being compared. For any doubt/query, comment below. " }, { "code": null, "e": 4030, "s": 4016, "text": "sumitgumber28" }, { "code": null, "e": 4047, "s": 4030, "text": "Machine Learning" }, { "code": null, "e": 4064, "s": 4047, "text": "Machine Learning" }, { "code": null, "e": 4162, "s": 4064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4203, "s": 4162, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4239, "s": 4203, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4272, "s": 4239, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4296, "s": 4272, "text": "Markov Decision Process" }, { "code": null, "e": 4347, "s": 4296, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 4380, "s": 4347, "text": "Normalization vs Standardization" }, { "code": null, "e": 4420, "s": 4380, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 4461, "s": 4420, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 4489, "s": 4461, "text": "Types of Environments in AI" } ]
Python – Fill list characters in String
29 Aug, 2020 Given String and list, construct a string with only list values filled. Input : test_str = “geeksforgeeks”, fill_list = [‘g’, ‘s’, ‘f’, k]Output : g__ksf__g__ksExplanation : All occurrences are filled in their position of g, s, f and k. Input : test_str = “geeksforgeeks”, fill_list = [‘g’, ‘s’]Output : g___s___g___sExplanation : All occurrences are filled in their position of g and s. Method #1 : Using loop This is brute force approach to this problem. In this, we iterate for all the elements in string, if it’s in list we fill it, else fill with “space” value. Python3 # Python3 code to demonstrate working of # Fill list characters in String # Using loop # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + str(test_str)) # initializing fill list fill_list = ['g', 's', 'f'] # loop to iterate through string res = ""for chr in test_str: # checking for presence if chr in fill_list: temp = chr else: temp = "_" res += temp # printing result print("The string after filling values : " + str(res)) The original string is : geeksforgeeks The string after filling values : g___sf__g___s Method #2 : Using join() + list comprehension The combination of above functions can be used to solve this problem. In this, we formulate logic using list comprehension and join() is used to perform join of required values using conditions. Python3 # Python3 code to demonstrate working of # Fill list characters in String # Using join() + list comprehension # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + str(test_str)) # initializing fill list fill_list = ['g', 's', 'f'] # join() used to concatenate result # using conditionals in list comprehensionres = "".join([chr if chr in fill_list else "_" for chr in list(test_str)]) # printing result print("The string after filling values : " + str(res)) The original string is : geeksforgeeks The string after filling values : g___sf__g___s Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 100, "s": 28, "text": "Given String and list, construct a string with only list values filled." }, { "code": null, "e": 265, "s": 100, "text": "Input : test_str = “geeksforgeeks”, fill_list = [‘g’, ‘s’, ‘f’, k]Output : g__ksf__g__ksExplanation : All occurrences are filled in their position of g, s, f and k." }, { "code": null, "e": 416, "s": 265, "text": "Input : test_str = “geeksforgeeks”, fill_list = [‘g’, ‘s’]Output : g___s___g___sExplanation : All occurrences are filled in their position of g and s." }, { "code": null, "e": 439, "s": 416, "text": "Method #1 : Using loop" }, { "code": null, "e": 595, "s": 439, "text": "This is brute force approach to this problem. In this, we iterate for all the elements in string, if it’s in list we fill it, else fill with “space” value." }, { "code": null, "e": 603, "s": 595, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Fill list characters in String # Using loop # initializing stringtest_str = \"geeksforgeeks\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing fill list fill_list = ['g', 's', 'f'] # loop to iterate through string res = \"\"for chr in test_str: # checking for presence if chr in fill_list: temp = chr else: temp = \"_\" res += temp # printing result print(\"The string after filling values : \" + str(res)) ", "e": 1126, "s": 603, "text": null }, { "code": null, "e": 1214, "s": 1126, "text": "The original string is : geeksforgeeks\nThe string after filling values : g___sf__g___s\n" }, { "code": null, "e": 1260, "s": 1214, "text": "Method #2 : Using join() + list comprehension" }, { "code": null, "e": 1455, "s": 1260, "text": "The combination of above functions can be used to solve this problem. In this, we formulate logic using list comprehension and join() is used to perform join of required values using conditions." }, { "code": null, "e": 1463, "s": 1455, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Fill list characters in String # Using join() + list comprehension # initializing stringtest_str = \"geeksforgeeks\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing fill list fill_list = ['g', 's', 'f'] # join() used to concatenate result # using conditionals in list comprehensionres = \"\".join([chr if chr in fill_list else \"_\" for chr in list(test_str)]) # printing result print(\"The string after filling values : \" + str(res)) ", "e": 1999, "s": 1463, "text": null }, { "code": null, "e": 2087, "s": 1999, "text": "The original string is : geeksforgeeks\nThe string after filling values : g___sf__g___s\n" }, { "code": null, "e": 2108, "s": 2087, "text": "Python list-programs" }, { "code": null, "e": 2131, "s": 2108, "text": "Python string-programs" }, { "code": null, "e": 2138, "s": 2131, "text": "Python" }, { "code": null, "e": 2154, "s": 2138, "text": "Python Programs" }, { "code": null, "e": 2252, "s": 2154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2284, "s": 2252, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2311, "s": 2284, "text": "Python Classes and Objects" }, { "code": null, "e": 2332, "s": 2311, "text": "Python OOPs Concepts" }, { "code": null, "e": 2355, "s": 2332, "text": "Introduction To PYTHON" }, { "code": null, "e": 2411, "s": 2355, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2433, "s": 2411, "text": "Defaultdict in Python" }, { "code": null, "e": 2472, "s": 2433, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2510, "s": 2472, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2559, "s": 2510, "text": "Python | Convert string dictionary to dictionary" } ]
How to get current_url using Selenium in Python?
06 Mar, 2020 While doing work with selenium many URL get opened and redirected in order to keeping track of URL current_url method is used. The current_url method is used to retrieve the URL of the webpage the user is currently accessing. It gives the URL of the current webpage loaded by the driver in selenium. URL : URL is the abbreviation of Uniform Resource Locator and is defined as the global address of documents and other resources on the World Wide Web, for example, to visit GeeksforGeeks website, you’ll go to the URL https://www.geeksforgeeks.org/ . Syntax : driver.current_url Argument : It takes no argument. Return value :It return the URL in string format. # Importing webdriver from seleniumfrom selenium import webdriver # Here chrome webdriver is useddriver = webdriver.Chrome() # URL of the website url = "https://www.geeksforgeeks.org/" # Opening the URLdriver.get(url) # Getting current URLget_url = driver.current_url # Printing the URLprint(get_url) Output : https://www.geeksforgeeks.org/ Code 2: # Importing webdriver from seleniumfrom selenium import webdriver # Here chrome webdriver is useddriver = webdriver.Chrome() # URL of the website url = "https://www.geeksforgeeks.org/" # Getting current URLget_url = driver.current_url # Printing the URLprint(get_url) # Opening the URLdriver.get(url) # Getting current URLget_url = driver.current_url # Printing the URLprint(get_url) Output : data:, https://www.geeksforgeeks.org/ Note: Here “data:, ” is printed because at that time no webpage is opened. Python-selenium Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Mar, 2020" }, { "code": null, "e": 328, "s": 28, "text": "While doing work with selenium many URL get opened and redirected in order to keeping track of URL current_url method is used. The current_url method is used to retrieve the URL of the webpage the user is currently accessing. It gives the URL of the current webpage loaded by the driver in selenium." }, { "code": null, "e": 578, "s": 328, "text": "URL : URL is the abbreviation of Uniform Resource Locator and is defined as the global address of documents and other resources on the World Wide Web, for example, to visit GeeksforGeeks website, you’ll go to the URL https://www.geeksforgeeks.org/ ." }, { "code": null, "e": 587, "s": 578, "text": "Syntax :" }, { "code": null, "e": 607, "s": 587, "text": "driver.current_url\n" }, { "code": null, "e": 618, "s": 607, "text": "Argument :" }, { "code": null, "e": 640, "s": 618, "text": "It takes no argument." }, { "code": null, "e": 690, "s": 640, "text": "Return value :It return the URL in string format." }, { "code": "# Importing webdriver from seleniumfrom selenium import webdriver # Here chrome webdriver is useddriver = webdriver.Chrome() # URL of the website url = \"https://www.geeksforgeeks.org/\" # Opening the URLdriver.get(url) # Getting current URLget_url = driver.current_url # Printing the URLprint(get_url)", "e": 996, "s": 690, "text": null }, { "code": null, "e": 1005, "s": 996, "text": "Output :" }, { "code": null, "e": 1036, "s": 1005, "text": "https://www.geeksforgeeks.org/" }, { "code": null, "e": 1044, "s": 1036, "text": "Code 2:" }, { "code": "# Importing webdriver from seleniumfrom selenium import webdriver # Here chrome webdriver is useddriver = webdriver.Chrome() # URL of the website url = \"https://www.geeksforgeeks.org/\" # Getting current URLget_url = driver.current_url # Printing the URLprint(get_url) # Opening the URLdriver.get(url) # Getting current URLget_url = driver.current_url # Printing the URLprint(get_url)", "e": 1435, "s": 1044, "text": null }, { "code": null, "e": 1444, "s": 1435, "text": "Output :" }, { "code": null, "e": 1483, "s": 1444, "text": "data:,\nhttps://www.geeksforgeeks.org/\n" }, { "code": null, "e": 1558, "s": 1483, "text": "Note: Here “data:, ” is printed because at that time no webpage is opened." }, { "code": null, "e": 1574, "s": 1558, "text": "Python-selenium" }, { "code": null, "e": 1581, "s": 1574, "text": "Python" }, { "code": null, "e": 1598, "s": 1581, "text": "Web Technologies" } ]
Count special palindromes in a String
14 Mar, 2022 Given a String s, count all special palindromic substrings of size greater than 1. A Substring is called special palindromic substring if all the characters in the substring are same or only the middle character is different for odd length. Example “aabaa” and “aaa” are special palindromic substrings and “abcba” is not special palindromic substring.Examples : Input : str = " abab" Output : 2 All Special Palindromic substring are: "aba", "bab" Input : str = "aabbb" Output : 4 All Special substring are: "aa", "bb", "bbb", "bb" Simple Solution is that we simply generate all substrings one-by-one and count how many substring are Special Palindromic substring. This solution takes O(n3) time.Efficient Solution There are 2 Cases : Case 1: All Palindromic substrings have same character : We can handle this case by simply counting the same continuous character and using formula K*(K+1)/2 (total number of substring possible : Here K is count of Continuous same char). Lets Str = "aaabba" Traverse string from left to right and Count of same char "aaabba" = 3, 2, 1 for "aaa" : total substring possible are 'aa' 'aa', 'aaa', 'a', 'a', 'a' : 3(3+1)/2 = 6 "bb" : 'b', 'b', 'bb' : 2(2+1)/2 = 3 'a' : 'a' : 1(1+1)/2 = 1 Case 2: We can handle this case by storing count of same character in another temporary array called “sameChar[n]” of size n. and pick each character one-by-one and check its previous and forward character are equal or not if equal then there are min_between( sameChar[previous], sameChar[forward] ) substring possible. Let's Str = "aabaaab" Count of smiler char from left to right : that we will store in Temporary array "sameChar" Str = " a a b a a a b " sameChar[] = 2 2 1 3 3 3 1 According to the problem statement middle character is different: so we have only left with char "b" at index :2 ( index from 0 to n-1) substring : "aabaaa" so only two substring are possible : "aabaa", "aba" that is min (smilerChar[index-1], smilerChar[index+1] ) that is 2. Below is the implementation of above idea C++ Java Python3 C# PHP Javascript // C++ program to count special Palindromic substring#include <bits/stdc++.h>using namespace std; // Function to count special Palindromic substringint CountSpecialPalindrome(string str){ int n = str.length(); // store count of special Palindromic substring int result = 0; // it will store the count of continues same char int sameChar[n] = { 0 }; int i = 0; // traverse string character from left to right while (i < n) { // store same character count int sameCharCount = 1; int j = i + 1; // count similar character while (str[i] == str[j] && j < n) sameCharCount++, j++; // Case : 1 // so total number of substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1) / 2); // store current same char count in sameChar[] // array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length Special Palindromic // substring for (int j = 1; j < n; j++) { // if current character is equal to previous // one then we assign Previous same character // count to current one if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1]; // case 2: odd length if (j > 0 && j < (n - 1) && (str[j - 1] == str[j + 1] && str[j] != str[j - 1])) result += min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single length substring return result - n;} // driver program to test above funint main(){ string str = "abccba"; cout << CountSpecialPalindrome(str) << endl; return 0;} // Java program to count special// Palindromic substringimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // Function to count special// Palindromic substringpublic static int CountSpecialPalindrome(String str){ int n = str.length(); // store count of special // Palindromic substring int result = 0; // it will store the count // of continues same char int[] sameChar = new int[n]; for(int v = 0; v < n; v++) sameChar[v] = 0; int i = 0; // traverse string character // from left to right while (i < n) { // store same character count int sameCharCount = 1; int j = i + 1; // count similar character while (j < n && str.charAt(i) == str.charAt(j)) { sameCharCount++; j++; } // Case : 1 // so total number of // substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1) / 2); // store current same char // count in sameChar[] array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length // Special Palindromic // substring for (int j = 1; j < n; j++) { // if current character is // equal to previous one // then we assign Previous // same character count to // current one if (str.charAt(j) == str.charAt(j - 1)) sameChar[j] = sameChar[j - 1]; // case 2: odd length if (j > 0 && j < (n - 1) && (str.charAt(j - 1) == str.charAt(j + 1) && str.charAt(j) != str.charAt(j - 1))) result += Math.min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single // length substring return result - n;} // Driver codepublic static void main(String args[]){ String str = "abccba"; System.out.print(CountSpecialPalindrome(str));}} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 program to count special# Palindromic substring # Function to count special# Palindromic substringdef CountSpecialPalindrome(str): n = len(str); # store count of special # Palindromic substring result = 0; # it will store the count # of continues same char sameChar=[0] * n; i = 0; # traverse string character # from left to right while (i < n): # store same character count sameCharCount = 1; j = i + 1; # count smiler character while (j < n): if(str[i] != str[j]): break; sameCharCount += 1; j += 1; # Case : 1 # so total number of substring # that we can generate are : # K *( K + 1 ) / 2 # here K is sameCharCount result += int(sameCharCount * (sameCharCount + 1) / 2); # store current same char # count in sameChar[] array sameChar[i] = sameCharCount; # increment i i = j; # Case 2: Count all odd length # Special Palindromic substring for j in range(1, n): # if current character is equal # to previous one then we assign # Previous same character count # to current one if (str[j] == str[j - 1]): sameChar[j] = sameChar[j - 1]; # case 2: odd length if (j > 0 and j < (n - 1) and (str[j - 1] == str[j + 1] and str[j] != str[j - 1])): result += (sameChar[j - 1] if(sameChar[j - 1] < sameChar[j + 1]) else sameChar[j + 1]); # subtract all single # length substring return result-n; # Driver Codestr = "abccba";print(CountSpecialPalindrome(str)); # This code is contributed by mits. // C# program to count special// Palindromic substringusing System; class GFG{ // Function to count special// Palindromic substringpublic static int CountSpecialPalindrome(String str){ int n = str.Length; // store count of special // Palindromic substring int result = 0; // it will store the count // of continues same char int[] sameChar = new int[n]; for(int v = 0; v < n; v++) sameChar[v] = 0; int i = 0; // traverse string character // from left to right while (i < n) { // store same character count int sameCharCount = 1; int j = i + 1; // count smiler character while (j < n && str[i] == str[j]) { sameCharCount++; j++; } // Case : 1 // so total number of // substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1) / 2); // store current same char // count in sameChar[] array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length // Special Palindromic // substring for (int j = 1; j < n; j++) { // if current character is // equal to previous one // then we assign Previous // same character count to // current one if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1]; // case 2: odd length if (j > 0 && j < (n - 1) && (str[j - 1] == str[j + 1] && str[j] != str[j - 1])) result += Math.Min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single // length substring return result - n;} // Driver codepublic static void Main(){ String str = "abccba"; Console.Write(CountSpecialPalindrome(str));}} // This code is contributed by mits. <?php// PHP program to count special// Palindromic substring // Function to count special// Palindromic substringfunction CountSpecialPalindrome($str){ $n = strlen($str); // store count of special // Palindromic substring $result = 0; // it will store the count // of continues same char $sameChar=array_fill(0, $n, 0); $i = 0; // traverse string character // from left to right while ($i < $n) { // store same character count $sameCharCount = 1; $j = $i + 1; // count smiler character while ($j < $n) { if($str[$i] != $str[$j]) break; $sameCharCount++; $j++; } // Case : 1 // so total number of substring // that we can generate are : // K *( K + 1 ) / 2 // here K is sameCharCount $result += (int)($sameCharCount * ($sameCharCount + 1) / 2); // store current same char // count in sameChar[] array $sameChar[$i] = $sameCharCount; // increment i $i = $j; } // Case 2: Count all odd length // Special Palindromic substring for ($j = 1; $j < $n; $j++) { // if current character is equal // to previous one then we assign // Previous same character count // to current one if ($str[$j] == $str[$j - 1]) $sameChar[$j] = $sameChar[$j - 1]; // case 2: odd length if ($j > 0 && $j < ($n - 1) && ($str[$j - 1] == $str[$j + 1] && $str[$j] != $str[$j - 1])) $result += $sameChar[$j - 1] < $sameChar[$j + 1] ? $sameChar[$j - 1] : $sameChar[$j + 1]; } // subtract all single // length substring return $result - $n;} // Driver Code$str = "abccba";echo CountSpecialPalindrome($str); // This code is contributed by mits.?> <script> // JavaScript program to count special Palindromic substring // Function to count special Palindromic substring function CountSpecialPalindrome(str) { var n = str.length; // store count of special Palindromic substring var result = 0; // it will store the count of continues same char var sameChar = [...Array(n)]; var i = 0; // traverse string character from left to right while (i < n) { // store same character count var sameCharCount = 1; var j = i + 1; // count smiler character while (str[i] == str[j] && j < n) sameCharCount++, j++; // Case : 1 // so total number of substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1)) / 2; // store current same char count in sameChar[] // array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length Special Palindromic // substring for (var j = 1; j < n; j++) { // if current character is equal to previous // one then we assign Previous same character // count to current one if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1]; // case 2: odd length if ( j > 0 && j < n - 1 && str[j - 1] == str[j + 1] && str[j] != str[j - 1] ) result += Math.min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single length substring return result - n; } // driver program to test above fun var str = "abccba"; document.write(CountSpecialPalindrome(str) + "<br>"); </script> Output : 1 Time Complexity : O(n) Auxiliary Space : O(n) Mithun Kumar Akanksha_Rai Wagner da Silva Fontes rdtank varshagumber28 sumitgumber28 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Length of the longest substring without repeating characters Convert string to char array in C++ Reverse words in a given string Check whether two strings are anagram of each other
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Mar, 2022" }, { "code": null, "e": 416, "s": 52, "text": "Given a String s, count all special palindromic substrings of size greater than 1. A Substring is called special palindromic substring if all the characters in the substring are same or only the middle character is different for odd length. Example “aabaa” and “aaa” are special palindromic substrings and “abcba” is not special palindromic substring.Examples : " }, { "code": null, "e": 588, "s": 416, "text": "Input : str = \" abab\"\nOutput : 2\nAll Special Palindromic substring are: \"aba\", \"bab\"\n\nInput : str = \"aabbb\"\nOutput : 4\nAll Special substring are: \"aa\", \"bb\", \"bbb\", \"bb\"" }, { "code": null, "e": 1033, "s": 590, "text": "Simple Solution is that we simply generate all substrings one-by-one and count how many substring are Special Palindromic substring. This solution takes O(n3) time.Efficient Solution There are 2 Cases : Case 1: All Palindromic substrings have same character : We can handle this case by simply counting the same continuous character and using formula K*(K+1)/2 (total number of substring possible : Here K is count of Continuous same char). " }, { "code": null, "e": 1302, "s": 1033, "text": " Lets Str = \"aaabba\"\n Traverse string from left to right and Count of same char\n \"aaabba\" = 3, 2, 1\n for \"aaa\" : total substring possible are\n 'aa' 'aa', 'aaa', 'a', 'a', 'a' : 3(3+1)/2 = 6 \n \"bb\" : 'b', 'b', 'bb' : 2(2+1)/2 = 3\n 'a' : 'a' : 1(1+1)/2 = 1 " }, { "code": null, "e": 1624, "s": 1302, "text": "Case 2: We can handle this case by storing count of same character in another temporary array called “sameChar[n]” of size n. and pick each character one-by-one and check its previous and forward character are equal or not if equal then there are min_between( sameChar[previous], sameChar[forward] ) substring possible. " }, { "code": null, "e": 2085, "s": 1624, "text": "Let's Str = \"aabaaab\"\n Count of smiler char from left to right :\n that we will store in Temporary array \"sameChar\"\n Str = \" a a b a a a b \"\nsameChar[] = 2 2 1 3 3 3 1\nAccording to the problem statement middle character is different:\nso we have only left with char \"b\" at index :2 ( index from 0 to n-1)\nsubstring : \"aabaaa\"\nso only two substring are possible : \"aabaa\", \"aba\"\nthat is min (smilerChar[index-1], smilerChar[index+1] ) that is 2." }, { "code": null, "e": 2129, "s": 2085, "text": "Below is the implementation of above idea " }, { "code": null, "e": 2133, "s": 2129, "text": "C++" }, { "code": null, "e": 2138, "s": 2133, "text": "Java" }, { "code": null, "e": 2146, "s": 2138, "text": "Python3" }, { "code": null, "e": 2149, "s": 2146, "text": "C#" }, { "code": null, "e": 2153, "s": 2149, "text": "PHP" }, { "code": null, "e": 2164, "s": 2153, "text": "Javascript" }, { "code": "// C++ program to count special Palindromic substring#include <bits/stdc++.h>using namespace std; // Function to count special Palindromic substringint CountSpecialPalindrome(string str){ int n = str.length(); // store count of special Palindromic substring int result = 0; // it will store the count of continues same char int sameChar[n] = { 0 }; int i = 0; // traverse string character from left to right while (i < n) { // store same character count int sameCharCount = 1; int j = i + 1; // count similar character while (str[i] == str[j] && j < n) sameCharCount++, j++; // Case : 1 // so total number of substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1) / 2); // store current same char count in sameChar[] // array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length Special Palindromic // substring for (int j = 1; j < n; j++) { // if current character is equal to previous // one then we assign Previous same character // count to current one if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1]; // case 2: odd length if (j > 0 && j < (n - 1) && (str[j - 1] == str[j + 1] && str[j] != str[j - 1])) result += min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single length substring return result - n;} // driver program to test above funint main(){ string str = \"abccba\"; cout << CountSpecialPalindrome(str) << endl; return 0;}", "e": 3923, "s": 2164, "text": null }, { "code": "// Java program to count special// Palindromic substringimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // Function to count special// Palindromic substringpublic static int CountSpecialPalindrome(String str){ int n = str.length(); // store count of special // Palindromic substring int result = 0; // it will store the count // of continues same char int[] sameChar = new int[n]; for(int v = 0; v < n; v++) sameChar[v] = 0; int i = 0; // traverse string character // from left to right while (i < n) { // store same character count int sameCharCount = 1; int j = i + 1; // count similar character while (j < n && str.charAt(i) == str.charAt(j)) { sameCharCount++; j++; } // Case : 1 // so total number of // substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1) / 2); // store current same char // count in sameChar[] array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length // Special Palindromic // substring for (int j = 1; j < n; j++) { // if current character is // equal to previous one // then we assign Previous // same character count to // current one if (str.charAt(j) == str.charAt(j - 1)) sameChar[j] = sameChar[j - 1]; // case 2: odd length if (j > 0 && j < (n - 1) && (str.charAt(j - 1) == str.charAt(j + 1) && str.charAt(j) != str.charAt(j - 1))) result += Math.min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single // length substring return result - n;} // Driver codepublic static void main(String args[]){ String str = \"abccba\"; System.out.print(CountSpecialPalindrome(str));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 6037, "s": 3923, "text": null }, { "code": "# Python3 program to count special# Palindromic substring # Function to count special# Palindromic substringdef CountSpecialPalindrome(str): n = len(str); # store count of special # Palindromic substring result = 0; # it will store the count # of continues same char sameChar=[0] * n; i = 0; # traverse string character # from left to right while (i < n): # store same character count sameCharCount = 1; j = i + 1; # count smiler character while (j < n): if(str[i] != str[j]): break; sameCharCount += 1; j += 1; # Case : 1 # so total number of substring # that we can generate are : # K *( K + 1 ) / 2 # here K is sameCharCount result += int(sameCharCount * (sameCharCount + 1) / 2); # store current same char # count in sameChar[] array sameChar[i] = sameCharCount; # increment i i = j; # Case 2: Count all odd length # Special Palindromic substring for j in range(1, n): # if current character is equal # to previous one then we assign # Previous same character count # to current one if (str[j] == str[j - 1]): sameChar[j] = sameChar[j - 1]; # case 2: odd length if (j > 0 and j < (n - 1) and (str[j - 1] == str[j + 1] and str[j] != str[j - 1])): result += (sameChar[j - 1] if(sameChar[j - 1] < sameChar[j + 1]) else sameChar[j + 1]); # subtract all single # length substring return result-n; # Driver Codestr = \"abccba\";print(CountSpecialPalindrome(str)); # This code is contributed by mits.", "e": 7824, "s": 6037, "text": null }, { "code": "// C# program to count special// Palindromic substringusing System; class GFG{ // Function to count special// Palindromic substringpublic static int CountSpecialPalindrome(String str){ int n = str.Length; // store count of special // Palindromic substring int result = 0; // it will store the count // of continues same char int[] sameChar = new int[n]; for(int v = 0; v < n; v++) sameChar[v] = 0; int i = 0; // traverse string character // from left to right while (i < n) { // store same character count int sameCharCount = 1; int j = i + 1; // count smiler character while (j < n && str[i] == str[j]) { sameCharCount++; j++; } // Case : 1 // so total number of // substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1) / 2); // store current same char // count in sameChar[] array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length // Special Palindromic // substring for (int j = 1; j < n; j++) { // if current character is // equal to previous one // then we assign Previous // same character count to // current one if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1]; // case 2: odd length if (j > 0 && j < (n - 1) && (str[j - 1] == str[j + 1] && str[j] != str[j - 1])) result += Math.Min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single // length substring return result - n;} // Driver codepublic static void Main(){ String str = \"abccba\"; Console.Write(CountSpecialPalindrome(str));}} // This code is contributed by mits.", "e": 9799, "s": 7824, "text": null }, { "code": "<?php// PHP program to count special// Palindromic substring // Function to count special// Palindromic substringfunction CountSpecialPalindrome($str){ $n = strlen($str); // store count of special // Palindromic substring $result = 0; // it will store the count // of continues same char $sameChar=array_fill(0, $n, 0); $i = 0; // traverse string character // from left to right while ($i < $n) { // store same character count $sameCharCount = 1; $j = $i + 1; // count smiler character while ($j < $n) { if($str[$i] != $str[$j]) break; $sameCharCount++; $j++; } // Case : 1 // so total number of substring // that we can generate are : // K *( K + 1 ) / 2 // here K is sameCharCount $result += (int)($sameCharCount * ($sameCharCount + 1) / 2); // store current same char // count in sameChar[] array $sameChar[$i] = $sameCharCount; // increment i $i = $j; } // Case 2: Count all odd length // Special Palindromic substring for ($j = 1; $j < $n; $j++) { // if current character is equal // to previous one then we assign // Previous same character count // to current one if ($str[$j] == $str[$j - 1]) $sameChar[$j] = $sameChar[$j - 1]; // case 2: odd length if ($j > 0 && $j < ($n - 1) && ($str[$j - 1] == $str[$j + 1] && $str[$j] != $str[$j - 1])) $result += $sameChar[$j - 1] < $sameChar[$j + 1] ? $sameChar[$j - 1] : $sameChar[$j + 1]; } // subtract all single // length substring return $result - $n;} // Driver Code$str = \"abccba\";echo CountSpecialPalindrome($str); // This code is contributed by mits.?>", "e": 11749, "s": 9799, "text": null }, { "code": "<script> // JavaScript program to count special Palindromic substring // Function to count special Palindromic substring function CountSpecialPalindrome(str) { var n = str.length; // store count of special Palindromic substring var result = 0; // it will store the count of continues same char var sameChar = [...Array(n)]; var i = 0; // traverse string character from left to right while (i < n) { // store same character count var sameCharCount = 1; var j = i + 1; // count smiler character while (str[i] == str[j] && j < n) sameCharCount++, j++; // Case : 1 // so total number of substring that we can // generate are : K *( K + 1 ) / 2 // here K is sameCharCount result += (sameCharCount * (sameCharCount + 1)) / 2; // store current same char count in sameChar[] // array sameChar[i] = sameCharCount; // increment i i = j; } // Case 2: Count all odd length Special Palindromic // substring for (var j = 1; j < n; j++) { // if current character is equal to previous // one then we assign Previous same character // count to current one if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1]; // case 2: odd length if ( j > 0 && j < n - 1 && str[j - 1] == str[j + 1] && str[j] != str[j - 1] ) result += Math.min(sameChar[j - 1], sameChar[j + 1]); } // subtract all single length substring return result - n; } // driver program to test above fun var str = \"abccba\"; document.write(CountSpecialPalindrome(str) + \"<br>\"); </script>", "e": 13592, "s": 11749, "text": null }, { "code": null, "e": 13603, "s": 13592, "text": "Output : " }, { "code": null, "e": 13605, "s": 13603, "text": "1" }, { "code": null, "e": 13652, "s": 13605, "text": "Time Complexity : O(n) Auxiliary Space : O(n) " }, { "code": null, "e": 13665, "s": 13652, "text": "Mithun Kumar" }, { "code": null, "e": 13678, "s": 13665, "text": "Akanksha_Rai" }, { "code": null, "e": 13701, "s": 13678, "text": "Wagner da Silva Fontes" }, { "code": null, "e": 13708, "s": 13701, "text": "rdtank" }, { "code": null, "e": 13723, "s": 13708, "text": "varshagumber28" }, { "code": null, "e": 13737, "s": 13723, "text": "sumitgumber28" }, { "code": null, "e": 13748, "s": 13737, "text": "palindrome" }, { "code": null, "e": 13756, "s": 13748, "text": "Strings" }, { "code": null, "e": 13764, "s": 13756, "text": "Strings" }, { "code": null, "e": 13775, "s": 13764, "text": "palindrome" }, { "code": null, "e": 13873, "s": 13775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13948, "s": 13873, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 13993, "s": 13948, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 14050, "s": 13993, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 14086, "s": 14050, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 14131, "s": 14086, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 14195, "s": 14131, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 14256, "s": 14195, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 14292, "s": 14256, "text": "Convert string to char array in C++" }, { "code": null, "e": 14324, "s": 14292, "text": "Reverse words in a given string" } ]
String Slicing in Python
21 Jun, 2022 Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end. For understanding slicing we will use different methods, here we will cover 2 methods of string slicing, the one is using the in-build slice() method and another using the [:] array slice. String slicing in Python is about obtaining a sub-string from the given string by slicing it respectively from start to end. Using a slice() method Using array slicing [ : : ] method Index tracker for positive and negative index: String indexing and slicing in python. Here, the Negative comes into consideration when tracking the string in reverse. The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step). Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Syntax: slice(stop) slice(start, stop, step) Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the slicing of object stops. step: It is an optional argument that determines the increment between each index for slicing. Return Type: Returns a sliced object containing elements in the given range only. Example: Python3 # Python program to demonstrate# string slicing # String slicingString = 'ASTRING' # Using slice constructors1 = slice(3)s2 = slice(1, 5, 2)s3 = slice(-1, -12, -2) print(& quot String slicing & quot )print(String[s1])print(String[s2])print(String[s3]) String slicing AST SR GITA In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way to slice a string using list slicing and Array slicing both syntax-wise and execution-wise. A start, end, and step have the same mechanism as the slice() constructor. Below we will see string slicing in Python with example. Syntax arr[start:stop] # items start through stop-1 arr[start:] # items start through the rest of the array arr[:stop] # items from the beginning through stop-1 arr[:] # a copy of the whole array arr[start:stop:step] # start through not past stop, by step Example 1: In this example, we will see slicing in python list the index start from 0 indexes and ending with a 2 index(stops at 3-1=2 ). Python3 # Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Using indexing sequenceprint(String[:3]) Output: GEE Example 2: In this example, we will see the example of starting from 1 index and ending with a 5 index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing string by character. Python3 # Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Using indexing sequenceprint(String[1:5:2]) Output: EK Example 3: In this example, we will see the example of starting from -1 indexes and ending with a -12 index(stops at 3-1=2 )and the skipping step is -2. Python3 # Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Using indexing sequenceprint(String[-1:-12:-2]) Output: SEGOSE Example 4: In this example, the whole string is printed in reverse order. Python3 # Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Prints string in reverseprint(String[::-1]) Output: SKEEGROFSKEEG Note: To know more about strings click here. surajkumarguptaintern python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 168, "s": 52, "text": "Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end. " }, { "code": null, "e": 483, "s": 168, "text": "For understanding slicing we will use different methods, here we will cover 2 methods of string slicing, the one is using the in-build slice() method and another using the [:] array slice. String slicing in Python is about obtaining a sub-string from the given string by slicing it respectively from start to end. " }, { "code": null, "e": 506, "s": 483, "text": "Using a slice() method" }, { "code": null, "e": 542, "s": 506, "text": "Using array slicing [ : : ] method" }, { "code": null, "e": 710, "s": 542, "text": "Index tracker for positive and negative index: String indexing and slicing in python. Here, the Negative comes into consideration when tracking the string in reverse. " }, { "code": null, "e": 828, "s": 710, "text": "The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step)." }, { "code": null, "e": 837, "s": 828, "text": "Chapters" }, { "code": null, "e": 864, "s": 837, "text": "descriptions off, selected" }, { "code": null, "e": 914, "s": 864, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 937, "s": 914, "text": "captions off, selected" }, { "code": null, "e": 945, "s": 937, "text": "English" }, { "code": null, "e": 969, "s": 945, "text": "This is a modal window." }, { "code": null, "e": 1038, "s": 969, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1060, "s": 1038, "text": "End of dialog window." }, { "code": null, "e": 1068, "s": 1060, "text": "Syntax:" }, { "code": null, "e": 1080, "s": 1068, "text": "slice(stop)" }, { "code": null, "e": 1105, "s": 1080, "text": "slice(start, stop, step)" }, { "code": null, "e": 1407, "s": 1105, "text": "Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the slicing of object stops. step: It is an optional argument that determines the increment between each index for slicing. Return Type: Returns a sliced object containing elements in the given range only. " }, { "code": null, "e": 1416, "s": 1407, "text": "Example:" }, { "code": null, "e": 1424, "s": 1416, "text": "Python3" }, { "code": "# Python program to demonstrate# string slicing # String slicingString = 'ASTRING' # Using slice constructors1 = slice(3)s2 = slice(1, 5, 2)s3 = slice(-1, -12, -2) print(& quot String slicing & quot )print(String[s1])print(String[s2])print(String[s3])", "e": 1688, "s": 1424, "text": null }, { "code": null, "e": 1715, "s": 1688, "text": "String slicing\nAST\nSR\nGITA" }, { "code": null, "e": 1995, "s": 1715, "text": "In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way to slice a string using list slicing and Array slicing both syntax-wise and execution-wise. A start, end, and step have the same mechanism as the slice() constructor. " }, { "code": null, "e": 2052, "s": 1995, "text": "Below we will see string slicing in Python with example." }, { "code": null, "e": 2059, "s": 2052, "text": "Syntax" }, { "code": null, "e": 2361, "s": 2059, "text": "arr[start:stop] # items start through stop-1\narr[start:] # items start through the rest of the array\narr[:stop] # items from the beginning through stop-1\narr[:] # a copy of the whole array\narr[start:stop:step] # start through not past stop, by step" }, { "code": null, "e": 2372, "s": 2361, "text": "Example 1:" }, { "code": null, "e": 2499, "s": 2372, "text": "In this example, we will see slicing in python list the index start from 0 indexes and ending with a 2 index(stops at 3-1=2 )." }, { "code": null, "e": 2507, "s": 2499, "text": "Python3" }, { "code": "# Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Using indexing sequenceprint(String[:3])", "e": 2639, "s": 2507, "text": null }, { "code": null, "e": 2647, "s": 2639, "text": "Output:" }, { "code": null, "e": 2651, "s": 2647, "text": "GEE" }, { "code": null, "e": 2662, "s": 2651, "text": "Example 2:" }, { "code": null, "e": 2860, "s": 2662, "text": "In this example, we will see the example of starting from 1 index and ending with a 5 index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing string by character." }, { "code": null, "e": 2868, "s": 2860, "text": "Python3" }, { "code": "# Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Using indexing sequenceprint(String[1:5:2])", "e": 3003, "s": 2868, "text": null }, { "code": null, "e": 3011, "s": 3003, "text": "Output:" }, { "code": null, "e": 3014, "s": 3011, "text": "EK" }, { "code": null, "e": 3025, "s": 3014, "text": "Example 3:" }, { "code": null, "e": 3167, "s": 3025, "text": "In this example, we will see the example of starting from -1 indexes and ending with a -12 index(stops at 3-1=2 )and the skipping step is -2." }, { "code": null, "e": 3175, "s": 3167, "text": "Python3" }, { "code": "# Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Using indexing sequenceprint(String[-1:-12:-2])", "e": 3314, "s": 3175, "text": null }, { "code": null, "e": 3322, "s": 3314, "text": "Output:" }, { "code": null, "e": 3329, "s": 3322, "text": "SEGOSE" }, { "code": null, "e": 3340, "s": 3329, "text": "Example 4:" }, { "code": null, "e": 3403, "s": 3340, "text": "In this example, the whole string is printed in reverse order." }, { "code": null, "e": 3411, "s": 3403, "text": "Python3" }, { "code": "# Python program to demonstrate# string slicing # String slicingString = 'GEEKSFORGEEKS' # Prints string in reverseprint(String[::-1])", "e": 3546, "s": 3411, "text": null }, { "code": null, "e": 3554, "s": 3546, "text": "Output:" }, { "code": null, "e": 3568, "s": 3554, "text": "SKEEGROFSKEEG" }, { "code": null, "e": 3613, "s": 3568, "text": "Note: To know more about strings click here." }, { "code": null, "e": 3635, "s": 3613, "text": "surajkumarguptaintern" }, { "code": null, "e": 3649, "s": 3635, "text": "python-string" }, { "code": null, "e": 3656, "s": 3649, "text": "Python" }, { "code": null, "e": 3754, "s": 3656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3796, "s": 3754, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3818, "s": 3796, "text": "Enumerate() in Python" }, { "code": null, "e": 3844, "s": 3818, "text": "Python String | replace()" }, { "code": null, "e": 3876, "s": 3844, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3905, "s": 3876, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3932, "s": 3905, "text": "Python Classes and Objects" }, { "code": null, "e": 3968, "s": 3932, "text": "Convert integer to string in Python" }, { "code": null, "e": 3999, "s": 3968, "text": "Python | os.path.join() method" }, { "code": null, "e": 4036, "s": 3999, "text": "Create a Pandas DataFrame from Lists" } ]
Data Mining For Intrusion Detection and Prevention
22 Sep, 2021 The security of our computer systems and data is at continual risk. The extensive growth of the Internet and the increasing availability of tools and tricks for intruding and attacking networks have prompted intrusion detection and prevention to become a critical component of networked systems. Unauthorized access by an intruder involves stealing valuable resources and misuse those resources, e.g. Worms and viruses. There are intrusion prevention techniques such as user authentication, and sharing encrypted information that is not enough to operate because the system is becoming more complex day by day so, we need a layer of security controls. It is an entity that is trying to gain unauthorized access over a system or a network. Moreover, the data present in that system will be corrupted along with an imbalance in the environment of that network. Intruders are of majorly two types Masquerader (Outside Intruder) – No authority to use the network or system Misfeasor (Inside Intruder) – authorized access to limited applications An Intrusion Detection System is a device or an application that detects unusual indication and monitors traffic and report its results to an administrator, but cannot take action to prevent unusual activity. The system protects the confidentiality, integrity, and availability of data and information systems from internet attacks. We see that the network extended dynamically, so too are the possibilities of risks and chances of malicious intrusions are increasing. Types of attacks detected by Intrusion detection systems majorly: Scanning attacks Denial of service (DOS) attacks Penetration attacks Fig.2 Architecture of IDS It is basically an extension of the Intrusion Detection System which can protect the system from suspicious activities, viruses, and threats, and once any unwelcome activity is identified IPS also takes action against those activities such as closing access points and prevent firewalls. The majority of intrusion detection and prevention systems use either signature-based detection or anomaly-based detection. 1. Signature-Based – The signature-based system uses some library of signatures of known attacks and if the signature matches with the pattern the system detects the intrusion take prevention by blocking the IP address or deactivate the user account from accessing the application. This system is basically a pattern-based system used to monitor the packets on the network and compares the packets against a database of signature from existing attacks or a list of attack patterns and if the signature matches with the pattern the system detect the intrusion and alert to the admin. E.g.Antiviruses. Advantage Worth detecting only Known attacks. Disadvantage Failed to identify new or unknown attacks. Regular update of new attacks 2. Anomaly-Based – The anomaly-based system waits for any abnormal activity. If activity is detected, the system blocks entry to the target host immediately. This system follows a baseline pattern first we train the system with a suitable baseline and compare activity against that baseline if someone crosses that baseline will be treated as suspicious activity and an alert is triggered to the administrator. Advantage Ability to detect unknown attacks. Disadvantage Higher complexity, sometimes it is difficult to detect and chances of false alarms. As we know that data mining is the system of extracting patterns from huge datasets through combining techniques from statistician artificial intelligence with database management. In intrusion detection (ID) and intrusion prevention device (IPS) we recollect a few things which might be utilized in data mining for intrusion detection systems (IDS) and intrusion prevention devices (IPS). Modern network technologies require a high level of security controls to ensure safe and trusted communication of information between the user and a client. An intrusion Detection System is to protect the system after the failure of traditional technologies. Data mining is the extraction of appropriate features from a large amount of data. And, it supports various learning algorithms, i.e. supervised and unsupervised. Intrusion detection is basically a data-centric process so, with the help of data mining algorithms, IDS will also learn from past intrusions, and improve performance from experience along with find unusual activities. It helps in exploring the large increase in the database and gather only valid information by improving segmentation and help organizations in real-time plan and save time. It has various applications such as detecting anomalous behavior, detecting fraud and abuse, terrorist activities, and investigating crimes through lie detection. Below list of areas in which data mining technology can be carried out for intrusion detection. Using data mining algorithms for developing a new model for IDS: Data mining algorithm for the IDS model having a higher efficiency rate and lower false alarms. Data mining algorithms can be used for both signature-based and anomaly-based detection. In signature-based detection, training information is classified as either “normal” or “intrusion.” A classifier can then be derived to discover acknowledged intrusions. Research on this place has included the software of clarification algorithms, association rule mining, and cost-sensitive modeling. Anomaly-primarily based totally detection builds models of normal behavior and automatically detects massive deviations from it. Methods consist of the software of clustering, outlier analysis, and class algorithms, and statistical approaches. The strategies used have to be efficient and scalable, and able to dealing with community information of excessive volume, dimensional, and heterogeneity. Analysis of Stream data: Analysis of stream data means is analyzing the data in a continuous manner but data mining is basically used on static data rather than Streaming due to complex calculation and high processing time. Due to the dynamic nature of intrusions and malicious attacks, it is more critical to perform intrusion detection withinside the records stream environment. Moreover, an event can be ordinary on its own but taken into consideration malicious if regarded as a part of a series of activities. Thus, it’s far essential to look at what sequences of activities are regularly encountered together, locate sequential patterns, and pick out outliers. Other data mining strategies for locating evolving clusters and constructing dynamic class models in records streams also are essential for real-time intrusion detection. Distributed data mining: It is used to analyze the random data which is inherently distributed into various databases so, it becomes difficult to integrate processing of the data. Intrusions may be launched from numerous distinctive places and focused on many distinctive destinations. Distributed data mining strategies can be used to investigate community data from numerous network places to detect those distributed attacks. Visualization tools: These tools are used to represent the data in the form of graphs which helps the user to get a visual understanding of the data. These tools are also used for viewing any anomalous patterns detected. Such tools may encompass capabilities for viewing associations, discriminative patterns, clusters, and outliers. Intrusion detection structures must actually have a graphical user interface that permits safety analysts to pose queries concerning the network data or intrusion detection results. Blogathon-2021 data mining Picked Blogathon Data Mining Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Sep, 2021" }, { "code": null, "e": 348, "s": 52, "text": "The security of our computer systems and data is at continual risk. The extensive growth of the Internet and the increasing availability of tools and tricks for intruding and attacking networks have prompted intrusion detection and prevention to become a critical component of networked systems." }, { "code": null, "e": 704, "s": 348, "text": "Unauthorized access by an intruder involves stealing valuable resources and misuse those resources, e.g. Worms and viruses. There are intrusion prevention techniques such as user authentication, and sharing encrypted information that is not enough to operate because the system is becoming more complex day by day so, we need a layer of security controls." }, { "code": null, "e": 913, "s": 704, "text": "It is an entity that is trying to gain unauthorized access over a system or a network. Moreover, the data present in that system will be corrupted along with an imbalance in the environment of that network. " }, { "code": null, "e": 948, "s": 913, "text": "Intruders are of majorly two types" }, { "code": null, "e": 1023, "s": 948, "text": "Masquerader (Outside Intruder) – No authority to use the network or system" }, { "code": null, "e": 1095, "s": 1023, "text": "Misfeasor (Inside Intruder) – authorized access to limited applications" }, { "code": null, "e": 1564, "s": 1095, "text": "An Intrusion Detection System is a device or an application that detects unusual indication and monitors traffic and report its results to an administrator, but cannot take action to prevent unusual activity. The system protects the confidentiality, integrity, and availability of data and information systems from internet attacks. We see that the network extended dynamically, so too are the possibilities of risks and chances of malicious intrusions are increasing." }, { "code": null, "e": 1630, "s": 1564, "text": "Types of attacks detected by Intrusion detection systems majorly:" }, { "code": null, "e": 1647, "s": 1630, "text": "Scanning attacks" }, { "code": null, "e": 1679, "s": 1647, "text": "Denial of service (DOS) attacks" }, { "code": null, "e": 1699, "s": 1679, "text": "Penetration attacks" }, { "code": null, "e": 1725, "s": 1699, "text": "Fig.2 Architecture of IDS" }, { "code": null, "e": 2015, "s": 1727, "text": "It is basically an extension of the Intrusion Detection System which can protect the system from suspicious activities, viruses, and threats, and once any unwelcome activity is identified IPS also takes action against those activities such as closing access points and prevent firewalls." }, { "code": null, "e": 2171, "s": 2015, "text": "The majority of intrusion detection and prevention systems use either signature-based detection or anomaly-based detection. " }, { "code": null, "e": 2774, "s": 2171, "text": "1. Signature-Based – The signature-based system uses some library of signatures of known attacks and if the signature matches with the pattern the system detects the intrusion take prevention by blocking the IP address or deactivate the user account from accessing the application. This system is basically a pattern-based system used to monitor the packets on the network and compares the packets against a database of signature from existing attacks or a list of attack patterns and if the signature matches with the pattern the system detect the intrusion and alert to the admin. E.g.Antiviruses." }, { "code": null, "e": 2787, "s": 2774, "text": " Advantage " }, { "code": null, "e": 2823, "s": 2787, "text": "Worth detecting only Known attacks." }, { "code": null, "e": 2838, "s": 2823, "text": " Disadvantage" }, { "code": null, "e": 2882, "s": 2838, "text": " Failed to identify new or unknown attacks." }, { "code": null, "e": 2914, "s": 2882, "text": " Regular update of new attacks " }, { "code": null, "e": 3326, "s": 2914, "text": "2. Anomaly-Based – The anomaly-based system waits for any abnormal activity. If activity is detected, the system blocks entry to the target host immediately. This system follows a baseline pattern first we train the system with a suitable baseline and compare activity against that baseline if someone crosses that baseline will be treated as suspicious activity and an alert is triggered to the administrator." }, { "code": null, "e": 3338, "s": 3326, "text": " Advantage " }, { "code": null, "e": 3373, "s": 3338, "text": "Ability to detect unknown attacks." }, { "code": null, "e": 3388, "s": 3373, "text": " Disadvantage " }, { "code": null, "e": 3473, "s": 3388, "text": " Higher complexity, sometimes it is difficult to detect and chances of false alarms." }, { "code": null, "e": 3866, "s": 3475, "text": "As we know that data mining is the system of extracting patterns from huge datasets through combining techniques from statistician artificial intelligence with database management. In intrusion detection (ID) and intrusion prevention device (IPS) we recollect a few things which might be utilized in data mining for intrusion detection systems (IDS) and intrusion prevention devices (IPS). " }, { "code": null, "e": 4939, "s": 3866, "text": "Modern network technologies require a high level of security controls to ensure safe and trusted communication of information between the user and a client. An intrusion Detection System is to protect the system after the failure of traditional technologies. Data mining is the extraction of appropriate features from a large amount of data. And, it supports various learning algorithms, i.e. supervised and unsupervised. Intrusion detection is basically a data-centric process so, with the help of data mining algorithms, IDS will also learn from past intrusions, and improve performance from experience along with find unusual activities. It helps in exploring the large increase in the database and gather only valid information by improving segmentation and help organizations in real-time plan and save time. It has various applications such as detecting anomalous behavior, detecting fraud and abuse, terrorist activities, and investigating crimes through lie detection. Below list of areas in which data mining technology can be carried out for intrusion detection." }, { "code": null, "e": 5890, "s": 4939, "text": "Using data mining algorithms for developing a new model for IDS: Data mining algorithm for the IDS model having a higher efficiency rate and lower false alarms. Data mining algorithms can be used for both signature-based and anomaly-based detection. In signature-based detection, training information is classified as either “normal” or “intrusion.” A classifier can then be derived to discover acknowledged intrusions. Research on this place has included the software of clarification algorithms, association rule mining, and cost-sensitive modeling. Anomaly-primarily based totally detection builds models of normal behavior and automatically detects massive deviations from it. Methods consist of the software of clustering, outlier analysis, and class algorithms, and statistical approaches. The strategies used have to be efficient and scalable, and able to dealing with community information of excessive volume, dimensional, and heterogeneity." }, { "code": null, "e": 6729, "s": 5890, "text": " Analysis of Stream data: Analysis of stream data means is analyzing the data in a continuous manner but data mining is basically used on static data rather than Streaming due to complex calculation and high processing time. Due to the dynamic nature of intrusions and malicious attacks, it is more critical to perform intrusion detection withinside the records stream environment. Moreover, an event can be ordinary on its own but taken into consideration malicious if regarded as a part of a series of activities. Thus, it’s far essential to look at what sequences of activities are regularly encountered together, locate sequential patterns, and pick out outliers. Other data mining strategies for locating evolving clusters and constructing dynamic class models in records streams also are essential for real-time intrusion detection." }, { "code": null, "e": 7158, "s": 6729, "text": "Distributed data mining: It is used to analyze the random data which is inherently distributed into various databases so, it becomes difficult to integrate processing of the data. Intrusions may be launched from numerous distinctive places and focused on many distinctive destinations. Distributed data mining strategies can be used to investigate community data from numerous network places to detect those distributed attacks." }, { "code": null, "e": 7674, "s": 7158, "text": "Visualization tools: These tools are used to represent the data in the form of graphs which helps the user to get a visual understanding of the data. These tools are also used for viewing any anomalous patterns detected. Such tools may encompass capabilities for viewing associations, discriminative patterns, clusters, and outliers. Intrusion detection structures must actually have a graphical user interface that permits safety analysts to pose queries concerning the network data or intrusion detection results." }, { "code": null, "e": 7689, "s": 7674, "text": "Blogathon-2021" }, { "code": null, "e": 7701, "s": 7689, "text": "data mining" }, { "code": null, "e": 7708, "s": 7701, "text": "Picked" }, { "code": null, "e": 7718, "s": 7708, "text": "Blogathon" }, { "code": null, "e": 7730, "s": 7718, "text": "Data Mining" } ]
Spark SQL - Quick Guide
Industries are using Hadoop extensively to analyze their data sets. The reason is that Hadoop framework is based on a simple programming model (MapReduce) and it enables a computing solution that is scalable, flexible, fault-tolerant and cost effective. Here, the main concern is to maintain speed in processing large datasets in terms of waiting time between queries and waiting time to run the program. Spark was introduced by Apache Software Foundation for speeding up the Hadoop computational computing software process. As against a common belief, Spark is not a modified version of Hadoop and is not, really, dependent on Hadoop because it has its own cluster management. Hadoop is just one of the ways to implement Spark. Spark uses Hadoop in two ways – one is storage and second is processing. Since Spark has its own cluster management computation, it uses Hadoop for storage purpose only. Apache Spark is a lightning-fast cluster computing technology, designed for fast computation. It is based on Hadoop MapReduce and it extends the MapReduce model to efficiently use it for more types of computations, which includes interactive queries and stream processing. The main feature of Spark is its in-memory cluster computing that increases the processing speed of an application. Spark is designed to cover a wide range of workloads such as batch applications, iterative algorithms, interactive queries and streaming. Apart from supporting all these workload in a respective system, it reduces the management burden of maintaining separate tools. Spark is one of Hadoop’s sub project developed in 2009 in UC Berkeley’s AMPLab by Matei Zaharia. It was Open Sourced in 2010 under a BSD license. It was donated to Apache software foundation in 2013, and now Apache Spark has become a top level Apache project from Feb-2014. Apache Spark has following features. Speed − Spark helps to run an application in Hadoop cluster, up to 100 times faster in memory, and 10 times faster when running on disk. This is possible by reducing number of read/write operations to disk. It stores the intermediate processing data in memory. Speed − Spark helps to run an application in Hadoop cluster, up to 100 times faster in memory, and 10 times faster when running on disk. This is possible by reducing number of read/write operations to disk. It stores the intermediate processing data in memory. Supports multiple languages − Spark provides built-in APIs in Java, Scala, or Python. Therefore, you can write applications in different languages. Spark comes up with 80 high-level operators for interactive querying. Supports multiple languages − Spark provides built-in APIs in Java, Scala, or Python. Therefore, you can write applications in different languages. Spark comes up with 80 high-level operators for interactive querying. Advanced Analytics − Spark not only supports ‘Map’ and ‘reduce’. It also supports SQL queries, Streaming data, Machine learning (ML), and Graph algorithms. Advanced Analytics − Spark not only supports ‘Map’ and ‘reduce’. It also supports SQL queries, Streaming data, Machine learning (ML), and Graph algorithms. The following diagram shows three ways of how Spark can be built with Hadoop components. There are three ways of Spark deployment as explained below. Standalone − Spark Standalone deployment means Spark occupies the place on top of HDFS(Hadoop Distributed File System) and space is allocated for HDFS, explicitly. Here, Spark and MapReduce will run side by side to cover all spark jobs on cluster. Standalone − Spark Standalone deployment means Spark occupies the place on top of HDFS(Hadoop Distributed File System) and space is allocated for HDFS, explicitly. Here, Spark and MapReduce will run side by side to cover all spark jobs on cluster. Hadoop Yarn − Hadoop Yarn deployment means, simply, spark runs on Yarn without any pre-installation or root access required. It helps to integrate Spark into Hadoop ecosystem or Hadoop stack. It allows other components to run on top of stack. Hadoop Yarn − Hadoop Yarn deployment means, simply, spark runs on Yarn without any pre-installation or root access required. It helps to integrate Spark into Hadoop ecosystem or Hadoop stack. It allows other components to run on top of stack. Spark in MapReduce (SIMR) − Spark in MapReduce is used to launch spark job in addition to standalone deployment. With SIMR, user can start Spark and uses its shell without any administrative access. Spark in MapReduce (SIMR) − Spark in MapReduce is used to launch spark job in addition to standalone deployment. With SIMR, user can start Spark and uses its shell without any administrative access. The following illustration depicts the different components of Spark. Spark Core is the underlying general execution engine for spark platform that all other functionality is built upon. It provides In-Memory computing and referencing datasets in external storage systems. Spark SQL is a component on top of Spark Core that introduces a new data abstraction called SchemaRDD, which provides support for structured and semi-structured data. Spark Streaming leverages Spark Core's fast scheduling capability to perform streaming analytics. It ingests data in mini-batches and performs RDD (Resilient Distributed Datasets) transformations on those mini-batches of data. MLlib is a distributed machine learning framework above Spark because of the distributed memory-based Spark architecture. It is, according to benchmarks, done by the MLlib developers against the Alternating Least Squares (ALS) implementations. Spark MLlib is nine times as fast as the Hadoop disk-based version of Apache Mahout (before Mahout gained a Spark interface). GraphX is a distributed graph-processing framework on top of Spark. It provides an API for expressing graph computation that can model the user-defined graphs by using Pregel abstraction API. It also provides an optimized runtime for this abstraction. Resilient Distributed Datasets (RDD) is a fundamental data structure of Spark. It is an immutable distributed collection of objects. Each dataset in RDD is divided into logical partitions, which may be computed on different nodes of the cluster. RDDs can contain any type of Python, Java, or Scala objects, including user-defined classes. Formally, an RDD is a read-only, partitioned collection of records. RDDs can be created through deterministic operations on either data on stable storage or other RDDs. RDD is a fault-tolerant collection of elements that can be operated on in parallel. There are two ways to create RDDs − parallelizing an existing collection in your driver program, or referencing a dataset in an external storage system, such as a shared file system, HDFS, HBase, or any data source offering a Hadoop Input Format. Spark makes use of the concept of RDD to achieve faster and efficient MapReduce operations. Let us first discuss how MapReduce operations take place and why they are not so efficient. MapReduce is widely adopted for processing and generating large datasets with a parallel, distributed algorithm on a cluster. It allows users to write parallel computations, using a set of high-level operators, without having to worry about work distribution and fault tolerance. Unfortunately, in most current frameworks, the only way to reuse data between computations (Ex: between two MapReduce jobs) is to write it to an external stable storage system (Ex: HDFS). Although this framework provides numerous abstractions for accessing a cluster’s computational resources, users still want more. Both Iterative and Interactive applications require faster data sharing across parallel jobs. Data sharing is slow in MapReduce due to replication, serialization, and disk IO. Regarding storage system, most of the Hadoop applications, they spend more than 90% of the time doing HDFS read-write operations. Reuse intermediate results across multiple computations in multi-stage applications. The following illustration explains how the current framework works, while doing the iterative operations on MapReduce. This incurs substantial overheads due to data replication, disk I/O, and serialization, which makes the system slow. User runs ad-hoc queries on the same subset of data. Each query will do the disk I/O on the stable storage, which can dominates application execution time. The following illustration explains how the current framework works while doing the interactive queries on MapReduce. Data sharing is slow in MapReduce due to replication, serialization, and disk IO. Most of the Hadoop applications, they spend more than 90% of the time doing HDFS read-write operations. Recognizing this problem, researchers developed a specialized framework called Apache Spark. The key idea of spark is Resilient Distributed Datasets (RDD); it supports in-memory processing computation. This means, it stores the state of memory as an object across the jobs and the object is sharable between those jobs. Data sharing in memory is 10 to 100 times faster than network and Disk. Let us now try to find out how iterative and interactive operations take place in Spark RDD. The illustration given below shows the iterative operations on Spark RDD. It will store intermediate results in a distributed memory instead of Stable storage (Disk) and make the system faster. Note − If the Distributed memory (RAM) in sufficient to store intermediate results (State of the JOB), then it will store those results on the disk This illustration shows interactive operations on Spark RDD. If different queries are run on the same set of data repeatedly, this particular data can be kept in memory for better execution times. By default, each transformed RDD may be recomputed each time you run an action on it. However, you may also persist an RDD in memory, in which case Spark will keep the elements around on the cluster for much faster access, the next time you query it. There is also support for persisting RDDs on disk, or replicated across multiple nodes. Spark is Hadoop’s sub-project. Therefore, it is better to install Spark into a Linux based system. The following steps show how to install Apache Spark. Java installation is one of the mandatory things in installing Spark. Try the following command to verify the JAVA version. $java -version If Java is already, installed on your system, you get to see the following response − java version "1.7.0_71" Java(TM) SE Runtime Environment (build 1.7.0_71-b13) Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode) In case you do not have Java installed on your system, then Install Java before proceeding to next step. You should Scala language to implement Spark. So let us verify Scala installation using following command. $scala -version If Scala is already installed on your system, you get to see the following response − Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL In case you don’t have Scala installed on your system, then proceed to next step for Scala installation. Download the latest version of Scala by visit the following link Download Scala. For this tutorial, we are using scala-2.11.6 version. After downloading, you will find the Scala tar file in the download folder. Follow the below given steps for installing Scala. Type the following command for extracting the Scala tar file. $ tar xvf scala-2.11.6.tgz Use the following commands for moving the Scala software files, to respective directory (/usr/local/scala). $ su – Password: # cd /home/Hadoop/Downloads/ # mv scala-2.11.6 /usr/local/scala # exit Use the following command for setting PATH for Scala. $ export PATH = $PATH:/usr/local/scala/bin After installation, it is better to verify it. Use the following command for verifying Scala installation. $scala -version If Scala is already installed on your system, you get to see the following response − Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL Download the latest version of Spark by visiting the following link Download Spark. For this tutorial, we are using spark-1.3.1-bin-hadoop2.6 version. After downloading it, you will find the Spark tar file in the download folder. Follow the steps given below for installing Spark. The following command for extracting the spark tar file. $ tar xvf spark-1.3.1-bin-hadoop2.6.tgz The following commands for moving the Spark software files to respective directory (/usr/local/spark). $ su – Password: # cd /home/Hadoop/Downloads/ # mv spark-1.3.1-bin-hadoop2.6 /usr/local/spark # exit Add the following line to ~/.bashrc file. It means adding the location, where the spark software file are located to the PATH variable. export PATH = $PATH:/usr/local/spark/bin Use the following command for sourcing the ~/.bashrc file. $ source ~/.bashrc Write the following command for opening Spark shell. $spark-shell If spark is installed successfully then you will find the following output. Spark assembly has been built with Hive, including Datanucleus jars on classpath Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties 15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop 15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop disabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop) 15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server 15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292. Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /___/ .__/\_,_/_/ /_/\_\ version 1.4.0 /_/ Using Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71) Type in expressions to have them evaluated. Spark context available as sc scala> Spark introduces a programming module for structured data processing called Spark SQL. It provides a programming abstraction called DataFrame and can act as distributed SQL query engine. The following are the features of Spark SQL − Integrated − Seamlessly mix SQL queries with Spark programs. Spark SQL lets you query structured data as a distributed dataset (RDD) in Spark, with integrated APIs in Python, Scala and Java. This tight integration makes it easy to run SQL queries alongside complex analytic algorithms. Integrated − Seamlessly mix SQL queries with Spark programs. Spark SQL lets you query structured data as a distributed dataset (RDD) in Spark, with integrated APIs in Python, Scala and Java. This tight integration makes it easy to run SQL queries alongside complex analytic algorithms. Unified Data Access − Load and query data from a variety of sources. Schema-RDDs provide a single interface for efficiently working with structured data, including Apache Hive tables, parquet files and JSON files. Unified Data Access − Load and query data from a variety of sources. Schema-RDDs provide a single interface for efficiently working with structured data, including Apache Hive tables, parquet files and JSON files. Hive Compatibility − Run unmodified Hive queries on existing warehouses. Spark SQL reuses the Hive frontend and MetaStore, giving you full compatibility with existing Hive data, queries, and UDFs. Simply install it alongside Hive. Hive Compatibility − Run unmodified Hive queries on existing warehouses. Spark SQL reuses the Hive frontend and MetaStore, giving you full compatibility with existing Hive data, queries, and UDFs. Simply install it alongside Hive. Standard Connectivity − Connect through JDBC or ODBC. Spark SQL includes a server mode with industry standard JDBC and ODBC connectivity. Standard Connectivity − Connect through JDBC or ODBC. Spark SQL includes a server mode with industry standard JDBC and ODBC connectivity. Scalability − Use the same engine for both interactive and long queries. Spark SQL takes advantage of the RDD model to support mid-query fault tolerance, letting it scale to large jobs too. Do not worry about using a different engine for historical data. Scalability − Use the same engine for both interactive and long queries. Spark SQL takes advantage of the RDD model to support mid-query fault tolerance, letting it scale to large jobs too. Do not worry about using a different engine for historical data. The following illustration explains the architecture of Spark SQL − This architecture contains three layers namely, Language API, Schema RDD, and Data Sources. Language API − Spark is compatible with different languages and Spark SQL. It is also, supported by these languages- API (python, scala, java, HiveQL). Language API − Spark is compatible with different languages and Spark SQL. It is also, supported by these languages- API (python, scala, java, HiveQL). Schema RDD − Spark Core is designed with special data structure called RDD. Generally, Spark SQL works on schemas, tables, and records. Therefore, we can use the Schema RDD as temporary table. We can call this Schema RDD as Data Frame. Schema RDD − Spark Core is designed with special data structure called RDD. Generally, Spark SQL works on schemas, tables, and records. Therefore, we can use the Schema RDD as temporary table. We can call this Schema RDD as Data Frame. Data Sources − Usually the Data source for spark-core is a text file, Avro file, etc. However, the Data Sources for Spark SQL is different. Those are Parquet file, JSON document, HIVE tables, and Cassandra database. Data Sources − Usually the Data source for spark-core is a text file, Avro file, etc. However, the Data Sources for Spark SQL is different. Those are Parquet file, JSON document, HIVE tables, and Cassandra database. We will discuss more about these in the subsequent chapters. A DataFrame is a distributed collection of data, which is organized into named columns. Conceptually, it is equivalent to relational tables with good optimization techniques. A DataFrame can be constructed from an array of different sources such as Hive tables, Structured Data files, external databases, or existing RDDs. This API was designed for modern Big Data and data science applications taking inspiration from DataFrame in R Programming and Pandas in Python. Here is a set of few characteristic features of DataFrame − Ability to process the data in the size of Kilobytes to Petabytes on a single node cluster to large cluster. Ability to process the data in the size of Kilobytes to Petabytes on a single node cluster to large cluster. Supports different data formats (Avro, csv, elastic search, and Cassandra) and storage systems (HDFS, HIVE tables, mysql, etc). Supports different data formats (Avro, csv, elastic search, and Cassandra) and storage systems (HDFS, HIVE tables, mysql, etc). State of art optimization and code generation through the Spark SQL Catalyst optimizer (tree transformation framework). State of art optimization and code generation through the Spark SQL Catalyst optimizer (tree transformation framework). Can be easily integrated with all Big Data tools and frameworks via Spark-Core. Can be easily integrated with all Big Data tools and frameworks via Spark-Core. Provides API for Python, Java, Scala, and R Programming. Provides API for Python, Java, Scala, and R Programming. SQLContext is a class and is used for initializing the functionalities of Spark SQL. SparkContext class object (sc) is required for initializing SQLContext class object. The following command is used for initializing the SparkContext through spark-shell. $ spark-shell By default, the SparkContext object is initialized with the name sc when the spark-shell starts. Use the following command to create SQLContext. scala> val sqlcontext = new org.apache.spark.sql.SQLContext(sc) Let us consider an example of employee records in a JSON file named employee.json. Use the following commands to create a DataFrame (df) and read a JSON document named employee.json with the following content. employee.json − Place this file in the directory where the current scala> pointer is located. { {"id" : "1201", "name" : "satish", "age" : "25"} {"id" : "1202", "name" : "krishna", "age" : "28"} {"id" : "1203", "name" : "amith", "age" : "39"} {"id" : "1204", "name" : "javed", "age" : "23"} {"id" : "1205", "name" : "prudvi", "age" : "23"} } DataFrame provides a domain-specific language for structured data manipulation. Here, we include some basic examples of structured data processing using DataFrames. Follow the steps given below to perform DataFrame operations − First, we have to read the JSON document. Based on this, generate a DataFrame named (dfs). Use the following command to read the JSON document named employee.json. The data is shown as a table with the fields − id, name, and age. scala> val dfs = sqlContext.read.json("employee.json") Output − The field names are taken automatically from employee.json. dfs: org.apache.spark.sql.DataFrame = [age: string, id: string, name: string] If you want to see the data in the DataFrame, then use the following command. scala> dfs.show() Output − You can see the employee data in a tabular format. <console>:22, took 0.052610 s +----+------+--------+ |age | id | name | +----+------+--------+ | 25 | 1201 | satish | | 28 | 1202 | krishna| | 39 | 1203 | amith | | 23 | 1204 | javed | | 23 | 1205 | prudvi | +----+------+--------+ If you want to see the Structure (Schema) of the DataFrame, then use the following command. scala> dfs.printSchema() Output root |-- age: string (nullable = true) |-- id: string (nullable = true) |-- name: string (nullable = true) Use the following command to fetch name-column among three columns from the DataFrame. scala> dfs.select("name").show() Output − You can see the values of the name column. <console>:22, took 0.044023 s +--------+ | name | +--------+ | satish | | krishna| | amith | | javed | | prudvi | +--------+ Use the following command for finding the employees whose age is greater than 23 (age > 23). scala> dfs.filter(dfs("age") > 23).show() Output <console>:22, took 0.078670 s +----+------+--------+ |age | id | name | +----+------+--------+ | 25 | 1201 | satish | | 28 | 1202 | krishna| | 39 | 1203 | amith | +----+------+--------+ Use the following command for counting the number of employees who are of the same age. scala> dfs.groupBy("age").count().show() Output − two employees are having age 23. <console>:22, took 5.196091 s +----+-----+ |age |count| +----+-----+ | 23 | 2 | | 25 | 1 | | 28 | 1 | | 39 | 1 | +----+-----+ An SQLContext enables applications to run SQL queries programmatically while running SQL functions and returns the result as a DataFrame. Generally, in the background, SparkSQL supports two different methods for converting existing RDDs into DataFrames − This method uses reflection to generate the schema of an RDD that contains specific types of objects. The second method for creating DataFrame is through programmatic interface that allows you to construct a schema and then apply it to an existing RDD. A DataFrame interface allows different DataSources to work on Spark SQL. It is a temporary table and can be operated as a normal RDD. Registering a DataFrame as a table allows you to run SQL queries over its data. In this chapter, we will describe the general methods for loading and saving data using different Spark DataSources. Thereafter, we will discuss in detail the specific options that are available for the built-in data sources. There are different types of data sources available in SparkSQL, some of which are listed below − Spark SQL can automatically capture the schema of a JSON dataset and load it as a DataFrame. Hive comes bundled with the Spark library as HiveContext, which inherits from SQLContext. Parquet is a columnar format, supported by many data processing systems.
[ { "code": null, "e": 2259, "s": 1854, "text": "Industries are using Hadoop extensively to analyze their data sets. The reason is that Hadoop framework is based on a simple programming model (MapReduce) and it enables a computing solution that is scalable, flexible, fault-tolerant and cost effective. Here, the main concern is to maintain speed in processing large datasets in terms of waiting time between queries and waiting time to run the program." }, { "code": null, "e": 2379, "s": 2259, "text": "Spark was introduced by Apache Software Foundation for speeding up the Hadoop computational computing software process." }, { "code": null, "e": 2583, "s": 2379, "text": "As against a common belief, Spark is not a modified version of Hadoop and is not, really, dependent on Hadoop because it has its own cluster management. Hadoop is just one of the ways to implement Spark." }, { "code": null, "e": 2753, "s": 2583, "text": "Spark uses Hadoop in two ways – one is storage and second is processing. Since Spark has its own cluster management computation, it uses Hadoop for storage purpose only." }, { "code": null, "e": 3142, "s": 2753, "text": "Apache Spark is a lightning-fast cluster computing technology, designed for fast computation. It is based on Hadoop MapReduce and it extends the MapReduce model to efficiently use it for more types of computations, which includes interactive queries and stream processing. The main feature of Spark is its in-memory cluster computing that increases the processing speed of an application." }, { "code": null, "e": 3409, "s": 3142, "text": "Spark is designed to cover a wide range of workloads such as batch applications, iterative algorithms, interactive queries and streaming. Apart from supporting all these workload in a respective system, it reduces the management burden of maintaining separate tools." }, { "code": null, "e": 3683, "s": 3409, "text": "Spark is one of Hadoop’s sub project developed in 2009 in UC Berkeley’s AMPLab by Matei Zaharia. It was Open Sourced in 2010 under a BSD license. It was donated to Apache software foundation in 2013, and now Apache Spark has become a top level Apache project from Feb-2014." }, { "code": null, "e": 3720, "s": 3683, "text": "Apache Spark has following features." }, { "code": null, "e": 3981, "s": 3720, "text": "Speed − Spark helps to run an application in Hadoop cluster, up to 100 times faster in memory, and 10 times faster when running on disk. This is possible by reducing number of read/write operations to disk. It stores the intermediate processing data in memory." }, { "code": null, "e": 4242, "s": 3981, "text": "Speed − Spark helps to run an application in Hadoop cluster, up to 100 times faster in memory, and 10 times faster when running on disk. This is possible by reducing number of read/write operations to disk. It stores the intermediate processing data in memory." }, { "code": null, "e": 4460, "s": 4242, "text": "Supports multiple languages − Spark provides built-in APIs in Java, Scala, or Python. Therefore, you can write applications in different languages. Spark comes up with 80 high-level operators for interactive querying." }, { "code": null, "e": 4678, "s": 4460, "text": "Supports multiple languages − Spark provides built-in APIs in Java, Scala, or Python. Therefore, you can write applications in different languages. Spark comes up with 80 high-level operators for interactive querying." }, { "code": null, "e": 4834, "s": 4678, "text": "Advanced Analytics − Spark not only supports ‘Map’ and ‘reduce’. It also supports SQL queries, Streaming data, Machine learning (ML), and Graph algorithms." }, { "code": null, "e": 4990, "s": 4834, "text": "Advanced Analytics − Spark not only supports ‘Map’ and ‘reduce’. It also supports SQL queries, Streaming data, Machine learning (ML), and Graph algorithms." }, { "code": null, "e": 5079, "s": 4990, "text": "The following diagram shows three ways of how Spark can be built with Hadoop components." }, { "code": null, "e": 5140, "s": 5079, "text": "There are three ways of Spark deployment as explained below." }, { "code": null, "e": 5388, "s": 5140, "text": "Standalone − Spark Standalone deployment means Spark occupies the place on top of HDFS(Hadoop Distributed File System) and space is allocated for HDFS, explicitly. Here, Spark and MapReduce will run side by side to cover all spark jobs on cluster." }, { "code": null, "e": 5636, "s": 5388, "text": "Standalone − Spark Standalone deployment means Spark occupies the place on top of HDFS(Hadoop Distributed File System) and space is allocated for HDFS, explicitly. Here, Spark and MapReduce will run side by side to cover all spark jobs on cluster." }, { "code": null, "e": 5879, "s": 5636, "text": "Hadoop Yarn − Hadoop Yarn deployment means, simply, spark runs on Yarn without any pre-installation or root access required. It helps to integrate Spark into Hadoop ecosystem or Hadoop stack. It allows other components to run on top of stack." }, { "code": null, "e": 6122, "s": 5879, "text": "Hadoop Yarn − Hadoop Yarn deployment means, simply, spark runs on Yarn without any pre-installation or root access required. It helps to integrate Spark into Hadoop ecosystem or Hadoop stack. It allows other components to run on top of stack." }, { "code": null, "e": 6321, "s": 6122, "text": "Spark in MapReduce (SIMR) − Spark in MapReduce is used to launch spark job in addition to standalone deployment. With SIMR, user can start Spark and uses its shell without any administrative access." }, { "code": null, "e": 6520, "s": 6321, "text": "Spark in MapReduce (SIMR) − Spark in MapReduce is used to launch spark job in addition to standalone deployment. With SIMR, user can start Spark and uses its shell without any administrative access." }, { "code": null, "e": 6590, "s": 6520, "text": "The following illustration depicts the different components of Spark." }, { "code": null, "e": 6793, "s": 6590, "text": "Spark Core is the underlying general execution engine for spark platform that all other functionality is built upon. It provides In-Memory computing and referencing datasets in external storage systems." }, { "code": null, "e": 6960, "s": 6793, "text": "Spark SQL is a component on top of Spark Core that introduces a new data abstraction called SchemaRDD, which provides support for structured and semi-structured data." }, { "code": null, "e": 7187, "s": 6960, "text": "Spark Streaming leverages Spark Core's fast scheduling capability to perform streaming analytics. It ingests data in mini-batches and performs RDD (Resilient Distributed Datasets) transformations on those mini-batches of data." }, { "code": null, "e": 7557, "s": 7187, "text": "MLlib is a distributed machine learning framework above Spark because of the distributed memory-based Spark architecture. It is, according to benchmarks, done by the MLlib developers against the Alternating Least Squares (ALS) implementations. Spark MLlib is nine times as fast as the Hadoop disk-based version of Apache Mahout (before Mahout gained a Spark interface)." }, { "code": null, "e": 7809, "s": 7557, "text": "GraphX is a distributed graph-processing framework on top of Spark. It provides an API for expressing graph computation that can model the user-defined graphs by using Pregel abstraction API. It also provides an optimized runtime for this abstraction." }, { "code": null, "e": 8148, "s": 7809, "text": "Resilient Distributed Datasets (RDD) is a fundamental data structure of Spark. It is an immutable distributed collection of objects. Each dataset in RDD is divided into logical partitions, which may be computed on different nodes of the cluster. RDDs can contain any type of Python, Java, or Scala objects, including user-defined classes." }, { "code": null, "e": 8401, "s": 8148, "text": "Formally, an RDD is a read-only, partitioned collection of records. RDDs can be created through deterministic operations on either data on stable storage or other RDDs. RDD is a fault-tolerant collection of elements that can be operated on in parallel." }, { "code": null, "e": 8648, "s": 8401, "text": "There are two ways to create RDDs − parallelizing an existing collection in your driver program, or referencing a dataset in an external storage system, such as a shared file system, HDFS, HBase, or any data source offering a Hadoop Input Format." }, { "code": null, "e": 8832, "s": 8648, "text": "Spark makes use of the concept of RDD to achieve faster and efficient MapReduce operations. Let us first discuss how MapReduce operations take place and why they are not so efficient." }, { "code": null, "e": 9112, "s": 8832, "text": "MapReduce is widely adopted for processing and generating large datasets with a parallel, distributed algorithm on a cluster. It allows users to write parallel computations, using a set of high-level operators, without having to worry about work distribution and fault tolerance." }, { "code": null, "e": 9429, "s": 9112, "text": "Unfortunately, in most current frameworks, the only way to reuse data between computations (Ex: between two MapReduce jobs) is to write it to an external stable storage system (Ex: HDFS). Although this framework provides numerous abstractions for accessing a cluster’s computational resources, users still want more." }, { "code": null, "e": 9735, "s": 9429, "text": "Both Iterative and Interactive applications require faster data sharing across parallel jobs. Data sharing is slow in MapReduce due to replication, serialization, and disk IO. Regarding storage system, most of the Hadoop applications, they spend more than 90% of the time doing HDFS read-write operations." }, { "code": null, "e": 10057, "s": 9735, "text": "Reuse intermediate results across multiple computations in multi-stage applications. The following illustration explains how the current framework works, while doing the iterative operations on MapReduce. This incurs substantial overheads due to data replication, disk I/O, and serialization, which makes the system slow." }, { "code": null, "e": 10213, "s": 10057, "text": "User runs ad-hoc queries on the same subset of data. Each query will do the disk I/O on the stable storage, which can dominates application execution time." }, { "code": null, "e": 10331, "s": 10213, "text": "The following illustration explains how the current framework works while doing the interactive queries on MapReduce." }, { "code": null, "e": 10517, "s": 10331, "text": "Data sharing is slow in MapReduce due to replication, serialization, and disk IO. Most of the Hadoop applications, they spend more than 90% of the time doing HDFS read-write operations." }, { "code": null, "e": 10909, "s": 10517, "text": "Recognizing this problem, researchers developed a specialized framework called Apache Spark. The key idea of spark is Resilient Distributed Datasets (RDD); it supports in-memory processing computation. This means, it stores the state of memory as an object across the jobs and the object is sharable between those jobs. Data sharing in memory is 10 to 100 times faster than network and Disk." }, { "code": null, "e": 11002, "s": 10909, "text": "Let us now try to find out how iterative and interactive operations take place in Spark RDD." }, { "code": null, "e": 11196, "s": 11002, "text": "The illustration given below shows the iterative operations on Spark RDD. It will store intermediate results in a distributed memory instead of Stable storage (Disk) and make the system faster." }, { "code": null, "e": 11344, "s": 11196, "text": "Note − If the Distributed memory (RAM) in sufficient to store intermediate results (State of the JOB), then it will store those results on the disk" }, { "code": null, "e": 11541, "s": 11344, "text": "This illustration shows interactive operations on Spark RDD. If different queries are run on the same set of data repeatedly, this particular data can be kept in memory for better execution times." }, { "code": null, "e": 11880, "s": 11541, "text": "By default, each transformed RDD may be recomputed each time you run an action on it. However, you may also persist an RDD in memory, in which case Spark will keep the elements around on the cluster for much faster access, the next time you query it. There is also support for persisting RDDs on disk, or replicated across multiple nodes." }, { "code": null, "e": 12033, "s": 11880, "text": "Spark is Hadoop’s sub-project. Therefore, it is better to install Spark into a Linux based system. The following steps show how to install Apache Spark." }, { "code": null, "e": 12157, "s": 12033, "text": "Java installation is one of the mandatory things in installing Spark. Try the following command to verify the JAVA version." }, { "code": null, "e": 12173, "s": 12157, "text": "$java -version\n" }, { "code": null, "e": 12259, "s": 12173, "text": "If Java is already, installed on your system, you get to see the following response −" }, { "code": null, "e": 12393, "s": 12259, "text": "java version \"1.7.0_71\"\nJava(TM) SE Runtime Environment (build 1.7.0_71-b13)\nJava HotSpot(TM) Client VM (build 25.0-b02, mixed mode)\n" }, { "code": null, "e": 12498, "s": 12393, "text": "In case you do not have Java installed on your system, then Install Java before proceeding to next step." }, { "code": null, "e": 12605, "s": 12498, "text": "You should Scala language to implement Spark. So let us verify Scala installation using following command." }, { "code": null, "e": 12622, "s": 12605, "text": "$scala -version\n" }, { "code": null, "e": 12708, "s": 12622, "text": "If Scala is already installed on your system, you get to see the following response −" }, { "code": null, "e": 12776, "s": 12708, "text": "Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL\n" }, { "code": null, "e": 12881, "s": 12776, "text": "In case you don’t have Scala installed on your system, then proceed to next step for Scala installation." }, { "code": null, "e": 13092, "s": 12881, "text": "Download the latest version of Scala by visit the following link Download Scala. For this tutorial, we are using scala-2.11.6 version. After downloading, you will find the Scala tar file in the download folder." }, { "code": null, "e": 13143, "s": 13092, "text": "Follow the below given steps for installing Scala." }, { "code": null, "e": 13205, "s": 13143, "text": "Type the following command for extracting the Scala tar file." }, { "code": null, "e": 13233, "s": 13205, "text": "$ tar xvf scala-2.11.6.tgz\n" }, { "code": null, "e": 13341, "s": 13233, "text": "Use the following commands for moving the Scala software files, to respective directory (/usr/local/scala)." }, { "code": null, "e": 13430, "s": 13341, "text": "$ su –\nPassword:\n# cd /home/Hadoop/Downloads/\n# mv scala-2.11.6 /usr/local/scala\n# exit\n" }, { "code": null, "e": 13484, "s": 13430, "text": "Use the following command for setting PATH for Scala." }, { "code": null, "e": 13528, "s": 13484, "text": "$ export PATH = $PATH:/usr/local/scala/bin\n" }, { "code": null, "e": 13635, "s": 13528, "text": "After installation, it is better to verify it. Use the following command for verifying Scala installation." }, { "code": null, "e": 13652, "s": 13635, "text": "$scala -version\n" }, { "code": null, "e": 13738, "s": 13652, "text": "If Scala is already installed on your system, you get to see the following response −" }, { "code": null, "e": 13806, "s": 13738, "text": "Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL\n" }, { "code": null, "e": 14036, "s": 13806, "text": "Download the latest version of Spark by visiting the following link Download Spark. For this tutorial, we are using spark-1.3.1-bin-hadoop2.6 version. After downloading it, you will find the Spark tar file in the download folder." }, { "code": null, "e": 14087, "s": 14036, "text": "Follow the steps given below for installing Spark." }, { "code": null, "e": 14144, "s": 14087, "text": "The following command for extracting the spark tar file." }, { "code": null, "e": 14185, "s": 14144, "text": "$ tar xvf spark-1.3.1-bin-hadoop2.6.tgz\n" }, { "code": null, "e": 14288, "s": 14185, "text": "The following commands for moving the Spark software files to respective directory (/usr/local/spark)." }, { "code": null, "e": 14390, "s": 14288, "text": "$ su –\nPassword:\n# cd /home/Hadoop/Downloads/\n# mv spark-1.3.1-bin-hadoop2.6 /usr/local/spark\n# exit\n" }, { "code": null, "e": 14526, "s": 14390, "text": "Add the following line to ~/.bashrc file. It means adding the location, where the spark software file are located to the PATH variable." }, { "code": null, "e": 14568, "s": 14526, "text": "export PATH = $PATH:/usr/local/spark/bin\n" }, { "code": null, "e": 14627, "s": 14568, "text": "Use the following command for sourcing the ~/.bashrc file." }, { "code": null, "e": 14647, "s": 14627, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 14700, "s": 14647, "text": "Write the following command for opening Spark shell." }, { "code": null, "e": 14714, "s": 14700, "text": "$spark-shell\n" }, { "code": null, "e": 14790, "s": 14714, "text": "If spark is installed successfully then you will find the following output." }, { "code": null, "e": 15656, "s": 14790, "text": "Spark assembly has been built with Hive, including Datanucleus jars on classpath\nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties\n15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop\n15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop\ndisabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)\n15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server\n15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292.\nWelcome to\n ____ __\n / __/__ ___ _____/ /__\n _\\ \\/ _ \\/ _ `/ __/ '_/\n /___/ .__/\\_,_/_/ /_/\\_\\ version 1.4.0\n /_/\nUsing Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71)\nType in expressions to have them evaluated.\nSpark context available as sc\nscala>\n" }, { "code": null, "e": 15843, "s": 15656, "text": "Spark introduces a programming module for structured data processing called Spark SQL. It provides a programming abstraction called DataFrame and can act as distributed SQL query engine." }, { "code": null, "e": 15889, "s": 15843, "text": "The following are the features of Spark SQL −" }, { "code": null, "e": 16175, "s": 15889, "text": "Integrated − Seamlessly mix SQL queries with Spark programs. Spark SQL lets you query structured data as a distributed dataset (RDD) in Spark, with integrated APIs in Python, Scala and Java. This tight integration makes it easy to run SQL queries alongside complex analytic algorithms." }, { "code": null, "e": 16461, "s": 16175, "text": "Integrated − Seamlessly mix SQL queries with Spark programs. Spark SQL lets you query structured data as a distributed dataset (RDD) in Spark, with integrated APIs in Python, Scala and Java. This tight integration makes it easy to run SQL queries alongside complex analytic algorithms." }, { "code": null, "e": 16675, "s": 16461, "text": "Unified Data Access − Load and query data from a variety of sources. Schema-RDDs provide a single interface for efficiently working with structured data, including Apache Hive tables, parquet files and JSON files." }, { "code": null, "e": 16889, "s": 16675, "text": "Unified Data Access − Load and query data from a variety of sources. Schema-RDDs provide a single interface for efficiently working with structured data, including Apache Hive tables, parquet files and JSON files." }, { "code": null, "e": 17120, "s": 16889, "text": "Hive Compatibility − Run unmodified Hive queries on existing warehouses. Spark SQL reuses the Hive frontend and MetaStore, giving you full compatibility with existing Hive data, queries, and UDFs. Simply install it alongside Hive." }, { "code": null, "e": 17351, "s": 17120, "text": "Hive Compatibility − Run unmodified Hive queries on existing warehouses. Spark SQL reuses the Hive frontend and MetaStore, giving you full compatibility with existing Hive data, queries, and UDFs. Simply install it alongside Hive." }, { "code": null, "e": 17489, "s": 17351, "text": "Standard Connectivity − Connect through JDBC or ODBC. Spark SQL includes a server mode with industry standard JDBC and ODBC connectivity." }, { "code": null, "e": 17627, "s": 17489, "text": "Standard Connectivity − Connect through JDBC or ODBC. Spark SQL includes a server mode with industry standard JDBC and ODBC connectivity." }, { "code": null, "e": 17882, "s": 17627, "text": "Scalability − Use the same engine for both interactive and long queries. Spark SQL takes advantage of the RDD model to support mid-query fault tolerance, letting it scale to large jobs too. Do not worry about using a different engine for historical data." }, { "code": null, "e": 18137, "s": 17882, "text": "Scalability − Use the same engine for both interactive and long queries. Spark SQL takes advantage of the RDD model to support mid-query fault tolerance, letting it scale to large jobs too. Do not worry about using a different engine for historical data." }, { "code": null, "e": 18205, "s": 18137, "text": "The following illustration explains the architecture of Spark SQL −" }, { "code": null, "e": 18297, "s": 18205, "text": "This architecture contains three layers namely, Language API, Schema RDD, and Data Sources." }, { "code": null, "e": 18449, "s": 18297, "text": "Language API − Spark is compatible with different languages and Spark SQL. It is also, supported by these languages- API (python, scala, java, HiveQL)." }, { "code": null, "e": 18601, "s": 18449, "text": "Language API − Spark is compatible with different languages and Spark SQL. It is also, supported by these languages- API (python, scala, java, HiveQL)." }, { "code": null, "e": 18837, "s": 18601, "text": "Schema RDD − Spark Core is designed with special data structure called RDD. Generally, Spark SQL works on schemas, tables, and records. Therefore, we can use the Schema RDD as temporary table. We can call this Schema RDD as Data Frame." }, { "code": null, "e": 19073, "s": 18837, "text": "Schema RDD − Spark Core is designed with special data structure called RDD. Generally, Spark SQL works on schemas, tables, and records. Therefore, we can use the Schema RDD as temporary table. We can call this Schema RDD as Data Frame." }, { "code": null, "e": 19289, "s": 19073, "text": "Data Sources − Usually the Data source for spark-core is a text file, Avro file, etc. However, the Data Sources for Spark SQL is different. Those are Parquet file, JSON document, HIVE tables, and Cassandra database." }, { "code": null, "e": 19505, "s": 19289, "text": "Data Sources − Usually the Data source for spark-core is a text file, Avro file, etc. However, the Data Sources for Spark SQL is different. Those are Parquet file, JSON document, HIVE tables, and Cassandra database." }, { "code": null, "e": 19566, "s": 19505, "text": "We will discuss more about these in the subsequent chapters." }, { "code": null, "e": 19741, "s": 19566, "text": "A DataFrame is a distributed collection of data, which is organized into named columns. Conceptually, it is equivalent to relational tables with good optimization techniques." }, { "code": null, "e": 20034, "s": 19741, "text": "A DataFrame can be constructed from an array of different sources such as Hive tables, Structured Data files, external databases, or existing RDDs. This API was designed for modern Big Data and data science applications taking inspiration from DataFrame in R Programming and Pandas in Python." }, { "code": null, "e": 20094, "s": 20034, "text": "Here is a set of few characteristic features of DataFrame −" }, { "code": null, "e": 20203, "s": 20094, "text": "Ability to process the data in the size of Kilobytes to Petabytes on a single node cluster to large cluster." }, { "code": null, "e": 20312, "s": 20203, "text": "Ability to process the data in the size of Kilobytes to Petabytes on a single node cluster to large cluster." }, { "code": null, "e": 20440, "s": 20312, "text": "Supports different data formats (Avro, csv, elastic search, and Cassandra) and storage systems (HDFS, HIVE tables, mysql, etc)." }, { "code": null, "e": 20568, "s": 20440, "text": "Supports different data formats (Avro, csv, elastic search, and Cassandra) and storage systems (HDFS, HIVE tables, mysql, etc)." }, { "code": null, "e": 20688, "s": 20568, "text": "State of art optimization and code generation through the Spark SQL Catalyst optimizer (tree transformation framework)." }, { "code": null, "e": 20808, "s": 20688, "text": "State of art optimization and code generation through the Spark SQL Catalyst optimizer (tree transformation framework)." }, { "code": null, "e": 20888, "s": 20808, "text": "Can be easily integrated with all Big Data tools and frameworks via Spark-Core." }, { "code": null, "e": 20968, "s": 20888, "text": "Can be easily integrated with all Big Data tools and frameworks via Spark-Core." }, { "code": null, "e": 21025, "s": 20968, "text": "Provides API for Python, Java, Scala, and R Programming." }, { "code": null, "e": 21082, "s": 21025, "text": "Provides API for Python, Java, Scala, and R Programming." }, { "code": null, "e": 21252, "s": 21082, "text": "SQLContext is a class and is used for initializing the functionalities of Spark SQL. SparkContext class object (sc) is required for initializing SQLContext class object." }, { "code": null, "e": 21337, "s": 21252, "text": "The following command is used for initializing the SparkContext through spark-shell." }, { "code": null, "e": 21352, "s": 21337, "text": "$ spark-shell\n" }, { "code": null, "e": 21449, "s": 21352, "text": "By default, the SparkContext object is initialized with the name sc when the spark-shell starts." }, { "code": null, "e": 21497, "s": 21449, "text": "Use the following command to create SQLContext." }, { "code": null, "e": 21562, "s": 21497, "text": "scala> val sqlcontext = new org.apache.spark.sql.SQLContext(sc)\n" }, { "code": null, "e": 21772, "s": 21562, "text": "Let us consider an example of employee records in a JSON file named employee.json. Use the following commands to create a DataFrame (df) and read a JSON document named employee.json with the following content." }, { "code": null, "e": 21866, "s": 21772, "text": "employee.json − Place this file in the directory where the current scala> pointer is located." }, { "code": null, "e": 22129, "s": 21866, "text": "{\n {\"id\" : \"1201\", \"name\" : \"satish\", \"age\" : \"25\"}\n {\"id\" : \"1202\", \"name\" : \"krishna\", \"age\" : \"28\"}\n {\"id\" : \"1203\", \"name\" : \"amith\", \"age\" : \"39\"}\n {\"id\" : \"1204\", \"name\" : \"javed\", \"age\" : \"23\"}\n {\"id\" : \"1205\", \"name\" : \"prudvi\", \"age\" : \"23\"}\n}" }, { "code": null, "e": 22294, "s": 22129, "text": "DataFrame provides a domain-specific language for structured data manipulation. Here, we include some basic examples of structured data processing using DataFrames." }, { "code": null, "e": 22357, "s": 22294, "text": "Follow the steps given below to perform DataFrame operations −" }, { "code": null, "e": 22448, "s": 22357, "text": "First, we have to read the JSON document. Based on this, generate a DataFrame named (dfs)." }, { "code": null, "e": 22587, "s": 22448, "text": "Use the following command to read the JSON document named employee.json. The data is shown as a table with the fields − id, name, and age." }, { "code": null, "e": 22643, "s": 22587, "text": "scala> val dfs = sqlContext.read.json(\"employee.json\")\n" }, { "code": null, "e": 22712, "s": 22643, "text": "Output − The field names are taken automatically from employee.json." }, { "code": null, "e": 22791, "s": 22712, "text": "dfs: org.apache.spark.sql.DataFrame = [age: string, id: string, name: string]\n" }, { "code": null, "e": 22869, "s": 22791, "text": "If you want to see the data in the DataFrame, then use the following command." }, { "code": null, "e": 22888, "s": 22869, "text": "scala> dfs.show()\n" }, { "code": null, "e": 22948, "s": 22888, "text": "Output − You can see the employee data in a tabular format." }, { "code": null, "e": 23186, "s": 22948, "text": "<console>:22, took 0.052610 s\n+----+------+--------+\n|age | id | name |\n+----+------+--------+\n| 25 | 1201 | satish |\n| 28 | 1202 | krishna|\n| 39 | 1203 | amith |\n| 23 | 1204 | javed |\n| 23 | 1205 | prudvi |\n+----+------+--------+\n" }, { "code": null, "e": 23278, "s": 23186, "text": "If you want to see the Structure (Schema) of the DataFrame, then use the following command." }, { "code": null, "e": 23304, "s": 23278, "text": "scala> dfs.printSchema()\n" }, { "code": null, "e": 23311, "s": 23304, "text": "Output" }, { "code": null, "e": 23428, "s": 23311, "text": "root\n |-- age: string (nullable = true)\n |-- id: string (nullable = true)\n |-- name: string (nullable = true)\n" }, { "code": null, "e": 23515, "s": 23428, "text": "Use the following command to fetch name-column among three columns from the DataFrame." }, { "code": null, "e": 23549, "s": 23515, "text": "scala> dfs.select(\"name\").show()\n" }, { "code": null, "e": 23601, "s": 23549, "text": "Output − You can see the values of the name column." }, { "code": null, "e": 23731, "s": 23601, "text": "<console>:22, took 0.044023 s\n+--------+\n| name |\n+--------+\n| satish |\n| krishna|\n| amith |\n| javed |\n| prudvi |\n+--------+\n" }, { "code": null, "e": 23824, "s": 23731, "text": "Use the following command for finding the employees whose age is greater than 23 (age > 23)." }, { "code": null, "e": 23867, "s": 23824, "text": "scala> dfs.filter(dfs(\"age\") > 23).show()\n" }, { "code": null, "e": 23874, "s": 23867, "text": "Output" }, { "code": null, "e": 24066, "s": 23874, "text": "<console>:22, took 0.078670 s\n+----+------+--------+\n|age | id | name |\n+----+------+--------+\n| 25 | 1201 | satish |\n| 28 | 1202 | krishna|\n| 39 | 1203 | amith |\n+----+------+--------+\n" }, { "code": null, "e": 24154, "s": 24066, "text": "Use the following command for counting the number of employees who are of the same age." }, { "code": null, "e": 24196, "s": 24154, "text": "scala> dfs.groupBy(\"age\").count().show()\n" }, { "code": null, "e": 24238, "s": 24196, "text": "Output − two employees are having age 23." }, { "code": null, "e": 24373, "s": 24238, "text": "<console>:22, took 5.196091 s\n+----+-----+\n|age |count|\n+----+-----+\n| 23 | 2 |\n| 25 | 1 |\n| 28 | 1 |\n| 39 | 1 |\n+----+-----+\n" }, { "code": null, "e": 24511, "s": 24373, "text": "An SQLContext enables applications to run SQL queries programmatically while running SQL functions and returns the result as a DataFrame." }, { "code": null, "e": 24628, "s": 24511, "text": "Generally, in the background, SparkSQL supports two different methods for converting existing RDDs into DataFrames −" }, { "code": null, "e": 24730, "s": 24628, "text": "This method uses reflection to generate the schema of an RDD that contains specific types of objects." }, { "code": null, "e": 24881, "s": 24730, "text": "The second method for creating DataFrame is through programmatic interface that allows you to construct a schema and then apply it to an existing RDD." }, { "code": null, "e": 25095, "s": 24881, "text": "A DataFrame interface allows different DataSources to work on Spark SQL. It is a temporary table and can be operated as a normal RDD. Registering a DataFrame as a table allows you to run SQL queries over its data." }, { "code": null, "e": 25321, "s": 25095, "text": "In this chapter, we will describe the general methods for loading and saving data using different Spark DataSources. Thereafter, we will discuss in detail the specific options that are available for the built-in data sources." }, { "code": null, "e": 25419, "s": 25321, "text": "There are different types of data sources available in SparkSQL, some of which are listed below −" }, { "code": null, "e": 25512, "s": 25419, "text": "Spark SQL can automatically capture the schema of a JSON dataset and load it as a DataFrame." }, { "code": null, "e": 25602, "s": 25512, "text": "Hive comes bundled with the Spark library as HiveContext, which inherits from SQLContext." } ]
Sets in Python
03 Mar, 2022 A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes like we do in lists. Python3 # Python program to# demonstrate sets # Same as {"a", "b", "c"}myset = set(["a", "b", "c"])print(myset) # Adding element to the setmyset.add("d")print(myset) {'c', 'b', 'a'} {'d', 'c', 'b', 'a'} Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. If no parameters are passed, it returns an empty frozenset. Python # Python program to demonstrate differences# between normal and frozen set # Same as {"a", "b","c"}normal_set = set(["a", "b","c"]) print("Normal Set")print(normal_set) # A frozen setfrozen_set = frozenset(["e", "f", "g"]) print("\nFrozen Set")print(frozen_set) # Uncommenting below line would cause error as# we are trying to add element to a frozen set# frozen_set.add("h") Normal Set set(['a', 'c', 'b']) Frozen Set frozenset(['e', 'g', 'f']) This is based on a data structure known as a hash table. If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, Python Sets are implemented using dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.Set Implementation:- Sets with Numerous operations on a single HashTable:- Insertion in set is done through set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case it can become O(n). Python3 # A Python program to# demonstrate adding elements# in a set # Creating a Setpeople = {"Jay", "Idrish", "Archi"} print("People:", end = " ")print(people) # This will add Daxit# in the setpeople.add("Daxit") # Adding elements to the# set using iteratorfor i in range(1, 6): people.add(i) print("\nSet after adding element:", end = " ")print(people) People: {'Idrish', 'Archi', 'Jay'} Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'} Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done. Python3 # Python Program to# demonstrate union of# two sets people = {"Jay", "Idrish", "Archil"}vampires = {"Karan", "Arjun"}dracula = {"Deepanshu", "Raju"} # Union using union()# functionpopulation = people.union(vampires) print("Union using union() function")print(population) # Union using "|"# operatorpopulation = people|dracula print("\nUnion using '|' operator")print(population) Union using union() function {'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'} Union using '|' operator {'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'} This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done. Python3 # Python program to# demonstrate intersection# of two sets set1 = set()set2 = set() for i in range(5): set1.add(i) for i in range(3,9): set2.add(i) # Intersection using# intersection() functionset3 = set1.intersection(set2) print("Intersection using intersection() function")print(set3) # Intersection using# "&" operatorset3 = set1 & set2 print("\nIntersection using '&' operator")print(set3) Intersection using intersection() function {3, 4} Intersection using '&' operator {3, 4} To find difference in between sets. Similar to find difference in linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1)) Python3 # Python program to# demonstrate difference# of two sets set1 = set()set2 = set() for i in range(5): set1.add(i) for i in range(3,9): set2.add(i) # Difference of two sets# using difference() functionset3 = set1.difference(set2) print(" Difference of two sets using difference() function")print(set3) # Difference of two sets# using '-' operatorset3 = set1 - set2 print("\nDifference of two sets using '-' operator")print(set3) Difference of two sets using difference() function {0, 1, 2} Difference of two sets using '-' operator {0, 1, 2} Clear() method empties the whole set. Python3 # Python program to# demonstrate clearing# of set set1 = {1,2,3,4,5,6} print("Initial set")print(set1) # This method will remove# all the elements of the setset1.clear() print("\nSet after using clear() function")print(set1) Initial set {1, 2, 3, 4, 5, 6} Set after using clear() function set() However, there are two major pitfalls in Python sets: The set doesn’t maintain elements in any particular order.Only instances of immutable types can be added to a Python set. The set doesn’t maintain elements in any particular order. Only instances of immutable types can be added to a Python set. Sets and frozen sets support the following operators: Code Snippet to illustrate all Set operations in Python Python # Python program to demonstrate working# of# Set in Python # Creating two setsset1 = set()set2 = set() # Adding elements to set1for i in range(1, 6): set1.add(i) # Adding elements to set2for i in range(3, 8): set2.add(i) print("Set1 = ", set1)print("Set2 = ", set2)print("\n") # Union of set1 and set2set3 = set1 | set2# set1.union(set2)print("Union of Set1 & Set2: Set3 = ", set3) # Intersection of set1 and set2set4 = set1 & set2# set1.intersection(set2)print("Intersection of Set1 & Set2: Set4 = ", set4)print("\n") # Checking relation between set3 and set4if set3 > set4: # set3.issuperset(set4) print("Set3 is superset of Set4")else if set3 < set4: # set3.issubset(set4) print("Set3 is subset of Set4")else : # set3 == set4 print("Set3 is same as Set4") # displaying relation between set4 and set3if set4 < set3: # set4.issubset(set3) print("Set4 is subset of Set3") print("\n") # difference between set3 and set4set5 = set3 - set4print("Elements in Set3 and not in Set4: Set5 = ", set5)print("\n") # check if set4 and set5 are disjoint setsif set4.isdisjoint(set5): print("Set4 and Set5 have nothing in common\n") # Removing all the values of set5set5.clear() print("After applying clear on sets Set5: ")print("Set5 = ", set5) ('Set1 = ', set([1, 2, 3, 4, 5])) ('Set2 = ', set([3, 4, 5, 6, 7])) ('Union of Set1 & Set2: Set3 = ', set([1, 2, 3, 4, 5, 6, 7])) ('Intersection of Set1 & Set2: Set4 = ', set([3, 4, 5])) Set3 is superset of Set4 Set4 is subset of Set3 ('Elements in Set3 and not in Set4: Set5 = ', set([1, 2, 6, 7])) Set4 and Set5 have nothing in common After applying clear on sets Set5: ('Set5 = ', set([])) Recent articles on Python Set. This article is contributed by Jay Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nikhilaggarwal3 surinderdawra388 python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Mar, 2022" }, { "code": null, "e": 522, "s": 52, "text": "A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes like we do in lists. " }, { "code": null, "e": 530, "s": 522, "text": "Python3" }, { "code": "# Python program to# demonstrate sets # Same as {\"a\", \"b\", \"c\"}myset = set([\"a\", \"b\", \"c\"])print(myset) # Adding element to the setmyset.add(\"d\")print(myset)", "e": 688, "s": 530, "text": null }, { "code": null, "e": 725, "s": 688, "text": "{'c', 'b', 'a'}\n{'d', 'c', 'b', 'a'}" }, { "code": null, "e": 1074, "s": 727, "text": "Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. If no parameters are passed, it returns an empty frozenset. " }, { "code": null, "e": 1081, "s": 1074, "text": "Python" }, { "code": "# Python program to demonstrate differences# between normal and frozen set # Same as {\"a\", \"b\",\"c\"}normal_set = set([\"a\", \"b\",\"c\"]) print(\"Normal Set\")print(normal_set) # A frozen setfrozen_set = frozenset([\"e\", \"f\", \"g\"]) print(\"\\nFrozen Set\")print(frozen_set) # Uncommenting below line would cause error as# we are trying to add element to a frozen set# frozen_set.add(\"h\")", "e": 1457, "s": 1081, "text": null }, { "code": null, "e": 1528, "s": 1457, "text": "Normal Set\nset(['a', 'c', 'b'])\n\nFrozen Set\nfrozenset(['e', 'g', 'f'])" }, { "code": null, "e": 1896, "s": 1530, "text": "This is based on a data structure known as a hash table. If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, Python Sets are implemented using dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.Set Implementation:- " }, { "code": null, "e": 1951, "s": 1896, "text": "Sets with Numerous operations on a single HashTable:- " }, { "code": null, "e": 2178, "s": 1955, "text": "Insertion in set is done through set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case it can become O(n). " }, { "code": null, "e": 2186, "s": 2178, "text": "Python3" }, { "code": "# A Python program to# demonstrate adding elements# in a set # Creating a Setpeople = {\"Jay\", \"Idrish\", \"Archi\"} print(\"People:\", end = \" \")print(people) # This will add Daxit# in the setpeople.add(\"Daxit\") # Adding elements to the# set using iteratorfor i in range(1, 6): people.add(i) print(\"\\nSet after adding element:\", end = \" \")print(people)", "e": 2537, "s": 2186, "text": null }, { "code": null, "e": 2650, "s": 2537, "text": "People: {'Idrish', 'Archi', 'Jay'}\n\nSet after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'}" }, { "code": null, "e": 2974, "s": 2652, "text": "Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done. " }, { "code": null, "e": 2982, "s": 2974, "text": "Python3" }, { "code": "# Python Program to# demonstrate union of# two sets people = {\"Jay\", \"Idrish\", \"Archil\"}vampires = {\"Karan\", \"Arjun\"}dracula = {\"Deepanshu\", \"Raju\"} # Union using union()# functionpopulation = people.union(vampires) print(\"Union using union() function\")print(population) # Union using \"|\"# operatorpopulation = people|dracula print(\"\\nUnion using '|' operator\")print(population)", "e": 3361, "s": 2982, "text": null }, { "code": null, "e": 3511, "s": 3361, "text": "Union using union() function\n{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}\n\nUnion using '|' operator\n{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}" }, { "code": null, "e": 3808, "s": 3513, "text": "This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done. " }, { "code": null, "e": 3816, "s": 3808, "text": "Python3" }, { "code": "# Python program to# demonstrate intersection# of two sets set1 = set()set2 = set() for i in range(5): set1.add(i) for i in range(3,9): set2.add(i) # Intersection using# intersection() functionset3 = set1.intersection(set2) print(\"Intersection using intersection() function\")print(set3) # Intersection using# \"&\" operatorset3 = set1 & set2 print(\"\\nIntersection using '&' operator\")print(set3)", "e": 4216, "s": 3816, "text": null }, { "code": null, "e": 4306, "s": 4216, "text": "Intersection using intersection() function\n{3, 4}\n\nIntersection using '&' operator\n{3, 4}" }, { "code": null, "e": 4497, "s": 4308, "text": "To find difference in between sets. Similar to find difference in linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1)) " }, { "code": null, "e": 4505, "s": 4497, "text": "Python3" }, { "code": "# Python program to# demonstrate difference# of two sets set1 = set()set2 = set() for i in range(5): set1.add(i) for i in range(3,9): set2.add(i) # Difference of two sets# using difference() functionset3 = set1.difference(set2) print(\" Difference of two sets using difference() function\")print(set3) # Difference of two sets# using '-' operatorset3 = set1 - set2 print(\"\\nDifference of two sets using '-' operator\")print(set3)", "e": 4938, "s": 4505, "text": null }, { "code": null, "e": 5052, "s": 4938, "text": "Difference of two sets using difference() function\n{0, 1, 2}\n\nDifference of two sets using '-' operator\n{0, 1, 2}" }, { "code": null, "e": 5093, "s": 5054, "text": "Clear() method empties the whole set. " }, { "code": null, "e": 5101, "s": 5093, "text": "Python3" }, { "code": "# Python program to# demonstrate clearing# of set set1 = {1,2,3,4,5,6} print(\"Initial set\")print(set1) # This method will remove# all the elements of the setset1.clear() print(\"\\nSet after using clear() function\")print(set1)", "e": 5326, "s": 5101, "text": null }, { "code": null, "e": 5397, "s": 5326, "text": "Initial set\n{1, 2, 3, 4, 5, 6}\n\nSet after using clear() function\nset()" }, { "code": null, "e": 5455, "s": 5399, "text": "However, there are two major pitfalls in Python sets: " }, { "code": null, "e": 5577, "s": 5455, "text": "The set doesn’t maintain elements in any particular order.Only instances of immutable types can be added to a Python set." }, { "code": null, "e": 5636, "s": 5577, "text": "The set doesn’t maintain elements in any particular order." }, { "code": null, "e": 5700, "s": 5636, "text": "Only instances of immutable types can be added to a Python set." }, { "code": null, "e": 5761, "s": 5706, "text": "Sets and frozen sets support the following operators: " }, { "code": null, "e": 5818, "s": 5761, "text": "Code Snippet to illustrate all Set operations in Python " }, { "code": null, "e": 5825, "s": 5818, "text": "Python" }, { "code": "# Python program to demonstrate working# of# Set in Python # Creating two setsset1 = set()set2 = set() # Adding elements to set1for i in range(1, 6): set1.add(i) # Adding elements to set2for i in range(3, 8): set2.add(i) print(\"Set1 = \", set1)print(\"Set2 = \", set2)print(\"\\n\") # Union of set1 and set2set3 = set1 | set2# set1.union(set2)print(\"Union of Set1 & Set2: Set3 = \", set3) # Intersection of set1 and set2set4 = set1 & set2# set1.intersection(set2)print(\"Intersection of Set1 & Set2: Set4 = \", set4)print(\"\\n\") # Checking relation between set3 and set4if set3 > set4: # set3.issuperset(set4) print(\"Set3 is superset of Set4\")else if set3 < set4: # set3.issubset(set4) print(\"Set3 is subset of Set4\")else : # set3 == set4 print(\"Set3 is same as Set4\") # displaying relation between set4 and set3if set4 < set3: # set4.issubset(set3) print(\"Set4 is subset of Set3\") print(\"\\n\") # difference between set3 and set4set5 = set3 - set4print(\"Elements in Set3 and not in Set4: Set5 = \", set5)print(\"\\n\") # check if set4 and set5 are disjoint setsif set4.isdisjoint(set5): print(\"Set4 and Set5 have nothing in common\\n\") # Removing all the values of set5set5.clear() print(\"After applying clear on sets Set5: \")print(\"Set5 = \", set5)", "e": 7082, "s": 5825, "text": null }, { "code": null, "e": 7485, "s": 7082, "text": "('Set1 = ', set([1, 2, 3, 4, 5]))\n('Set2 = ', set([3, 4, 5, 6, 7]))\n\n\n('Union of Set1 & Set2: Set3 = ', set([1, 2, 3, 4, 5, 6, 7]))\n('Intersection of Set1 & Set2: Set4 = ', set([3, 4, 5]))\n\n\nSet3 is superset of Set4\nSet4 is subset of Set3\n\n\n('Elements in Set3 and not in Set4: Set5 = ', set([1, 2, 6, 7]))\n\n\nSet4 and Set5 have nothing in common\n\nAfter applying clear on sets Set5: \n('Set5 = ', set([]))" }, { "code": null, "e": 7519, "s": 7487, "text": "Recent articles on Python Set. " }, { "code": null, "e": 7783, "s": 7519, "text": "This article is contributed by Jay Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7909, "s": 7785, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 7927, "s": 7911, "text": "nikhilaggarwal3" }, { "code": null, "e": 7944, "s": 7927, "text": "surinderdawra388" }, { "code": null, "e": 7955, "s": 7944, "text": "python-set" }, { "code": null, "e": 7962, "s": 7955, "text": "Python" }, { "code": null, "e": 7973, "s": 7962, "text": "python-set" } ]
SQL Query to Check or Find the Column Name Which Is Primary Key Column
08 Apr, 2021 Structured Query Language or SQL, is composed of commands that enable users to create database and table structures, perform various types of data manipulation and data administration and query the database to extract useful information. We will start with creating the database “geeksforgeeks” and then we will proceed with creating a table “interns” in that database. After this we will execute our query on the table. Creating Database : CREATE DATABASE geeksforgeeks; To use above created database : USE geeksforgeeks; Create Table : CREATE TABLE interns( id SERIAL PRIMARY KEY, name VARCHAR(30), gender VARCHAR(1), mobile BIGINT, email VARCHAR(35), city VARCHAR(25)); To see description of above created table : DESC interns; Insert data into the table : INSERT INTO interns(name, gender, mobile, email, city) VALUES ('Richa', 'F', '7999022923', '[email protected]', 'Delhi'); INSERT INTO interns(name, gender, mobile, email, city) VALUES ('Shivam', 'M', '9999028833', '[email protected]', 'Pune'); INSERT INTO interns(name, gender, mobile, email, city) VALUES ('Varnika', 'F', '7919490007', '[email protected]', 'Mumbai'); INSERT INTO interns(name, gender, mobile, email, city) VALUES ('Abhishek', 'M', '7610573879', '[email protected]', 'Bangalore'); View inserted data : SELECT * FROM interns; We are finished with creating database, creating table and inserting data into the table. Now, we have to find out the PRIMARY KEY of the created table and that PRIMARY KEY should be “id”. To find PRIMARY KEY of any table : SELECT K.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K ON K.CONSTRAINT_NAME=T.CONSTRAINT_NAME WHERE K.TABLE_NAME=‘YOUR-TABLE-NAME’ AND K.TABLE_SCHEMA=‘YOUR-DATABASE_NAME’ AND T.CONSTRAINT_TYPE=’PRIMARY KEY’ LIMIT 1; Example : SELECT K.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K ON K.CONSTRAINT_NAME=T.CONSTRAINT_NAME WHERE K.TABLE_NAME='interns' AND K.TABLE_SCHEMA='geeksforgeeks' AND T.CONSTRAINT_TYPE='PRIMARY KEY' LIMIT 1; Here, we get COLUMN_NAME as “id” i.e. PRIMARY KEY of “interns” table. Explanation : INFORMATION_SCHEMA.TABLE_CONSTRAINTS is a table which consists of information about all the tables created in any of the database till now. We require this table to validate the CONSTRAINT_TYPE. You can view information provided by the table by running below query. SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS; Also, we have INFORMATION_SCHEMA.KEY_COLUMN_USAGE table which describes which key columns have constraints. We require this table to get the COLUMN_NAME. You can view information provided by the table by running below query. SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE; So, we have joined these two tables TABLE_CONSTRAINTS (T) and KEY_COLUMN_USAGE (K) on CONSTRAINT_NAME. We have selected K.COLUMN_NAME of those records where K.TABLE_NAME = ‘interns’ and K.TABLE_SCHEMA = ‘geeksforgeeks’ and T.CONSTRAINT_TYPE = ‘PRIMARY KEY’. SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Apr, 2021" }, { "code": null, "e": 475, "s": 54, "text": "Structured Query Language or SQL, is composed of commands that enable users to create database and table structures, perform various types of data manipulation and data administration and query the database to extract useful information. We will start with creating the database “geeksforgeeks” and then we will proceed with creating a table “interns” in that database. After this we will execute our query on the table." }, { "code": null, "e": 495, "s": 475, "text": "Creating Database :" }, { "code": null, "e": 526, "s": 495, "text": "CREATE DATABASE geeksforgeeks;" }, { "code": null, "e": 558, "s": 526, "text": "To use above created database :" }, { "code": null, "e": 577, "s": 558, "text": "USE geeksforgeeks;" }, { "code": null, "e": 592, "s": 577, "text": "Create Table :" }, { "code": null, "e": 756, "s": 592, "text": "CREATE TABLE interns(\n id SERIAL PRIMARY KEY, \n name VARCHAR(30),\n gender VARCHAR(1), \n mobile BIGINT, \n email VARCHAR(35), \n city VARCHAR(25));" }, { "code": null, "e": 800, "s": 756, "text": "To see description of above created table :" }, { "code": null, "e": 814, "s": 800, "text": "DESC interns;" }, { "code": null, "e": 843, "s": 814, "text": "Insert data into the table :" }, { "code": null, "e": 1339, "s": 843, "text": "INSERT INTO interns(name, gender, mobile, email, city) VALUES ('Richa', 'F', '7999022923', '[email protected]', 'Delhi');\nINSERT INTO interns(name, gender, mobile, email, city) VALUES ('Shivam', 'M', '9999028833', '[email protected]', 'Pune');\nINSERT INTO interns(name, gender, mobile, email, city) VALUES ('Varnika', 'F', '7919490007', '[email protected]', 'Mumbai');\nINSERT INTO interns(name, gender, mobile, email, city) VALUES ('Abhishek', 'M', '7610573879', '[email protected]', 'Bangalore');" }, { "code": null, "e": 1360, "s": 1339, "text": "View inserted data :" }, { "code": null, "e": 1383, "s": 1360, "text": "SELECT * FROM interns;" }, { "code": null, "e": 1572, "s": 1383, "text": "We are finished with creating database, creating table and inserting data into the table. Now, we have to find out the PRIMARY KEY of the created table and that PRIMARY KEY should be “id”." }, { "code": null, "e": 1607, "s": 1572, "text": "To find PRIMARY KEY of any table :" }, { "code": null, "e": 1635, "s": 1607, "text": "SELECT K.COLUMN_NAME FROM " }, { "code": null, "e": 1675, "s": 1635, "text": "INFORMATION_SCHEMA.TABLE_CONSTRAINTS T " }, { "code": null, "e": 1718, "s": 1675, "text": "JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K" }, { "code": null, "e": 1759, "s": 1718, "text": "ON K.CONSTRAINT_NAME=T.CONSTRAINT_NAME " }, { "code": null, "e": 1799, "s": 1759, "text": "WHERE K.TABLE_NAME=‘YOUR-TABLE-NAME’ " }, { "code": null, "e": 1839, "s": 1799, "text": "AND K.TABLE_SCHEMA=‘YOUR-DATABASE_NAME’" }, { "code": null, "e": 1884, "s": 1839, "text": "AND T.CONSTRAINT_TYPE=’PRIMARY KEY’ LIMIT 1;" }, { "code": null, "e": 1894, "s": 1884, "text": "Example :" }, { "code": null, "e": 2156, "s": 1894, "text": "SELECT K.COLUMN_NAME FROM \nINFORMATION_SCHEMA.TABLE_CONSTRAINTS T\nJOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K\nON K.CONSTRAINT_NAME=T.CONSTRAINT_NAME \nWHERE K.TABLE_NAME='interns'\nAND K.TABLE_SCHEMA='geeksforgeeks' \nAND T.CONSTRAINT_TYPE='PRIMARY KEY' LIMIT 1;" }, { "code": null, "e": 2226, "s": 2156, "text": "Here, we get COLUMN_NAME as “id” i.e. PRIMARY KEY of “interns” table." }, { "code": null, "e": 2240, "s": 2226, "text": "Explanation :" }, { "code": null, "e": 2506, "s": 2240, "text": "INFORMATION_SCHEMA.TABLE_CONSTRAINTS is a table which consists of information about all the tables created in any of the database till now. We require this table to validate the CONSTRAINT_TYPE. You can view information provided by the table by running below query." }, { "code": null, "e": 2558, "s": 2506, "text": "SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS;" }, { "code": null, "e": 2783, "s": 2558, "text": "Also, we have INFORMATION_SCHEMA.KEY_COLUMN_USAGE table which describes which key columns have constraints. We require this table to get the COLUMN_NAME. You can view information provided by the table by running below query." }, { "code": null, "e": 2834, "s": 2783, "text": "SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE;" }, { "code": null, "e": 3092, "s": 2834, "text": "So, we have joined these two tables TABLE_CONSTRAINTS (T) and KEY_COLUMN_USAGE (K) on CONSTRAINT_NAME. We have selected K.COLUMN_NAME of those records where K.TABLE_NAME = ‘interns’ and K.TABLE_SCHEMA = ‘geeksforgeeks’ and T.CONSTRAINT_TYPE = ‘PRIMARY KEY’." }, { "code": null, "e": 3096, "s": 3092, "text": "SQL" }, { "code": null, "e": 3100, "s": 3096, "text": "SQL" } ]
PostgreSQL – Create table using Python
30 Aug, 2020 This article explores the process of creating table in The PostgreSQL database using Python. psycopg2 module sample database To create a table in the database use the following steps: First create a CREATE TABLE statement Second establish a connection to the database using the connect() function Third construct a cursor object by using the cursor() method. Now execute the above created CREATE TABLE statement using the execute function. Example: In this example we have already created a Database called school. We will be adding tables to it. To do so we created a file called create_table.py and defined a create_table() function as shown below: Python3 import psycopg2from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE student ( student_id SERIAL PRIMARY KEY, student_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE grade ( grade_id SERIAL PRIMARY KEY, grade_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE student_grade ( grade_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (grade_id) REFERENCES grade (grade_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE student_detail ( student_id INTEGER NOT NULL, grade_id INTEGER NOT NULL, PRIMARY KEY (student_id , grade_id), FOREIGN KEY (student_id) REFERENCES student (student_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (grade_id) REFERENCES grade (grade_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables() This will successfully create the tables : student grade student_grade student_detail To verify so use the below command through the client tool of the same database(ie, school): \dt Output: postgreSQL-managing-table PostgreSQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - IF Statement PostgreSQL - DROP TABLE PostgreSQL - For Loops PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Function Returning A Table Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2020" }, { "code": null, "e": 121, "s": 28, "text": "This article explores the process of creating table in The PostgreSQL database using Python." }, { "code": null, "e": 137, "s": 121, "text": "psycopg2 module" }, { "code": null, "e": 153, "s": 137, "text": "sample database" }, { "code": null, "e": 212, "s": 153, "text": "To create a table in the database use the following steps:" }, { "code": null, "e": 250, "s": 212, "text": "First create a CREATE TABLE statement" }, { "code": null, "e": 325, "s": 250, "text": "Second establish a connection to the database using the connect() function" }, { "code": null, "e": 387, "s": 325, "text": "Third construct a cursor object by using the cursor() method." }, { "code": null, "e": 468, "s": 387, "text": "Now execute the above created CREATE TABLE statement using the execute function." }, { "code": null, "e": 477, "s": 468, "text": "Example:" }, { "code": null, "e": 679, "s": 477, "text": "In this example we have already created a Database called school. We will be adding tables to it. To do so we created a file called create_table.py and defined a create_table() function as shown below:" }, { "code": null, "e": 687, "s": 679, "text": "Python3" }, { "code": "import psycopg2from config import config def create_tables(): \"\"\" create tables in the PostgreSQL database\"\"\" commands = ( \"\"\" CREATE TABLE student ( student_id SERIAL PRIMARY KEY, student_name VARCHAR(255) NOT NULL ) \"\"\", \"\"\" CREATE TABLE grade ( grade_id SERIAL PRIMARY KEY, grade_name VARCHAR(255) NOT NULL ) \"\"\", \"\"\" CREATE TABLE student_grade ( grade_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (grade_id) REFERENCES grade (grade_id) ON UPDATE CASCADE ON DELETE CASCADE ) \"\"\", \"\"\" CREATE TABLE student_detail ( student_id INTEGER NOT NULL, grade_id INTEGER NOT NULL, PRIMARY KEY (student_id , grade_id), FOREIGN KEY (student_id) REFERENCES student (student_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (grade_id) REFERENCES grade (grade_id) ON UPDATE CASCADE ON DELETE CASCADE ) \"\"\") conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()", "e": 2573, "s": 687, "text": null }, { "code": null, "e": 2617, "s": 2573, "text": "This will successfully create the tables : " }, { "code": null, "e": 2625, "s": 2617, "text": "student" }, { "code": null, "e": 2631, "s": 2625, "text": "grade" }, { "code": null, "e": 2645, "s": 2631, "text": "student_grade" }, { "code": null, "e": 2660, "s": 2645, "text": "student_detail" }, { "code": null, "e": 2753, "s": 2660, "text": "To verify so use the below command through the client tool of the same database(ie, school):" }, { "code": null, "e": 2758, "s": 2753, "text": "\\dt\n" }, { "code": null, "e": 2766, "s": 2758, "text": "Output:" }, { "code": null, "e": 2792, "s": 2766, "text": "postgreSQL-managing-table" }, { "code": null, "e": 2803, "s": 2792, "text": "PostgreSQL" }, { "code": null, "e": 2810, "s": 2803, "text": "Python" }, { "code": null, "e": 2908, "s": 2810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2934, "s": 2908, "text": "PostgreSQL - IF Statement" }, { "code": null, "e": 2958, "s": 2934, "text": "PostgreSQL - DROP TABLE" }, { "code": null, "e": 2981, "s": 2958, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 3019, "s": 2981, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 3059, "s": 3019, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 3087, "s": 3059, "text": "Read JSON file using Python" }, { "code": null, "e": 3137, "s": 3087, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3159, "s": 3137, "text": "Python map() function" }, { "code": null, "e": 3177, "s": 3159, "text": "Python Dictionary" } ]
What is the difference between getter/setter methods and constructor in Java?
A constructor in Java is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have the same name as their class and, have no return type. If you do not provide a constructor the compiler defines one on your behalf, which initializes the instance variables with default values. You can also accept parameters through constructors and initialize the instance variables of a class using the given values, these are known as parameterized constructors. The following Java program has a class named student which initializes its instance variables name and age using both default and parameterized constructors. Live Demo import java.util.Scanner; class Student { private String name; private int age; Student(){ this.name = "Rama"; this.age = 29; } Student(String name, int age){ this.name = name; this.age = age; } public void display() { System.out.println("name: "+this.name); System.out.println("age: "+this.age); } } public class AccessData{ public static void main(String args[]) { //Reading values from user Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); Student obj1 = new Student(name, age); obj1.display(); Student obj2 = new Student(); obj2.display(); } } Enter the name of the student: Krishna Enter the age of the student: 20 name: Krishna age: 20 name: Rama age: 29 While defining a POJO/Bean object (or, encapsulating variables of a class) we generally, Declare all the variables of the as private. Declare all the variables of the as private. Provide public methods to modify and view their values (since you cannot access them directly). Provide public methods to modify and view their values (since you cannot access them directly). The method that is used to set/modify the value of a private instance variable of a class is known as a setter method and, the method that is used to retrieve the value of a private instance variable is known as a getter method. In the following Java program, the Student (POJO) class has two variables name and age. We are encapsulating this class by making them private and providing setter and getter methods. If you want to access these variables you cannot access them directly, you can just use the provided setter and getter methods to read and write their values. The variables which you haven’t provided these methods will be completely hidden from the outside classes. Live Demo import java.util.Scanner; class Student { private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("name: "+getName()); System.out.println("age: "+getAge()); } } public class AccessData{ public static void main(String args[]) { //Reading values from user Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); //Calling the setter and getter methods Student obj = new Student(); obj.setName(name); obj.setAge(age); obj.display(); } } Enter the name of the student: Krishna Enter the age of the student: 20 name: Krishna age: 20 As you observe, the main difference between constructors and setter/getter methods is − The constructors are used to initialize the instance variable of a class or, create objects. The constructors are used to initialize the instance variable of a class or, create objects. The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class. The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class.
[ { "code": null, "e": 1440, "s": 1187, "text": "A constructor in Java is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have the same name as their class and, have no return type." }, { "code": null, "e": 1579, "s": 1440, "text": "If you do not provide a constructor the compiler defines one on your behalf, which initializes the instance variables with default values." }, { "code": null, "e": 1751, "s": 1579, "text": "You can also accept parameters through constructors and initialize the instance variables of a class using the given values, these are known as parameterized constructors." }, { "code": null, "e": 1909, "s": 1751, "text": "The following Java program has a class named student which initializes its instance variables name and age using both default and parameterized constructors." }, { "code": null, "e": 1920, "s": 1909, "text": " Live Demo" }, { "code": null, "e": 2744, "s": 1920, "text": "import java.util.Scanner;\nclass Student {\n private String name;\n private int age;\n Student(){\n this.name = \"Rama\";\n this.age = 29;\n }\n Student(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void display() {\n System.out.println(\"name: \"+this.name);\n System.out.println(\"age: \"+this.age);\n }\n}\npublic class AccessData{\n public static void main(String args[]) {\n //Reading values from user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the name of the student: \");\n String name = sc.nextLine();\n System.out.println(\"Enter the age of the student: \");\n int age = sc.nextInt();\n Student obj1 = new Student(name, age);\n obj1.display();\n Student obj2 = new Student();\n obj2.display();\n }\n}" }, { "code": null, "e": 2857, "s": 2744, "text": "Enter the name of the student:\nKrishna\nEnter the age of the student:\n20\nname: Krishna\nage: 20\nname: Rama\nage: 29" }, { "code": null, "e": 2946, "s": 2857, "text": "While defining a POJO/Bean object (or, encapsulating variables of a class) we generally," }, { "code": null, "e": 2991, "s": 2946, "text": "Declare all the variables of the as private." }, { "code": null, "e": 3036, "s": 2991, "text": "Declare all the variables of the as private." }, { "code": null, "e": 3132, "s": 3036, "text": "Provide public methods to modify and view their values (since you cannot access them directly)." }, { "code": null, "e": 3228, "s": 3132, "text": "Provide public methods to modify and view their values (since you cannot access them directly)." }, { "code": null, "e": 3457, "s": 3228, "text": "The method that is used to set/modify the value of a private instance variable of a class is known as a setter method and, the method that is used to retrieve the value of a private instance variable is known as a getter method." }, { "code": null, "e": 3641, "s": 3457, "text": "In the following Java program, the Student (POJO) class has two variables name and age. We are encapsulating this class by making them private and providing setter and getter methods." }, { "code": null, "e": 3907, "s": 3641, "text": "If you want to access these variables you cannot access them directly, you can just use the provided setter and getter methods to read and write their values. The variables which you haven’t provided these methods will be completely hidden from the outside classes." }, { "code": null, "e": 3918, "s": 3907, "text": " Live Demo" }, { "code": null, "e": 4817, "s": 3918, "text": "import java.util.Scanner;\nclass Student {\n private String name;\n private int age;\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void display() {\n System.out.println(\"name: \"+getName());\n System.out.println(\"age: \"+getAge());\n }\n}\npublic class AccessData{\n public static void main(String args[]) {\n //Reading values from user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the name of the student: \");\n String name = sc.nextLine();\n System.out.println(\"Enter the age of the student: \");\n int age = sc.nextInt();\n //Calling the setter and getter methods\n Student obj = new Student();\n obj.setName(name);\n obj.setAge(age);\n obj.display();\n }\n}" }, { "code": null, "e": 4911, "s": 4817, "text": "Enter the name of the student:\nKrishna\nEnter the age of the student:\n20\nname: Krishna\nage: 20" }, { "code": null, "e": 4999, "s": 4911, "text": "As you observe, the main difference between constructors and setter/getter methods is −" }, { "code": null, "e": 5092, "s": 4999, "text": "The constructors are used to initialize the instance variable of a class or, create objects." }, { "code": null, "e": 5185, "s": 5092, "text": "The constructors are used to initialize the instance variable of a class or, create objects." }, { "code": null, "e": 5295, "s": 5185, "text": "The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class." }, { "code": null, "e": 5405, "s": 5295, "text": "The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class." } ]
How to align text content into center using JavaScript ?
05 Nov, 2021 In this article, we will align the text content into center by using JavaScript. TWe use HTML DOM style textAlign property to set the alignment of text. Syntax: object.style.textAlign = "center" The above syntax set the text alignment into center dynamically. Example: HTML <!DOCTYPE html><html> <head> <title> How to align text content into center using JavaScript ? </title></head> <body> <h1 style="color: green;">GeeksforGeeks</h1> <h3> How to align text content into center using JavaScript ? </h3> <p id="content"> GeeksforGeeks: A computer science portal for geeks </p> <button onclick="myFunction();"> Set Alignment </button> <script type="text/javascript"> function myFunction() { let txt = document.getElementById("content"); txt.style.textAlign = "center"; } </script></body> </html> Output: Before Button Click: After Button Click: Supported Browsers: Google Chrome Internet Explorer Mozilla Firefox Opera Safari ysachin2314 chhabradhanvi CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Nov, 2021" }, { "code": null, "e": 181, "s": 28, "text": "In this article, we will align the text content into center by using JavaScript. TWe use HTML DOM style textAlign property to set the alignment of text." }, { "code": null, "e": 189, "s": 181, "text": "Syntax:" }, { "code": null, "e": 223, "s": 189, "text": "object.style.textAlign = \"center\"" }, { "code": null, "e": 288, "s": 223, "text": "The above syntax set the text alignment into center dynamically." }, { "code": null, "e": 297, "s": 288, "text": "Example:" }, { "code": null, "e": 302, "s": 297, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to align text content into center using JavaScript ? </title></head> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h3> How to align text content into center using JavaScript ? </h3> <p id=\"content\"> GeeksforGeeks: A computer science portal for geeks </p> <button onclick=\"myFunction();\"> Set Alignment </button> <script type=\"text/javascript\"> function myFunction() { let txt = document.getElementById(\"content\"); txt.style.textAlign = \"center\"; } </script></body> </html>", "e": 949, "s": 302, "text": null }, { "code": null, "e": 957, "s": 949, "text": "Output:" }, { "code": null, "e": 978, "s": 957, "text": "Before Button Click:" }, { "code": null, "e": 998, "s": 978, "text": "After Button Click:" }, { "code": null, "e": 1019, "s": 998, "text": "Supported Browsers: " }, { "code": null, "e": 1033, "s": 1019, "text": "Google Chrome" }, { "code": null, "e": 1051, "s": 1033, "text": "Internet Explorer" }, { "code": null, "e": 1067, "s": 1051, "text": "Mozilla Firefox" }, { "code": null, "e": 1073, "s": 1067, "text": "Opera" }, { "code": null, "e": 1080, "s": 1073, "text": "Safari" }, { "code": null, "e": 1092, "s": 1080, "text": "ysachin2314" }, { "code": null, "e": 1106, "s": 1092, "text": "chhabradhanvi" }, { "code": null, "e": 1115, "s": 1106, "text": "CSS-Misc" }, { "code": null, "e": 1125, "s": 1115, "text": "HTML-Misc" }, { "code": null, "e": 1141, "s": 1125, "text": "JavaScript-Misc" }, { "code": null, "e": 1145, "s": 1141, "text": "CSS" }, { "code": null, "e": 1150, "s": 1145, "text": "HTML" }, { "code": null, "e": 1161, "s": 1150, "text": "JavaScript" }, { "code": null, "e": 1178, "s": 1161, "text": "Web Technologies" }, { "code": null, "e": 1183, "s": 1178, "text": "HTML" } ]
Difference between link and anchor Tags
22 Sep, 2021 The HTML language is the most basic component of web development. If you are a beginner to web development, learning about HTML then you must have discovered the “link” and “a” tag. These two entities <link> and <a>, are used for some kind of linking so if you are confused between them or want to learn about the actual difference between them, Then you are at the right place. In this article, we are going to differentiate them, followed by the actual definition with examples of both. <link> Tag: This tag is used to establish a connection/relationship between the current document and some external resources that are associated with the webpage. The resource could be a CSS file, an icon used in the site, a manifest, etc. It has certain attributes some of mostly used are the following. Attribute_Name=”Value” Example Description Example 1: Creating a link to some external CSS stylesheet in our document. The id given to the h2 tag contains only a style color: green inside that external CSS file. Javascript <!DOCTYPE html><html> <head> <title>Link Tag</title> <link rel="stylesheet" href="./externalResource.css" /></head> <body> <h2 id="hello"> Hello, GeeksforGeeks Learner </h2> <p> The above text is having color green instead of default black, because a file which contains some css code is associated/linked with this document. </p> </body> </html> Output: Example 2: Adding some external favicon for the website. Javascript <!DOCTYPE html><html> <head> <title>Link Tag</title> // Add png image source here <link rel="icon" href="./gfgIcon.png" /></head> <body> <p> The Favicon being displayed along with text in title is because a png file is associated /linked with this document </p> </body> </html> Output: <a> Tag: This anchor tag establishes a hyperlink to an external or internal document of HTML, an address like email or telephone, and some kind of external URL address. Some of the commonly used attributes are:- Attribute_Name=”Value” Example Description Note: The rel and type attribute described in the link tag can also be used with the anchor tag. Example 1: We are going to sketch a basic clone of the footer of geeksforgeeks.org to illustrate use cases of the anchor tag, You must have seen this many times so for a practical example it may be a better option. Explanation:- The first anchor tag has a reference to the official website of GFG, and there is another attribute target, that is set to a value _blank means this hyperlink will be open in another tab. The next anchor tag is delivering a hyperlink to the mail of GFG. its syntax is “mailto: any_mail_id_will_appear_here“, when the user clicks on this tag the browser will be going to open some default applications to send mail. Later there is a link to the YouTube channel of GFG, notice the difference between the first one and this one, It has no target attribute so by default it will open in the same tab. At the end, there is a hyperlink to make a telephone call it accepts a number with country code after the colon i.e. “tel: any_telephone_number, and similar to a mail hyperlink here also the browser will decide which application to use for calling purposes. HTML <!DOCTYPE html><html> <body> <h2>Anchor Tags</h2> <a href="https://www.geeksforgeeks.org" target="_blank"> GeeksforGeeks </a><br> <div> <span> 5th Floor, A-118,<br>Sector-136, Noida, Uttar Pradesh - 201305 </span> </div> <a href="mailto:[email protected]"> [email protected] </a><br> <a href="https://www.youtube.com/geeksforgeeksvideos/"> Video Tutorials </a><br> <a href="tel:00000000">Call Us</a></body> </html> Output:- Difference between <link> tag and <a> tag: <link> Tag <a> Tag Blogathon-2021 HTML-Questions HTML-Tags Picked Blogathon Difference Between HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Sep, 2021" }, { "code": null, "e": 543, "s": 54, "text": "The HTML language is the most basic component of web development. If you are a beginner to web development, learning about HTML then you must have discovered the “link” and “a” tag. These two entities <link> and <a>, are used for some kind of linking so if you are confused between them or want to learn about the actual difference between them, Then you are at the right place. In this article, we are going to differentiate them, followed by the actual definition with examples of both." }, { "code": null, "e": 783, "s": 543, "text": "<link> Tag: This tag is used to establish a connection/relationship between the current document and some external resources that are associated with the webpage. The resource could be a CSS file, an icon used in the site, a manifest, etc." }, { "code": null, "e": 850, "s": 783, "text": "It has certain attributes some of mostly used are the following. " }, { "code": null, "e": 875, "s": 852, "text": "Attribute_Name=”Value”" }, { "code": null, "e": 883, "s": 875, "text": "Example" }, { "code": null, "e": 895, "s": 883, "text": "Description" }, { "code": null, "e": 1064, "s": 895, "text": "Example 1: Creating a link to some external CSS stylesheet in our document. The id given to the h2 tag contains only a style color: green inside that external CSS file." }, { "code": null, "e": 1075, "s": 1064, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <title>Link Tag</title> <link rel=\"stylesheet\" href=\"./externalResource.css\" /></head> <body> <h2 id=\"hello\"> Hello, GeeksforGeeks Learner </h2> <p> The above text is having color green instead of default black, because a file which contains some css code is associated/linked with this document. </p> </body> </html>", "e": 1501, "s": 1075, "text": null }, { "code": null, "e": 1509, "s": 1501, "text": "Output:" }, { "code": null, "e": 1568, "s": 1511, "text": "Example 2: Adding some external favicon for the website." }, { "code": null, "e": 1579, "s": 1568, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <title>Link Tag</title> // Add png image source here <link rel=\"icon\" href=\"./gfgIcon.png\" /></head> <body> <p> The Favicon being displayed along with text in title is because a png file is associated /linked with this document </p> </body> </html>", "e": 1914, "s": 1579, "text": null }, { "code": null, "e": 1922, "s": 1914, "text": "Output:" }, { "code": null, "e": 2092, "s": 1922, "text": "<a> Tag: This anchor tag establishes a hyperlink to an external or internal document of HTML, an address like email or telephone, and some kind of external URL address. " }, { "code": null, "e": 2135, "s": 2092, "text": "Some of the commonly used attributes are:-" }, { "code": null, "e": 2158, "s": 2135, "text": "Attribute_Name=”Value”" }, { "code": null, "e": 2166, "s": 2158, "text": "Example" }, { "code": null, "e": 2178, "s": 2166, "text": "Description" }, { "code": null, "e": 2275, "s": 2178, "text": "Note: The rel and type attribute described in the link tag can also be used with the anchor tag." }, { "code": null, "e": 2490, "s": 2275, "text": "Example 1: We are going to sketch a basic clone of the footer of geeksforgeeks.org to illustrate use cases of the anchor tag, You must have seen this many times so for a practical example it may be a better option." }, { "code": null, "e": 2505, "s": 2490, "text": "Explanation:- " }, { "code": null, "e": 2693, "s": 2505, "text": "The first anchor tag has a reference to the official website of GFG, and there is another attribute target, that is set to a value _blank means this hyperlink will be open in another tab." }, { "code": null, "e": 2920, "s": 2693, "text": "The next anchor tag is delivering a hyperlink to the mail of GFG. its syntax is “mailto: any_mail_id_will_appear_here“, when the user clicks on this tag the browser will be going to open some default applications to send mail." }, { "code": null, "e": 3102, "s": 2920, "text": "Later there is a link to the YouTube channel of GFG, notice the difference between the first one and this one, It has no target attribute so by default it will open in the same tab." }, { "code": null, "e": 3360, "s": 3102, "text": "At the end, there is a hyperlink to make a telephone call it accepts a number with country code after the colon i.e. “tel: any_telephone_number, and similar to a mail hyperlink here also the browser will decide which application to use for calling purposes." }, { "code": null, "e": 3365, "s": 3360, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>Anchor Tags</h2> <a href=\"https://www.geeksforgeeks.org\" target=\"_blank\"> GeeksforGeeks </a><br> <div> <span> 5th Floor, A-118,<br>Sector-136, Noida, Uttar Pradesh - 201305 </span> </div> <a href=\"mailto:[email protected]\"> [email protected] </a><br> <a href=\"https://www.youtube.com/geeksforgeeksvideos/\"> Video Tutorials </a><br> <a href=\"tel:00000000\">Call Us</a></body> </html>", "e": 3919, "s": 3365, "text": null }, { "code": null, "e": 3929, "s": 3919, "text": "Output:- " }, { "code": null, "e": 3972, "s": 3929, "text": "Difference between <link> tag and <a> tag:" }, { "code": null, "e": 3983, "s": 3972, "text": "<link> Tag" }, { "code": null, "e": 3991, "s": 3983, "text": "<a> Tag" }, { "code": null, "e": 4006, "s": 3991, "text": "Blogathon-2021" }, { "code": null, "e": 4021, "s": 4006, "text": "HTML-Questions" }, { "code": null, "e": 4031, "s": 4021, "text": "HTML-Tags" }, { "code": null, "e": 4038, "s": 4031, "text": "Picked" }, { "code": null, "e": 4048, "s": 4038, "text": "Blogathon" }, { "code": null, "e": 4067, "s": 4048, "text": "Difference Between" }, { "code": null, "e": 4072, "s": 4067, "text": "HTML" }, { "code": null, "e": 4089, "s": 4072, "text": "Web Technologies" }, { "code": null, "e": 4094, "s": 4089, "text": "HTML" }, { "code": null, "e": 4192, "s": 4094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4233, "s": 4192, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 4271, "s": 4233, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 4315, "s": 4271, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 4375, "s": 4315, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 4442, "s": 4375, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 4482, "s": 4442, "text": "Class method vs Static method in Python" }, { "code": null, "e": 4513, "s": 4482, "text": "Difference between BFS and DFS" }, { "code": null, "e": 4574, "s": 4513, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4642, "s": 4574, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
EnumMap class in Java
06 Dec, 2021 EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. It belongs to java.util package. A few important features of EnumMap are as follows: EnumMap class is a member of the Java Collections Framework & is not synchronized. EnumMap is an ordered collection and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constants are declared inside enum type ) It’s a high-performance map implementation, much faster than HashMap. All keys of each EnumMap instance must be keys of a single enum type. EnumMap doesn’t allow null key and throws NullPointerException when we attempt to insert the null key. Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress. EnumMap is internally represented as arrays. This representation is extremely compact and efficient. Syntax: Declaration public class EnumMap<K extends Enum<K>,​V> extends AbstractMap<K,​V> implements Serializable, Cloneable Parameters: Key object type Value object type K must extend Enum, which enforces the requirement that the keys must be of the specified enum type. EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType.EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMapEnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter. EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType. EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMap EnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter. Example Java // Java Program to illustrate Working of EnumMap class// and its functions // Importing EnumMap classimport java.util.EnumMap; // Main classpublic class EnumMapExample { // Enum public enum GFG { CODE, CONTRIBUTE, QUIZ, MCQ; } // Main driver method public static void main(String args[]) { // Java EnumMap // Creating an empty EnumMap with key // as enum type state EnumMap<GFG, String> gfgMap = new EnumMap<GFG, String>(GFG.class); // Putting values inside EnumMap in Java // Inserting Enum keys different from // their natural order gfgMap.put(GFG.CODE, "Start Coding with gfg"); gfgMap.put(GFG.CONTRIBUTE, "Contribute for others"); gfgMap.put(GFG.QUIZ, "Practice Quizes"); gfgMap.put(GFG.MCQ, "Test Speed with Mcqs"); // Printing size of EnumMap System.out.println("Size of EnumMap in java: " + gfgMap.size()); // Printing Java EnumMap // Print EnumMap in natural order // of enum keys (order on which they are declared) System.out.println("EnumMap: " + gfgMap); // Retrieving value from EnumMap System.out.println("Key : " + GFG.CODE + " Value: " + gfgMap.get(GFG.CODE)); // Checking if EnumMap contains a particular key System.out.println( "Does gfgMap has " + GFG.CONTRIBUTE + ": " + gfgMap.containsKey(GFG.CONTRIBUTE)); // Checking if EnumMap contains a particular value System.out.println( "Does gfgMap has :" + GFG.QUIZ + " : " + gfgMap.containsValue("Practice Quizes")); System.out.println("Does gfgMap has :" + GFG.QUIZ + " : " + gfgMap.containsValue(null)); }} Size of EnumMap in java: 4 EnumMap: {CODE=Start Coding with gfg, CONTRIBUTE=Contribute for others, QUIZ=Practice Quizes, MCQ=Test Speed with Mcqs} Key : CODE Value: Start Coding with gfg Does gfgMap has CONTRIBUTE: true Does gfgMap has :QUIZ : true Does gfgMap has :QUIZ : false Operation 1: Adding Elements In order to add elements to the EnumMap, we can use put() or putAll() method as shown below. Java // Java Program to Add Elements to the EnumMap // Importing EnumMap classimport java.util.EnumMap; // Main class// AddingElementsToEnumMapclass GFG { enum Color { RED, GREEN, BLUE, WHITE } public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors1 = new EnumMap<>(Color.class); // Insert elements in Map // using put() method colors1.put(Color.RED, 1); colors1.put(Color.GREEN, 2); // Printing mappings to the console System.out.println("EnumMap colors1: " + colors1); // Creating an EnumMap of the Color Enum EnumMap<Color, Integer> colors2 = new EnumMap<>(Color.class); // Adding elements using the putAll() method colors2.putAll(colors1); colors2.put(Color.BLUE, 3); // Printing mappings to the console System.out.println("EnumMap colors2: " + colors2); }} EnumMap colors1: {RED=1, GREEN=2} EnumMap colors2: {RED=1, GREEN=2, BLUE=3} Operation 2: Accessing the Elements We can access the elements of EnumMap using entrySet(), keySet(), values(), get(). The example below explains these methods. Java // Java Program to Access the Elements of EnumMap // Importing required classesimport java.util.EnumMap; // Main class// AccessElementsOfEnumMapclass GFG { // Enum enum Color { RED, GREEN, BLUE, WHITE } // Main driver method public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors = new EnumMap<>(Color.class); // Inserting elements using put() method colors.put(Color.RED, 1); colors.put(Color.GREEN, 2); colors.put(Color.BLUE, 3); colors.put(Color.WHITE, 4); System.out.println("EnumMap colors : " + colors); // Using the entrySet() method System.out.println("Key/Value mappings: " + colors.entrySet()); // Using the keySet() method System.out.println("Keys: " + colors.keySet()); // Using the values() method System.out.println("Values: " + colors.values()); // Using the get() method System.out.println("Value of RED : " + colors.get(Color.RED)); }} EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4} Key/Value mappings: [RED=1, GREEN=2, BLUE=3, WHITE=4] Keys: [RED, GREEN, BLUE, WHITE] Values: [1, 2, 3, 4] Value of RED : 1 Operation 3: Removing elements In order to remove the elements, EnumMap provides two variations of the remove() method. Example Java // Java program to Remove Elements of EnumMap // Importing EnumMap classimport java.util.EnumMap; // Main classclass GFG { // Enum enum Color { // Custom elements RED, GREEN, BLUE, WHITE } // Main driver method public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors = new EnumMap<>(Color.class); // Inserting elements in the Map // using put() method colors.put(Color.RED, 1); colors.put(Color.GREEN, 2); colors.put(Color.BLUE, 3); colors.put(Color.WHITE, 4); // Printing colors in the EnumMap System.out.println("EnumMap colors : " + colors); // Removing a mapping // using remove() Method int value = colors.remove(Color.WHITE); // Displaying the removed value System.out.println("Removed Value: " + value); // Removing specific color and storing boolean // if removed or not boolean result = colors.remove(Color.RED, 1); // Printing the boolean result whether removed or // not System.out.println("Is the entry {RED=1} removed? " + result); // Printing the updated Map to the console System.out.println("Updated EnumMap: " + colors); }} EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4} Removed Value: 4 Is the entry {RED=1} removed? true Updated EnumMap: {GREEN=2, BLUE=3} Operation 4: Replacing elements Map interface provides three variations of the replace() method to change the mappings of EnumMap. Example Java // Java Program to Replace Elements of EnumMap // Importing required classesimport java.util.EnumMap; // Main classclass GFG { // Enum enum Color { RED, GREEN, BLUE, WHITE } // Main driver method public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors = new EnumMap<>(Color.class); // Inserting elements to Map // using put() method colors.put(Color.RED, 1); colors.put(Color.GREEN, 2); colors.put(Color.BLUE, 3); colors.put(Color.WHITE, 4); // Printing all elements inside above Map System.out.println("EnumMap colors " + colors); // Replacing certain elements depicting colors // using the replace() method colors.replace(Color.RED, 11); colors.replace(Color.GREEN, 2, 12); // Printing the updated elements (colors) System.out.println("EnumMap using replace(): " + colors); // Replacing all colors using the replaceAll() // method colors.replaceAll((key, oldValue) -> oldValue + 3); // Printing the elements of above Map System.out.println("EnumMap using replaceAll(): " + colors); }} EnumMap colors {RED=1, GREEN=2, BLUE=3, WHITE=4} EnumMap using replace(): {RED=11, GREEN=12, BLUE=3, WHITE=4} EnumMap using replaceAll(): {RED=14, GREEN=15, BLUE=6, WHITE=7} The implementation of an EnumMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the synchronizedMap() method of the Collections class. This is best done at the creation time, to prevent accidental unsynchronized access. Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...)); K – Type of the key object V – Type of the value object Method Action Performed Method Description Method Descriptionenter Property EnumMap EnumSet This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on GeeksforGeek’s main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Chinmoy Lenka Ganeshchowdharysadanala prasannachalluri solankimayank Java-Collections Java-EnumMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2021" }, { "code": null, "e": 287, "s": 52, "text": "EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. It belongs to java.util package. A few important features of EnumMap are as follows: " }, { "code": null, "e": 370, "s": 287, "text": "EnumMap class is a member of the Java Collections Framework & is not synchronized." }, { "code": null, "e": 560, "s": 370, "text": "EnumMap is an ordered collection and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constants are declared inside enum type )" }, { "code": null, "e": 630, "s": 560, "text": "It’s a high-performance map implementation, much faster than HashMap." }, { "code": null, "e": 700, "s": 630, "text": "All keys of each EnumMap instance must be keys of a single enum type." }, { "code": null, "e": 803, "s": 700, "text": "EnumMap doesn’t allow null key and throws NullPointerException when we attempt to insert the null key." }, { "code": null, "e": 1043, "s": 803, "text": "Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress." }, { "code": null, "e": 1144, "s": 1043, "text": "EnumMap is internally represented as arrays. This representation is extremely compact and efficient." }, { "code": null, "e": 1164, "s": 1144, "text": "Syntax: Declaration" }, { "code": null, "e": 1268, "s": 1164, "text": "public class EnumMap<K extends Enum<K>,​V> extends AbstractMap<K,​V> implements Serializable, Cloneable" }, { "code": null, "e": 1280, "s": 1268, "text": "Parameters:" }, { "code": null, "e": 1296, "s": 1280, "text": "Key object type" }, { "code": null, "e": 1314, "s": 1296, "text": "Value object type" }, { "code": null, "e": 1416, "s": 1314, "text": "K must extend Enum, which enforces the requirement that the keys must be of the specified enum type. " }, { "code": null, "e": 1807, "s": 1416, "text": "EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType.EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMapEnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter." }, { "code": null, "e": 1910, "s": 1807, "text": "EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType." }, { "code": null, "e": 2077, "s": 1910, "text": "EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMap" }, { "code": null, "e": 2200, "s": 2077, "text": "EnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter." }, { "code": null, "e": 2210, "s": 2200, "text": "Example " }, { "code": null, "e": 2215, "s": 2210, "text": "Java" }, { "code": "// Java Program to illustrate Working of EnumMap class// and its functions // Importing EnumMap classimport java.util.EnumMap; // Main classpublic class EnumMapExample { // Enum public enum GFG { CODE, CONTRIBUTE, QUIZ, MCQ; } // Main driver method public static void main(String args[]) { // Java EnumMap // Creating an empty EnumMap with key // as enum type state EnumMap<GFG, String> gfgMap = new EnumMap<GFG, String>(GFG.class); // Putting values inside EnumMap in Java // Inserting Enum keys different from // their natural order gfgMap.put(GFG.CODE, \"Start Coding with gfg\"); gfgMap.put(GFG.CONTRIBUTE, \"Contribute for others\"); gfgMap.put(GFG.QUIZ, \"Practice Quizes\"); gfgMap.put(GFG.MCQ, \"Test Speed with Mcqs\"); // Printing size of EnumMap System.out.println(\"Size of EnumMap in java: \" + gfgMap.size()); // Printing Java EnumMap // Print EnumMap in natural order // of enum keys (order on which they are declared) System.out.println(\"EnumMap: \" + gfgMap); // Retrieving value from EnumMap System.out.println(\"Key : \" + GFG.CODE + \" Value: \" + gfgMap.get(GFG.CODE)); // Checking if EnumMap contains a particular key System.out.println( \"Does gfgMap has \" + GFG.CONTRIBUTE + \": \" + gfgMap.containsKey(GFG.CONTRIBUTE)); // Checking if EnumMap contains a particular value System.out.println( \"Does gfgMap has :\" + GFG.QUIZ + \" : \" + gfgMap.containsValue(\"Practice Quizes\")); System.out.println(\"Does gfgMap has :\" + GFG.QUIZ + \" : \" + gfgMap.containsValue(null)); }}", "e": 4073, "s": 2215, "text": null }, { "code": null, "e": 4352, "s": 4073, "text": "Size of EnumMap in java: 4\nEnumMap: {CODE=Start Coding with gfg, CONTRIBUTE=Contribute for others, QUIZ=Practice Quizes, MCQ=Test Speed with Mcqs}\nKey : CODE Value: Start Coding with gfg\nDoes gfgMap has CONTRIBUTE: true\nDoes gfgMap has :QUIZ : true\nDoes gfgMap has :QUIZ : false" }, { "code": null, "e": 4381, "s": 4352, "text": "Operation 1: Adding Elements" }, { "code": null, "e": 4474, "s": 4381, "text": "In order to add elements to the EnumMap, we can use put() or putAll() method as shown below." }, { "code": null, "e": 4479, "s": 4474, "text": "Java" }, { "code": "// Java Program to Add Elements to the EnumMap // Importing EnumMap classimport java.util.EnumMap; // Main class// AddingElementsToEnumMapclass GFG { enum Color { RED, GREEN, BLUE, WHITE } public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors1 = new EnumMap<>(Color.class); // Insert elements in Map // using put() method colors1.put(Color.RED, 1); colors1.put(Color.GREEN, 2); // Printing mappings to the console System.out.println(\"EnumMap colors1: \" + colors1); // Creating an EnumMap of the Color Enum EnumMap<Color, Integer> colors2 = new EnumMap<>(Color.class); // Adding elements using the putAll() method colors2.putAll(colors1); colors2.put(Color.BLUE, 3); // Printing mappings to the console System.out.println(\"EnumMap colors2: \" + colors2); }}", "e": 5440, "s": 4479, "text": null }, { "code": null, "e": 5516, "s": 5440, "text": "EnumMap colors1: {RED=1, GREEN=2}\nEnumMap colors2: {RED=1, GREEN=2, BLUE=3}" }, { "code": null, "e": 5553, "s": 5516, "text": " Operation 2: Accessing the Elements" }, { "code": null, "e": 5678, "s": 5553, "text": "We can access the elements of EnumMap using entrySet(), keySet(), values(), get(). The example below explains these methods." }, { "code": null, "e": 5683, "s": 5678, "text": "Java" }, { "code": "// Java Program to Access the Elements of EnumMap // Importing required classesimport java.util.EnumMap; // Main class// AccessElementsOfEnumMapclass GFG { // Enum enum Color { RED, GREEN, BLUE, WHITE } // Main driver method public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors = new EnumMap<>(Color.class); // Inserting elements using put() method colors.put(Color.RED, 1); colors.put(Color.GREEN, 2); colors.put(Color.BLUE, 3); colors.put(Color.WHITE, 4); System.out.println(\"EnumMap colors : \" + colors); // Using the entrySet() method System.out.println(\"Key/Value mappings: \" + colors.entrySet()); // Using the keySet() method System.out.println(\"Keys: \" + colors.keySet()); // Using the values() method System.out.println(\"Values: \" + colors.values()); // Using the get() method System.out.println(\"Value of RED : \" + colors.get(Color.RED)); }}", "e": 6796, "s": 5683, "text": null }, { "code": null, "e": 6971, "s": 6796, "text": "EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}\nKey/Value mappings: [RED=1, GREEN=2, BLUE=3, WHITE=4]\nKeys: [RED, GREEN, BLUE, WHITE]\nValues: [1, 2, 3, 4]\nValue of RED : 1" }, { "code": null, "e": 7002, "s": 6971, "text": "Operation 3: Removing elements" }, { "code": null, "e": 7091, "s": 7002, "text": "In order to remove the elements, EnumMap provides two variations of the remove() method." }, { "code": null, "e": 7099, "s": 7091, "text": "Example" }, { "code": null, "e": 7104, "s": 7099, "text": "Java" }, { "code": "// Java program to Remove Elements of EnumMap // Importing EnumMap classimport java.util.EnumMap; // Main classclass GFG { // Enum enum Color { // Custom elements RED, GREEN, BLUE, WHITE } // Main driver method public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors = new EnumMap<>(Color.class); // Inserting elements in the Map // using put() method colors.put(Color.RED, 1); colors.put(Color.GREEN, 2); colors.put(Color.BLUE, 3); colors.put(Color.WHITE, 4); // Printing colors in the EnumMap System.out.println(\"EnumMap colors : \" + colors); // Removing a mapping // using remove() Method int value = colors.remove(Color.WHITE); // Displaying the removed value System.out.println(\"Removed Value: \" + value); // Removing specific color and storing boolean // if removed or not boolean result = colors.remove(Color.RED, 1); // Printing the boolean result whether removed or // not System.out.println(\"Is the entry {RED=1} removed? \" + result); // Printing the updated Map to the console System.out.println(\"Updated EnumMap: \" + colors); }}", "e": 8467, "s": 7104, "text": null }, { "code": null, "e": 8605, "s": 8467, "text": "EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}\nRemoved Value: 4\nIs the entry {RED=1} removed? true\nUpdated EnumMap: {GREEN=2, BLUE=3}" }, { "code": null, "e": 8637, "s": 8605, "text": "Operation 4: Replacing elements" }, { "code": null, "e": 8736, "s": 8637, "text": "Map interface provides three variations of the replace() method to change the mappings of EnumMap." }, { "code": null, "e": 8744, "s": 8736, "text": "Example" }, { "code": null, "e": 8749, "s": 8744, "text": "Java" }, { "code": "// Java Program to Replace Elements of EnumMap // Importing required classesimport java.util.EnumMap; // Main classclass GFG { // Enum enum Color { RED, GREEN, BLUE, WHITE } // Main driver method public static void main(String[] args) { // Creating an EnumMap of the Color enum EnumMap<Color, Integer> colors = new EnumMap<>(Color.class); // Inserting elements to Map // using put() method colors.put(Color.RED, 1); colors.put(Color.GREEN, 2); colors.put(Color.BLUE, 3); colors.put(Color.WHITE, 4); // Printing all elements inside above Map System.out.println(\"EnumMap colors \" + colors); // Replacing certain elements depicting colors // using the replace() method colors.replace(Color.RED, 11); colors.replace(Color.GREEN, 2, 12); // Printing the updated elements (colors) System.out.println(\"EnumMap using replace(): \" + colors); // Replacing all colors using the replaceAll() // method colors.replaceAll((key, oldValue) -> oldValue + 3); // Printing the elements of above Map System.out.println(\"EnumMap using replaceAll(): \" + colors); }}", "e": 10062, "s": 8749, "text": null }, { "code": null, "e": 10236, "s": 10062, "text": "EnumMap colors {RED=1, GREEN=2, BLUE=3, WHITE=4}\nEnumMap using replace(): {RED=11, GREEN=12, BLUE=3, WHITE=4}\nEnumMap using replaceAll(): {RED=14, GREEN=15, BLUE=6, WHITE=7}" }, { "code": null, "e": 10625, "s": 10236, "text": "The implementation of an EnumMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the synchronizedMap() method of the Collections class. This is best done at the creation time, to prevent accidental unsynchronized access. " }, { "code": null, "e": 10705, "s": 10625, "text": " Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...));" }, { "code": null, "e": 10732, "s": 10705, "text": "K – Type of the key object" }, { "code": null, "e": 10761, "s": 10732, "text": "V – Type of the value object" }, { "code": null, "e": 10768, "s": 10761, "text": "Method" }, { "code": null, "e": 10786, "s": 10768, "text": "Action Performed " }, { "code": null, "e": 10793, "s": 10786, "text": "Method" }, { "code": null, "e": 10805, "s": 10793, "text": "Description" }, { "code": null, "e": 10812, "s": 10805, "text": "Method" }, { "code": null, "e": 10830, "s": 10812, "text": "Descriptionenter " }, { "code": null, "e": 10839, "s": 10830, "text": "Property" }, { "code": null, "e": 10847, "s": 10839, "text": "EnumMap" }, { "code": null, "e": 10855, "s": 10847, "text": "EnumSet" }, { "code": null, "e": 11276, "s": 10855, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on GeeksforGeek’s main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11290, "s": 11276, "text": "Chinmoy Lenka" }, { "code": null, "e": 11314, "s": 11290, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 11331, "s": 11314, "text": "prasannachalluri" }, { "code": null, "e": 11345, "s": 11331, "text": "solankimayank" }, { "code": null, "e": 11362, "s": 11345, "text": "Java-Collections" }, { "code": null, "e": 11375, "s": 11362, "text": "Java-EnumMap" }, { "code": null, "e": 11380, "s": 11375, "text": "Java" }, { "code": null, "e": 11385, "s": 11380, "text": "Java" }, { "code": null, "e": 11402, "s": 11385, "text": "Java-Collections" }, { "code": null, "e": 11500, "s": 11402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11515, "s": 11500, "text": "Arrays in Java" }, { "code": null, "e": 11551, "s": 11515, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 11576, "s": 11551, "text": "Reverse a string in Java" }, { "code": null, "e": 11620, "s": 11576, "text": "Split() String method in Java with examples" }, { "code": null, "e": 11671, "s": 11620, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 11693, "s": 11671, "text": "For-each loop in Java" }, { "code": null, "e": 11724, "s": 11693, "text": "How to iterate any Map in Java" }, { "code": null, "e": 11743, "s": 11724, "text": "Interfaces in Java" }, { "code": null, "e": 11773, "s": 11743, "text": "HashMap in Java with Examples" } ]
How to Create Dynamic Bottom Sheet Dialog in Android using Firebase Firestore?
24 Jan, 2021 Bottom Sheet Dialog is one of the famous Material UI Component which is used to display the data or notifications in it. We can display any type of data or any UI component in our Bottom Sheet Dialog. In this article, we will take a look at the implementation of dynamic Bottom Sheet Dialog in Android using Firebase Firestore. We will be building a simple application in which we will be displaying a simple bottom sheet dialog, and we will display the data inside that bottom sheet dynamically from Firebase. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a new Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. implementation ‘com.google.firebase:firebase-firestore:22.0.1’ implementation ‘com.squareup.picasso:picasso:2.71828’ After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. Step 3: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. XML <!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the activity_main.xml file As we are not displaying any UI inside our activity_main.xml. So we are not adding any UI component in our activity_main.xml because we are displaying the data in our custom layout file. Step 5: Creating a new layout file for our Bottom Sheet Dialog As we are displaying one image and text inside our bottom sheet dialog. So we will be building a custom layout for our Bottom Sheet Dialog. For creating a new layout file four our bottom sheet dialog box. Navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as bottom_sheet_layout and add below code to it. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/idRLBottomSheet" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white" android:backgroundTint="@color/white" android:padding="20dp"> <!--ImageView for displaying our image--> <ImageView android:id="@+id/idIVimage" android:layout_width="120dp" android:layout_height="120dp" android:layout_margin="10dp" android:padding="5dp" /> <!--Text view for displaying a heading text--> <TextView android:id="@+id/idTVtext" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_toRightOf="@id/idIVimage" android:padding="5dp" android:text="Message one" android:textColor="@color/black" android:textSize="15sp" android:textStyle="bold" /> <!--Text View for displaying description text--> <TextView android:id="@+id/idTVtextTwo" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVtext" android:layout_margin="10dp" android:layout_marginTop="10dp" android:layout_toEndOf="@id/idIVimage" android:padding="5dp" android:text="Message Two" android:textColor="@color/black" android:textSize="12sp" /> </RelativeLayout> Step 6: Adding a Bottom Sheet style to our styles.xml file Navigate to the app > res > values > themes.xml file and add the below code to it in the resources file. XML <style name="BottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog"> <item name="bottomSheetStyle">@style/BottomSheetStyle</item> </style> <style name="BottomSheetStyle" parent="Widget.Design.BottomSheet.Modal"> <item name="android:background">@android:color/transparent</item></style> Step 7: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.bottomsheet.BottomSheetDialog;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException;import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { // creating a variable for our firebase // firestore and relative layout of bottom sheet. FirebaseFirestore db; RelativeLayout bottomSheetRL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. db = FirebaseFirestore.getInstance(); bottomSheetRL = findViewById(R.id.idRLBottomSheet); // calling method to // display bottom sheet. displayBottomSheet(); } private void displayBottomSheet() { // creating a variable for our bottom sheet dialog. final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(MainActivity.this, R.style.BottomSheetDialogTheme); // passing a layout file for our bottom sheet dialog. View layout = LayoutInflater.from(MainActivity.this).inflate(R.layout.bottom_sheet_layout, bottomSheetRL); // passing our layout file to our bottom sheet dialog. bottomSheetTeachersDialog.setContentView(layout); // below line is to set our bottom sheet dialog as cancelable. bottomSheetTeachersDialog.setCancelable(false); // below line is to set our bottom sheet cancelable. bottomSheetTeachersDialog.setCanceledOnTouchOutside(true); // below line is to display our bottom sheet dialog. bottomSheetTeachersDialog.show(); // initializing our text views and image views. ImageView imageIV = layout.findViewById(R.id.idIVimage); TextView textOneTV = layout.findViewById(R.id.idTVtext); TextView textTwoTV = layout.findViewById(R.id.idTVtextTwo); // creating a variable for document reference. DocumentReference documentReference = db.collection("BottomSheetDIalog").document("Data"); // adding snapshot listener to our document reference. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { // inside the on event method. if (error != null) { // this method is called when error is not null // and we gt any error // in this cas we are displaying an error message. Toast.makeText(MainActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show(); return; } if (value != null && value.exists()) { // if the value from firestore is not null then we are // getting our data and setting that data to our text view. // after getting the value from firebase firestore // we are setting it to our text view and image view. textOneTV.setText(value.getData().get("textOne").toString()); Picasso.get().load(value.getData().get("Image").toString()).into(imageIV); textTwoTV.setText(value.getData().get("textTwo").toString()); } } }); }} Step 8: Adding the data to Firebase Firestore Console in Android After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Firebase Firestore Database in the left window. After clicking on Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we have to add data to Firebase Firestore in Android. For adding new data. Click on Start Collection Option, then specify collection Name as “BottomSheetDIalog” and after that click on Next, after that, specify Document ID Name as “Data“. Inside the Field section creates three fields as “textOne“, “textTwo“, and “Image” and pass values to it. After adding values to it and click on save and now run your application. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 357, "s": 28, "text": "Bottom Sheet Dialog is one of the famous Material UI Component which is used to display the data or notifications in it. We can display any type of data or any UI component in our Bottom Sheet Dialog. In this article, we will take a look at the implementation of dynamic Bottom Sheet Dialog in Android using Firebase Firestore. " }, { "code": null, "e": 705, "s": 357, "text": "We will be building a simple application in which we will be displaying a simple bottom sheet dialog, and we will display the data inside that bottom sheet dynamically from Firebase. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 734, "s": 705, "text": "Step 1: Create a new Project" }, { "code": null, "e": 898, "s": 734, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. " }, { "code": null, "e": 935, "s": 898, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 1140, "s": 935, "text": "After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot." }, { "code": null, "e": 1549, "s": 1140, "text": "Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. " }, { "code": null, "e": 1879, "s": 1549, "text": "After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. " }, { "code": null, "e": 1942, "s": 1879, "text": "implementation ‘com.google.firebase:firebase-firestore:22.0.1’" }, { "code": null, "e": 1996, "s": 1942, "text": "implementation ‘com.squareup.picasso:picasso:2.71828’" }, { "code": null, "e": 2233, "s": 1996, "text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. " }, { "code": null, "e": 2283, "s": 2233, "text": "Step 3: Working with the AndroidManifest.xml file" }, { "code": null, "e": 2498, "s": 2283, "text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. " }, { "code": null, "e": 2502, "s": 2498, "text": "XML" }, { "code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 2670, "s": 2502, "text": null }, { "code": null, "e": 2720, "s": 2670, "text": "Step 4: Working with the activity_main.xml file " }, { "code": null, "e": 2909, "s": 2720, "text": "As we are not displaying any UI inside our activity_main.xml. So we are not adding any UI component in our activity_main.xml because we are displaying the data in our custom layout file. " }, { "code": null, "e": 2972, "s": 2909, "text": "Step 5: Creating a new layout file for our Bottom Sheet Dialog" }, { "code": null, "e": 3333, "s": 2972, "text": "As we are displaying one image and text inside our bottom sheet dialog. So we will be building a custom layout for our Bottom Sheet Dialog. For creating a new layout file four our bottom sheet dialog box. Navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as bottom_sheet_layout and add below code to it. " }, { "code": null, "e": 3337, "s": 3333, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/idRLBottomSheet\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/white\" android:backgroundTint=\"@color/white\" android:padding=\"20dp\"> <!--ImageView for displaying our image--> <ImageView android:id=\"@+id/idIVimage\" android:layout_width=\"120dp\" android:layout_height=\"120dp\" android:layout_margin=\"10dp\" android:padding=\"5dp\" /> <!--Text view for displaying a heading text--> <TextView android:id=\"@+id/idTVtext\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_toRightOf=\"@id/idIVimage\" android:padding=\"5dp\" android:text=\"Message one\" android:textColor=\"@color/black\" android:textSize=\"15sp\" android:textStyle=\"bold\" /> <!--Text View for displaying description text--> <TextView android:id=\"@+id/idTVtextTwo\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVtext\" android:layout_margin=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_toEndOf=\"@id/idIVimage\" android:padding=\"5dp\" android:text=\"Message Two\" android:textColor=\"@color/black\" android:textSize=\"12sp\" /> </RelativeLayout>", "e": 4870, "s": 3337, "text": null }, { "code": null, "e": 4929, "s": 4870, "text": "Step 6: Adding a Bottom Sheet style to our styles.xml file" }, { "code": null, "e": 5035, "s": 4929, "text": "Navigate to the app > res > values > themes.xml file and add the below code to it in the resources file. " }, { "code": null, "e": 5039, "s": 5035, "text": "XML" }, { "code": "<style name=\"BottomSheetDialogTheme\" parent=\"Theme.Design.Light.BottomSheetDialog\"> <item name=\"bottomSheetStyle\">@style/BottomSheetStyle</item> </style> <style name=\"BottomSheetStyle\" parent=\"Widget.Design.BottomSheet.Modal\"> <item name=\"android:background\">@android:color/transparent</item></style>", "e": 5360, "s": 5039, "text": null }, { "code": null, "e": 5408, "s": 5360, "text": "Step 7: Working with the MainActivity.java file" }, { "code": null, "e": 5598, "s": 5408, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5603, "s": 5598, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.bottomsheet.BottomSheetDialog;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException;import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { // creating a variable for our firebase // firestore and relative layout of bottom sheet. FirebaseFirestore db; RelativeLayout bottomSheetRL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. db = FirebaseFirestore.getInstance(); bottomSheetRL = findViewById(R.id.idRLBottomSheet); // calling method to // display bottom sheet. displayBottomSheet(); } private void displayBottomSheet() { // creating a variable for our bottom sheet dialog. final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(MainActivity.this, R.style.BottomSheetDialogTheme); // passing a layout file for our bottom sheet dialog. View layout = LayoutInflater.from(MainActivity.this).inflate(R.layout.bottom_sheet_layout, bottomSheetRL); // passing our layout file to our bottom sheet dialog. bottomSheetTeachersDialog.setContentView(layout); // below line is to set our bottom sheet dialog as cancelable. bottomSheetTeachersDialog.setCancelable(false); // below line is to set our bottom sheet cancelable. bottomSheetTeachersDialog.setCanceledOnTouchOutside(true); // below line is to display our bottom sheet dialog. bottomSheetTeachersDialog.show(); // initializing our text views and image views. ImageView imageIV = layout.findViewById(R.id.idIVimage); TextView textOneTV = layout.findViewById(R.id.idTVtext); TextView textTwoTV = layout.findViewById(R.id.idTVtextTwo); // creating a variable for document reference. DocumentReference documentReference = db.collection(\"BottomSheetDIalog\").document(\"Data\"); // adding snapshot listener to our document reference. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { // inside the on event method. if (error != null) { // this method is called when error is not null // and we gt any error // in this cas we are displaying an error message. Toast.makeText(MainActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show(); return; } if (value != null && value.exists()) { // if the value from firestore is not null then we are // getting our data and setting that data to our text view. // after getting the value from firebase firestore // we are setting it to our text view and image view. textOneTV.setText(value.getData().get(\"textOne\").toString()); Picasso.get().load(value.getData().get(\"Image\").toString()).into(imageIV); textTwoTV.setText(value.getData().get(\"textTwo\").toString()); } } }); }}", "e": 9630, "s": 5603, "text": null }, { "code": null, "e": 9695, "s": 9630, "text": "Step 8: Adding the data to Firebase Firestore Console in Android" }, { "code": null, "e": 9889, "s": 9695, "text": "After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. " }, { "code": null, "e": 10013, "s": 9889, "text": "After clicking on this screen you will get to see the below screen with your all project inside that select your project. " }, { "code": null, "e": 10090, "s": 10013, "text": "Inside that screen click n Firebase Firestore Database in the left window. " }, { "code": null, "e": 10171, "s": 10090, "text": "After clicking on Create Database option you will get to see the below screen. " }, { "code": null, "e": 10459, "s": 10171, "text": "Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. " }, { "code": null, "e": 11012, "s": 10459, "text": "Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we have to add data to Firebase Firestore in Android. For adding new data. Click on Start Collection Option, then specify collection Name as “BottomSheetDIalog” and after that click on Next, after that, specify Document ID Name as “Data“. Inside the Field section creates three fields as “textOne“, “textTwo“, and “Image” and pass values to it. After adding values to it and click on save and now run your application. " }, { "code": null, "e": 11020, "s": 11012, "text": "android" }, { "code": null, "e": 11044, "s": 11020, "text": "Technical Scripter 2020" }, { "code": null, "e": 11052, "s": 11044, "text": "Android" }, { "code": null, "e": 11057, "s": 11052, "text": "Java" }, { "code": null, "e": 11076, "s": 11057, "text": "Technical Scripter" }, { "code": null, "e": 11081, "s": 11076, "text": "Java" }, { "code": null, "e": 11089, "s": 11081, "text": "Android" }, { "code": null, "e": 11187, "s": 11089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11256, "s": 11187, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 11288, "s": 11256, "text": "Android SDK and it's Components" }, { "code": null, "e": 11327, "s": 11288, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 11376, "s": 11327, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 11418, "s": 11376, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 11433, "s": 11418, "text": "Arrays in Java" }, { "code": null, "e": 11469, "s": 11433, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 11513, "s": 11469, "text": "Split() String method in Java with examples" }, { "code": null, "e": 11538, "s": 11513, "text": "Reverse a string in Java" } ]
HTML | DOM lastModified Property
08 Jul, 2022 The DOM lastModified property in HTML is used to return the date and time of the current document that was last modified. This property is read-only. This property returns a string which contains the date and time when the document was last modified. Syntax: document.lastModified Example: html <!DOCTYPE html><html> <head> <title> DOM lastModified Property </title></head> <body style="text-align:center"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM lastModified Property </h2> <button onclick="geeks()"> Submit </button> <p id="sudo"></p> <script> /* Function to use lastModified property */ function geeks() { var x = document.lastModified; document.getElementById("sudo").innerHTML = x; } </script></body> </html> Output: Supported Browsers: The browser supported by DOM lastModified Property are listed below: Google Chrome 1 Edge 12 Internet Explorer 4 Firefox 1 Opera 12.1 Safari 1 geeksr3ap HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2022" }, { "code": null, "e": 280, "s": 28, "text": "The DOM lastModified property in HTML is used to return the date and time of the current document that was last modified. This property is read-only. This property returns a string which contains the date and time when the document was last modified. " }, { "code": null, "e": 288, "s": 280, "text": "Syntax:" }, { "code": null, "e": 310, "s": 288, "text": "document.lastModified" }, { "code": null, "e": 320, "s": 310, "text": "Example: " }, { "code": null, "e": 325, "s": 320, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM lastModified Property </title></head> <body style=\"text-align:center\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM lastModified Property </h2> <button onclick=\"geeks()\"> Submit </button> <p id=\"sudo\"></p> <script> /* Function to use lastModified property */ function geeks() { var x = document.lastModified; document.getElementById(\"sudo\").innerHTML = x; } </script></body> </html> ", "e": 885, "s": 325, "text": null }, { "code": null, "e": 893, "s": 885, "text": "Output:" }, { "code": null, "e": 985, "s": 896, "text": "Supported Browsers: The browser supported by DOM lastModified Property are listed below:" }, { "code": null, "e": 1001, "s": 985, "text": "Google Chrome 1" }, { "code": null, "e": 1009, "s": 1001, "text": "Edge 12" }, { "code": null, "e": 1029, "s": 1009, "text": "Internet Explorer 4" }, { "code": null, "e": 1039, "s": 1029, "text": "Firefox 1" }, { "code": null, "e": 1050, "s": 1039, "text": "Opera 12.1" }, { "code": null, "e": 1059, "s": 1050, "text": "Safari 1" }, { "code": null, "e": 1069, "s": 1059, "text": "geeksr3ap" }, { "code": null, "e": 1078, "s": 1069, "text": "HTML-DOM" }, { "code": null, "e": 1083, "s": 1078, "text": "HTML" }, { "code": null, "e": 1100, "s": 1083, "text": "Web Technologies" }, { "code": null, "e": 1105, "s": 1100, "text": "HTML" }, { "code": null, "e": 1203, "s": 1105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1251, "s": 1203, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1313, "s": 1251, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1363, "s": 1313, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1387, "s": 1363, "text": "REST API (Introduction)" }, { "code": null, "e": 1440, "s": 1387, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1473, "s": 1440, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1535, "s": 1473, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1596, "s": 1535, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1646, "s": 1596, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Exceptional Conditions Testing in Unit Tests
12 Jun, 2019 This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used. Code #1 : Testing that a function raised a ValueError exception import unittest # A simple function to illustratedef parse_int(s): return int(s) class TestConversion(unittest.TestCase): def test_bad_int(self): self.assertRaises(ValueError, parse_int, 'N/A') Code #2 : Test the exception’s value with a different approach is needed import errno class TestIO(unittest.TestCase): def test_file_not_found(self): try: f = open('/file/not/found') except IOError as e: self.assertEqual(e.errno, errno.ENOENT) else: self.fail('IOError not raised') The assertRaises() method provides a convenient way to test for the presence of an exception. A common pitfall is to write tests that manually try to do things with exceptions on their own. Code #3 : Example class TestConversion(unittest.TestCase): def test_bad_int(self): try: r = parse_int('N/A') except ValueError as e: self.assertEqual(type(e), ValueError) The problem with such approaches is that it is easy to forget about corner cases, such as that when no exception is raised at all. To do that, an extra check for that situation needs to be added, as shown in the code below. Code #4 : class TestConversion(unittest.TestCase): def test_bad_int(self): try: r = parse_int('N/A') except ValueError as e: self.assertEqual(type(e), ValueError) else: self.fail('ValueError not raised') The assertRaises() method simply takes care of these details, so it is preferred to be used. The one limitation of assertRaises() is that it doesn’t provide a means for testing the value of the exception object that’s created.To do that, it has to be manually tested. Somewhere in between these two extremes, the assertRaisesRegex() method can be used and it allows to test for an exception and perform a regular expression match against the exception’s string representation at the same time. Code #5 : class TestConversion(unittest.TestCase): def test_bad_int(self): self.assertRaisesRegex( ValueError, 'invalid literal .*', parse_int, 'N/A') A little-known fact about assertRaises() and assertRaisesRegex() is that they can also be used as context managers. Code #6 : class TestConversion(unittest.TestCase): def test_bad_int(self): with self.assertRaisesRegex(ValueError, 'invalid literal .*'): r = parse_int('N/A') This form can be useful if the test involves multiple steps (e.g., setup) besides that of simply executing a callable. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 172, "s": 28, "text": "This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used." }, { "code": null, "e": 236, "s": 172, "text": "Code #1 : Testing that a function raised a ValueError exception" }, { "code": "import unittest # A simple function to illustratedef parse_int(s): return int(s) class TestConversion(unittest.TestCase): def test_bad_int(self): self.assertRaises(ValueError, parse_int, 'N/A')", "e": 445, "s": 236, "text": null }, { "code": null, "e": 518, "s": 445, "text": "Code #2 : Test the exception’s value with a different approach is needed" }, { "code": "import errno class TestIO(unittest.TestCase): def test_file_not_found(self): try: f = open('/file/not/found') except IOError as e: self.assertEqual(e.errno, errno.ENOENT) else: self.fail('IOError not raised')", "e": 785, "s": 518, "text": null }, { "code": null, "e": 975, "s": 785, "text": "The assertRaises() method provides a convenient way to test for the presence of an exception. A common pitfall is to write tests that manually try to do things with exceptions on their own." }, { "code": null, "e": 993, "s": 975, "text": "Code #3 : Example" }, { "code": "class TestConversion(unittest.TestCase): def test_bad_int(self): try: r = parse_int('N/A') except ValueError as e: self.assertEqual(type(e), ValueError)", "e": 1185, "s": 993, "text": null }, { "code": null, "e": 1409, "s": 1185, "text": "The problem with such approaches is that it is easy to forget about corner cases, such as that when no exception is raised at all. To do that, an extra check for that situation needs to be added, as shown in the code below." }, { "code": null, "e": 1419, "s": 1409, "text": "Code #4 :" }, { "code": "class TestConversion(unittest.TestCase): def test_bad_int(self): try: r = parse_int('N/A') except ValueError as e: self.assertEqual(type(e), ValueError) else: self.fail('ValueError not raised')", "e": 1670, "s": 1419, "text": null }, { "code": null, "e": 2164, "s": 1670, "text": "The assertRaises() method simply takes care of these details, so it is preferred to be used. The one limitation of assertRaises() is that it doesn’t provide a means for testing the value of the exception object that’s created.To do that, it has to be manually tested. Somewhere in between these two extremes, the assertRaisesRegex() method can be used and it allows to test for an exception and perform a regular expression match against the exception’s string representation at the same time." }, { "code": null, "e": 2174, "s": 2164, "text": "Code #5 :" }, { "code": "class TestConversion(unittest.TestCase): def test_bad_int(self): self.assertRaisesRegex( ValueError, 'invalid literal .*', parse_int, 'N/A')", "e": 2356, "s": 2174, "text": null }, { "code": null, "e": 2472, "s": 2356, "text": "A little-known fact about assertRaises() and assertRaisesRegex() is that they can also be used as context managers." }, { "code": null, "e": 2482, "s": 2472, "text": "Code #6 :" }, { "code": "class TestConversion(unittest.TestCase): def test_bad_int(self): with self.assertRaisesRegex(ValueError, 'invalid literal .*'): r = parse_int('N/A')", "e": 2652, "s": 2482, "text": null }, { "code": null, "e": 2771, "s": 2652, "text": "This form can be useful if the test involves multiple steps (e.g., setup) besides that of simply executing a callable." }, { "code": null, "e": 2786, "s": 2771, "text": "python-utility" }, { "code": null, "e": 2793, "s": 2786, "text": "Python" }, { "code": null, "e": 2891, "s": 2793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2909, "s": 2891, "text": "Python Dictionary" }, { "code": null, "e": 2951, "s": 2909, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2973, "s": 2951, "text": "Enumerate() in Python" }, { "code": null, "e": 3008, "s": 2973, "text": "Read a file line by line in Python" }, { "code": null, "e": 3034, "s": 3008, "text": "Python String | replace()" }, { "code": null, "e": 3066, "s": 3034, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3095, "s": 3066, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3122, "s": 3095, "text": "Python Classes and Objects" }, { "code": null, "e": 3152, "s": 3122, "text": "Iterate over a list in Python" } ]
Covariance and Correlation in R Programming
14 Jan, 2022 Covariance and Correlation are terms used in statistics to measure relationships between two random variables. Both of these terms measure linear dependency between a pair of random variables or bivariate data. In this article, we are going to discuss cov(), cor() and cov2cor() functions in R which use covariance and correlation methods of statistics and probability theory. In R programming, covariance can be measured using cov() function. Covariance is a statistical term used to measures the direction of the linear relationship between the data vectors. Mathematically, where, x represents the x data vector y represents the y data vector [Tex]\bar{x} [/Tex]represents mean of x data vector [Tex]\bar{y} [/Tex]represents mean of y data vector N represents total observations Syntax: cov(x, y, method) where, x and y represents the data vectors method defines the type of method to be used to compute covariance. Default is “pearson”. Example: R # Data vectorsx <- c(1, 3, 5, 10) y <- c(2, 4, 6, 20) # Print covariance using different methodsprint(cov(x, y))print(cov(x, y, method = "pearson"))print(cov(x, y, method = "kendall"))print(cov(x, y, method = "spearman")) Output: [1] 30.66667 [1] 30.66667 [1] 12 [1] 1.666667 cor() function in R programming measures the correlation coefficient value. Correlation is a relationship term in statistics that uses the covariance method to measure how strong the vectors are related. Mathematically, where, x represents the x data vector y represents the y data vector [Tex]\bar{x} [/Tex]represents mean of x data vector [Tex]\bar{y} [/Tex]represents mean of y data vector Syntax: cor(x, y, method) where, x and y represents the data vectors method defines the type of method to be used to compute covariance. Default is “pearson”. Example: R # Data vectorsx <- c(1, 3, 5, 10) y <- c(2, 4, 6, 20) # Print correlation using different methodsprint(cor(x, y)) print(cor(x, y, method = "pearson"))print(cor(x, y, method = "kendall"))print(cor(x, y, method = "spearman")) Output: [1] 0.9724702 [1] 0.9724702 [1] 1 [1] 1 cov2cor() function in R programming converts a covariance matrix into corresponding correlation matrix. Syntax: cov2cor(X) where, X and y represents the covariance square matrix Example: R # Data vectorsx <- rnorm(2)y <- rnorm(2) # Binding into square matrixmat <- cbind(x, y) # Defining X as the covariance matrixX <- cov(mat) # Print covariance matrixprint(X) # Print correlation matrix of data# vectorprint(cor(mat)) # Using function cov2cor()# To convert covariance matrix to# correlation matrixprint(cov2cor(X)) Output: x y x 0.0742700 -0.1268199 y -0.1268199 0.2165516 x y x 1 -1 y -1 1 x y x 1 -1 y -1 1 kumar_satyam rkbhola5 R-Functions R-Statistics R-Vectors R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2022" }, { "code": null, "e": 240, "s": 28, "text": "Covariance and Correlation are terms used in statistics to measure relationships between two random variables. Both of these terms measure linear dependency between a pair of random variables or bivariate data. " }, { "code": null, "e": 406, "s": 240, "text": "In this article, we are going to discuss cov(), cor() and cov2cor() functions in R which use covariance and correlation methods of statistics and probability theory." }, { "code": null, "e": 607, "s": 406, "text": "In R programming, covariance can be measured using cov() function. Covariance is a statistical term used to measures the direction of the linear relationship between the data vectors. Mathematically, " }, { "code": null, "e": 615, "s": 607, "text": "where, " }, { "code": null, "e": 815, "s": 615, "text": "x represents the x data vector y represents the y data vector [Tex]\\bar{x} [/Tex]represents mean of x data vector [Tex]\\bar{y} [/Tex]represents mean of y data vector N represents total observations" }, { "code": null, "e": 841, "s": 815, "text": "Syntax: cov(x, y, method)" }, { "code": null, "e": 849, "s": 841, "text": "where, " }, { "code": null, "e": 885, "s": 849, "text": "x and y represents the data vectors" }, { "code": null, "e": 975, "s": 885, "text": "method defines the type of method to be used to compute covariance. Default is “pearson”." }, { "code": null, "e": 985, "s": 975, "text": "Example: " }, { "code": null, "e": 987, "s": 985, "text": "R" }, { "code": "# Data vectorsx <- c(1, 3, 5, 10) y <- c(2, 4, 6, 20) # Print covariance using different methodsprint(cov(x, y))print(cov(x, y, method = \"pearson\"))print(cov(x, y, method = \"kendall\"))print(cov(x, y, method = \"spearman\"))", "e": 1209, "s": 987, "text": null }, { "code": null, "e": 1218, "s": 1209, "text": "Output: " }, { "code": null, "e": 1264, "s": 1218, "text": "[1] 30.66667\n[1] 30.66667\n[1] 12\n[1] 1.666667" }, { "code": null, "e": 1484, "s": 1264, "text": "cor() function in R programming measures the correlation coefficient value. Correlation is a relationship term in statistics that uses the covariance method to measure how strong the vectors are related. Mathematically," }, { "code": null, "e": 1492, "s": 1484, "text": "where, " }, { "code": null, "e": 1660, "s": 1492, "text": "x represents the x data vector y represents the y data vector [Tex]\\bar{x} [/Tex]represents mean of x data vector [Tex]\\bar{y} [/Tex]represents mean of y data vector" }, { "code": null, "e": 1686, "s": 1660, "text": "Syntax: cor(x, y, method)" }, { "code": null, "e": 1694, "s": 1686, "text": "where, " }, { "code": null, "e": 1730, "s": 1694, "text": "x and y represents the data vectors" }, { "code": null, "e": 1820, "s": 1730, "text": "method defines the type of method to be used to compute covariance. Default is “pearson”." }, { "code": null, "e": 1830, "s": 1820, "text": "Example: " }, { "code": null, "e": 1832, "s": 1830, "text": "R" }, { "code": "# Data vectorsx <- c(1, 3, 5, 10) y <- c(2, 4, 6, 20) # Print correlation using different methodsprint(cor(x, y)) print(cor(x, y, method = \"pearson\"))print(cor(x, y, method = \"kendall\"))print(cor(x, y, method = \"spearman\"))", "e": 2056, "s": 1832, "text": null }, { "code": null, "e": 2065, "s": 2056, "text": "Output: " }, { "code": null, "e": 2105, "s": 2065, "text": "[1] 0.9724702\n[1] 0.9724702\n[1] 1\n[1] 1" }, { "code": null, "e": 2209, "s": 2105, "text": "cov2cor() function in R programming converts a covariance matrix into corresponding correlation matrix." }, { "code": null, "e": 2228, "s": 2209, "text": "Syntax: cov2cor(X)" }, { "code": null, "e": 2236, "s": 2228, "text": "where, " }, { "code": null, "e": 2284, "s": 2236, "text": "X and y represents the covariance square matrix" }, { "code": null, "e": 2294, "s": 2284, "text": "Example: " }, { "code": null, "e": 2296, "s": 2294, "text": "R" }, { "code": "# Data vectorsx <- rnorm(2)y <- rnorm(2) # Binding into square matrixmat <- cbind(x, y) # Defining X as the covariance matrixX <- cov(mat) # Print covariance matrixprint(X) # Print correlation matrix of data# vectorprint(cor(mat)) # Using function cov2cor()# To convert covariance matrix to# correlation matrixprint(cov2cor(X))", "e": 2624, "s": 2296, "text": null }, { "code": null, "e": 2633, "s": 2624, "text": "Output: " }, { "code": null, "e": 2755, "s": 2633, "text": " x y\nx 0.0742700 -0.1268199\ny -0.1268199 0.2165516\n\n x y\nx 1 -1\ny -1 1\n\n x y\nx 1 -1\ny -1 1" }, { "code": null, "e": 2768, "s": 2755, "text": "kumar_satyam" }, { "code": null, "e": 2777, "s": 2768, "text": "rkbhola5" }, { "code": null, "e": 2789, "s": 2777, "text": "R-Functions" }, { "code": null, "e": 2802, "s": 2789, "text": "R-Statistics" }, { "code": null, "e": 2812, "s": 2802, "text": "R-Vectors" }, { "code": null, "e": 2823, "s": 2812, "text": "R Language" }, { "code": null, "e": 2921, "s": 2823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2966, "s": 2921, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 3018, "s": 2966, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 3076, "s": 3018, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 3128, "s": 3076, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3186, "s": 3128, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3218, "s": 3186, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 3281, "s": 3218, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 3316, "s": 3281, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3360, "s": 3316, "text": "How to change Row Names of DataFrame in R ?" } ]
Check if strings are rotations of each other or not | Practice | GeeksforGeeks
Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase. Example 1: Input: geeksforgeeks forgeeksgeeks Output: 1 Explanation: s1 is geeksforgeeks, s2 is forgeeksgeeks. Clearly, s2 is a rotated version of s1 as s2 can be obtained by left-rotating s1 by 5 units. Example 2: Input: mightandmagic andmagicmigth Output: 0 Explanation: Here with any amount of rotation s2 can't be obtained by s1. Your Task: The task is to complete the function areRotations() which checks if the two strings are rotations of each other. The function returns true if string 1 can be obtained by rotating string 2, else it returns false. Expected Time Complexity: O(N). Expected Space Complexity: O(N). Note: N = |s1|. Constraints: 1 <= |s1|, |s2| <= 107 0 luvgupta76691 week ago Simple Optimal Working Best Java Solution | No Built-In method | No Extra Space- Sol 1- Using no extra space, no direct functions used- public static boolean areRotations(String s,String goal){ if(s.length()!=goal.length()) { return false; } for(int i=0;i<s.length();i++){ if (isRotated(s, goal, i)) { return true; } } return false; } static boolean isRotated(String s,String goal,int rotation){ for(int j=0; j<s.length(); j++){ if(s.charAt(j)!=goal.charAt((j+rotation)%s.length())){ return false; } } return true; } Sol 2- Using no extra space, direct functions used- public static boolean areRotations(String s1,String s2){ return s1.length()==s2.length() && (s2+s2).contains(s1); } +1 swathipriya4961 week ago def areRotations(self,s1,s2): #code here for i in range(0,len(s1)): s1=s1[1:len(s1)]+s1[0] if(s1==s2): return True return False +1 17_7_31 week ago if(s1.length()!=s2.length()){ return false; }else{ s1=s1+s1; return (s1.find(s2)!=-1)?true:false; } 0 neelasatyasai931 week ago def areRotations(self,s1,s2): for i in range(len(s1)): temp = s1[i:]+s1[:i] if temp == s2: return True else: return False 0 benzwrites1 week ago class Solution: #Function to check if two strings are rotations of each other or not. def areRotations(self,s1,s2): for i in range(len(s1)): temp = s1[i::]+s1[:i] if temp == s2: return True else: return False 0 yamijalaanvay2 weeks ago Easiest C++ Solution: O(N) bool areRotations(string s1,string s2) { // Your code here if(s1.length()!=s2.length()) return false; return ((s1+s1).find(s2)!=string::npos); } 0 mrpalashbharati2 weeks ago bool areRotations(string s1,string s2) { // Your code here if(s1.size()!=s2.size()){ return false; } return (s1+s1).find(s2)!=-1; } +2 thecodebuilder2 weeks ago Two solutions: Using temporary string bool areRotations(string s1,string s2) { if(s1.length()!=s2.length()) return false; for(int i=0;i<s1.length();i++){ string temp = ""; temp+=s1[s1.length()-1]; s1.pop_back(); temp+=s1; s1=temp; if(temp==s2) return true; } return false; } Using concatenation of one string bool areRotations(string s1,string s2) { if(s1.length()!=s2.length()) return false; s1 = s1+s1; return (s1.find(s2)!=-1)?true:false; } 0 thakursahabsingh122 weeks ago JAVA : class Solution{ //Function to check if two strings are rotations of each other or not. public static boolean areRotations(String s1, String s2 ) { // Your code here if(s1.length()!=s2.length()) return false; return (s1+s1).contains(s2); } } +1 anujparask8hq2 weeks ago PYTHON SOLUTION #Function to check if two strings are rotations of each other or not. def areRotations(self,s1,s2): if len(s1)==len(s2): if s2 in (s1+s1): return 1 return 0 #code here We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 369, "s": 226, "text": "Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase." }, { "code": null, "e": 382, "s": 371, "text": "Example 1:" }, { "code": null, "e": 577, "s": 382, "text": "Input:\ngeeksforgeeks\nforgeeksgeeks\nOutput: \n1\nExplanation: s1 is geeksforgeeks, s2 is\nforgeeksgeeks. Clearly, s2 is a rotated\nversion of s1 as s2 can be obtained by\nleft-rotating s1 by 5 units.\n" }, { "code": null, "e": 590, "s": 579, "text": "Example 2:" }, { "code": null, "e": 710, "s": 590, "text": "Input:\nmightandmagic\nandmagicmigth\nOutput: \n0\nExplanation: Here with any amount of\nrotation s2 can't be obtained by s1." }, { "code": null, "e": 935, "s": 712, "text": "Your Task:\nThe task is to complete the function areRotations() which checks if the two strings are rotations of each other. The function returns true if string 1 can be obtained by rotating string 2, else it returns false." }, { "code": null, "e": 1018, "s": 937, "text": "Expected Time Complexity: O(N).\nExpected Space Complexity: O(N).\nNote: N = |s1|." }, { "code": null, "e": 1056, "s": 1020, "text": "Constraints:\n1 <= |s1|, |s2| <= 107" }, { "code": null, "e": 1058, "s": 1056, "text": "0" }, { "code": null, "e": 1081, "s": 1058, "text": "luvgupta76691 week ago" }, { "code": null, "e": 1162, "s": 1081, "text": "Simple Optimal Working Best Java Solution | No Built-In method | No Extra Space-" }, { "code": null, "e": 1219, "s": 1164, "text": "Sol 1- Using no extra space, no direct functions used-" }, { "code": null, "e": 1782, "s": 1219, "text": " public static boolean areRotations(String s,String goal){\n if(s.length()!=goal.length()) { \n return false; \n }\n for(int i=0;i<s.length();i++){ \n if (isRotated(s, goal, i)) { \n return true; \n }\n }\n return false;\n }\n static boolean isRotated(String s,String goal,int rotation){\n for(int j=0; j<s.length(); j++){\n if(s.charAt(j)!=goal.charAt((j+rotation)%s.length())){\n return false; \n }\n }\n return true;\n }" }, { "code": null, "e": 1834, "s": 1782, "text": "Sol 2- Using no extra space, direct functions used-" }, { "code": null, "e": 1968, "s": 1836, "text": "public static boolean areRotations(String s1,String s2){ \n return s1.length()==s2.length() && (s2+s2).contains(s1);\n}" }, { "code": null, "e": 1971, "s": 1968, "text": "+1" }, { "code": null, "e": 1996, "s": 1971, "text": "swathipriya4961 week ago" }, { "code": null, "e": 2187, "s": 1996, "text": "def areRotations(self,s1,s2): #code here for i in range(0,len(s1)): s1=s1[1:len(s1)]+s1[0] if(s1==s2): return True return False " }, { "code": null, "e": 2190, "s": 2187, "text": "+1" }, { "code": null, "e": 2207, "s": 2190, "text": "17_7_31 week ago" }, { "code": null, "e": 2362, "s": 2207, "text": " if(s1.length()!=s2.length()){\n return false;\n }else{\n s1=s1+s1;\n return (s1.find(s2)!=-1)?true:false;\n }" }, { "code": null, "e": 2364, "s": 2362, "text": "0" }, { "code": null, "e": 2390, "s": 2364, "text": "neelasatyasai931 week ago" }, { "code": null, "e": 2566, "s": 2390, "text": " def areRotations(self,s1,s2): for i in range(len(s1)): temp = s1[i:]+s1[:i] if temp == s2: return True else: return False" }, { "code": null, "e": 2568, "s": 2566, "text": "0" }, { "code": null, "e": 2589, "s": 2568, "text": "benzwrites1 week ago" }, { "code": null, "e": 2861, "s": 2589, "text": "class Solution: #Function to check if two strings are rotations of each other or not. def areRotations(self,s1,s2): for i in range(len(s1)): temp = s1[i::]+s1[:i] if temp == s2: return True else: return False" }, { "code": null, "e": 2863, "s": 2861, "text": "0" }, { "code": null, "e": 2888, "s": 2863, "text": "yamijalaanvay2 weeks ago" }, { "code": null, "e": 2915, "s": 2888, "text": "Easiest C++ Solution: O(N)" }, { "code": null, "e": 3084, "s": 2917, "text": "bool areRotations(string s1,string s2) { // Your code here if(s1.length()!=s2.length()) return false; return ((s1+s1).find(s2)!=string::npos); }" }, { "code": null, "e": 3086, "s": 3084, "text": "0" }, { "code": null, "e": 3113, "s": 3086, "text": "mrpalashbharati2 weeks ago" }, { "code": null, "e": 3283, "s": 3113, "text": "bool areRotations(string s1,string s2) { // Your code here if(s1.size()!=s2.size()){ return false; } return (s1+s1).find(s2)!=-1; }" }, { "code": null, "e": 3286, "s": 3283, "text": "+2" }, { "code": null, "e": 3312, "s": 3286, "text": "thecodebuilder2 weeks ago" }, { "code": null, "e": 3327, "s": 3312, "text": "Two solutions:" }, { "code": null, "e": 3350, "s": 3327, "text": "Using temporary string" }, { "code": null, "e": 3713, "s": 3350, "text": "bool areRotations(string s1,string s2)\n {\n if(s1.length()!=s2.length())\n return false;\n for(int i=0;i<s1.length();i++){\n string temp = \"\";\n temp+=s1[s1.length()-1];\n s1.pop_back();\n temp+=s1;\n s1=temp;\n if(temp==s2)\n return true;\n }\n return false;\n }" }, { "code": null, "e": 3747, "s": 3713, "text": "Using concatenation of one string" }, { "code": null, "e": 3920, "s": 3747, "text": "bool areRotations(string s1,string s2)\n {\n if(s1.length()!=s2.length())\n return false;\n s1 = s1+s1;\n return (s1.find(s2)!=-1)?true:false;\n }" }, { "code": null, "e": 3922, "s": 3920, "text": "0" }, { "code": null, "e": 3952, "s": 3922, "text": "thakursahabsingh122 weeks ago" }, { "code": null, "e": 3959, "s": 3952, "text": "JAVA :" }, { "code": null, "e": 4240, "s": 3961, "text": "class Solution{ //Function to check if two strings are rotations of each other or not. public static boolean areRotations(String s1, String s2 ) { // Your code here if(s1.length()!=s2.length()) return false; return (s1+s1).contains(s2);" }, { "code": null, "e": 4249, "s": 4240, "text": " } }" }, { "code": null, "e": 4252, "s": 4249, "text": "+1" }, { "code": null, "e": 4277, "s": 4252, "text": "anujparask8hq2 weeks ago" }, { "code": null, "e": 4296, "s": 4277, "text": "PYTHON SOLUTION " }, { "code": null, "e": 4513, "s": 4296, "text": " #Function to check if two strings are rotations of each other or not. def areRotations(self,s1,s2): if len(s1)==len(s2): if s2 in (s1+s1): return 1 return 0 #code here" }, { "code": null, "e": 4659, "s": 4513, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4695, "s": 4659, "text": " Login to access your submissions. " }, { "code": null, "e": 4705, "s": 4695, "text": "\nProblem\n" }, { "code": null, "e": 4715, "s": 4705, "text": "\nContest\n" }, { "code": null, "e": 4778, "s": 4715, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4963, "s": 4778, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5247, "s": 4963, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 5393, "s": 5247, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 5470, "s": 5393, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5511, "s": 5470, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5539, "s": 5511, "text": "Disable browser extensions." }, { "code": null, "e": 5610, "s": 5539, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 5797, "s": 5610, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Generating hash id’s using uuid3() and uuid5() in Python
21 Sep, 2021 Python’s UUID class defines four functions and each generates different version of UUIDs. Let’s see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID’s taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are : uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string.uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string. uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string. uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string. uuid module defines the following namespace identifiers for use with uuid3() or uuid5() : NAMESPACE_DNS : Used when name string is fully qualified domain name. NAMESPACE_URL : Used when name string is a URL. NAMESPACE_OID : Used when name string is an ISO OID. NAMESPACE_X500 : Used when name string is an X.500 DN in DER or a text output format. Code #1 : Python3 # Python3 code to demonstrate working# of uuid3() and uuid5()import uuid # initializing a stringurl = "https://www.geeksforgeeks.org/fibonacci-sum-subset-elements/" # using NAMESPACE_URL as namespace# to generate MD5 hash uuidprint ("The SHA1 hash value generated ID is : ", uuid.uuid3(uuid.NAMESPACE_URL, url)) # using NAMESPACE_URL as namespace # to generate SHA-1 hash uuidprint ("The MD5 hash value generated ID is : ", uuid.uuid5(uuid.NAMESPACE_URL, url)) The SHA1 hash value generated ID is : e13a319e-16d9-3ff5-a83c-96564007998e The MD5 hash value generated ID is : dbe3178d-4b83-5024-9b26-9b8e1b280514 Code #2 : Python3 # Python3 code to demonstrate working # of uuid3() and uuid5()import uuid # initializing a stringqualified_dns = "www.geeksforgeeks.org" # using NAMESPACE_DNS as namespace# to find MD5 hash idprint ("The SHA1 hash value generated ID is : ", uuid.uuid3(uuid.NAMESPACE_DNS, qualified_dns)) # using NAMESPACE_DNS as namespace# to generate SHA-1 hash idprint ("The MD5 hash value generated ID is : ", uuid.uuid5(uuid.NAMESPACE_DNS, qualified_dns)) The SHA1 hash value generated ID is : adbed9f7-bbe3-376f-b88d-2018b8f6db07 The MD5 hash value generated ID is : f72cdf8a-b361-50b2-9451-37a997f8675d Note : The ID generation is 2 step process. First, the concatenation of string and namespaces takes place, then given as input to the respective function to return a 128 UUID generated. If the same NAMESPACE value with a similar string is chosen again, ID generated will be same as well. Reference : https://docs.python.org/2/library/uuid.html simmytarika5 Python-Library Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 380, "s": 28, "text": "Python’s UUID class defines four functions and each generates different version of UUIDs. Let’s see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID’s taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are : " }, { "code": null, "e": 681, "s": 380, "text": "uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string.uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string." }, { "code": null, "e": 831, "s": 681, "text": "uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string." }, { "code": null, "e": 983, "s": 831, "text": "uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string." }, { "code": null, "e": 1075, "s": 983, "text": "uuid module defines the following namespace identifiers for use with uuid3() or uuid5() : " }, { "code": null, "e": 1334, "s": 1075, "text": "NAMESPACE_DNS : Used when name string is fully qualified domain name. NAMESPACE_URL : Used when name string is a URL. NAMESPACE_OID : Used when name string is an ISO OID. NAMESPACE_X500 : Used when name string is an X.500 DN in DER or a text output format. " }, { "code": null, "e": 1348, "s": 1334, "text": " Code #1 : " }, { "code": null, "e": 1356, "s": 1348, "text": "Python3" }, { "code": "# Python3 code to demonstrate working# of uuid3() and uuid5()import uuid # initializing a stringurl = \"https://www.geeksforgeeks.org/fibonacci-sum-subset-elements/\" # using NAMESPACE_URL as namespace# to generate MD5 hash uuidprint (\"The SHA1 hash value generated ID is : \", uuid.uuid3(uuid.NAMESPACE_URL, url)) # using NAMESPACE_URL as namespace # to generate SHA-1 hash uuidprint (\"The MD5 hash value generated ID is : \", uuid.uuid5(uuid.NAMESPACE_URL, url))", "e": 1839, "s": 1356, "text": null }, { "code": null, "e": 1990, "s": 1839, "text": "The SHA1 hash value generated ID is : e13a319e-16d9-3ff5-a83c-96564007998e\nThe MD5 hash value generated ID is : dbe3178d-4b83-5024-9b26-9b8e1b280514" }, { "code": null, "e": 2005, "s": 1992, "text": " Code #2 : " }, { "code": null, "e": 2013, "s": 2005, "text": "Python3" }, { "code": "# Python3 code to demonstrate working # of uuid3() and uuid5()import uuid # initializing a stringqualified_dns = \"www.geeksforgeeks.org\" # using NAMESPACE_DNS as namespace# to find MD5 hash idprint (\"The SHA1 hash value generated ID is : \", uuid.uuid3(uuid.NAMESPACE_DNS, qualified_dns)) # using NAMESPACE_DNS as namespace# to generate SHA-1 hash idprint (\"The MD5 hash value generated ID is : \", uuid.uuid5(uuid.NAMESPACE_DNS, qualified_dns))", "e": 2463, "s": 2013, "text": null }, { "code": null, "e": 2614, "s": 2463, "text": "The SHA1 hash value generated ID is : adbed9f7-bbe3-376f-b88d-2018b8f6db07\nThe MD5 hash value generated ID is : f72cdf8a-b361-50b2-9451-37a997f8675d" }, { "code": null, "e": 2963, "s": 2616, "text": " Note : The ID generation is 2 step process. First, the concatenation of string and namespaces takes place, then given as input to the respective function to return a 128 UUID generated. If the same NAMESPACE value with a similar string is chosen again, ID generated will be same as well. Reference : https://docs.python.org/2/library/uuid.html " }, { "code": null, "e": 2976, "s": 2963, "text": "simmytarika5" }, { "code": null, "e": 2991, "s": 2976, "text": "Python-Library" }, { "code": null, "e": 2998, "s": 2991, "text": "Python" }, { "code": null, "e": 3017, "s": 2998, "text": "Technical Scripter" } ]
Up-sampling in MATLAB
01 Oct, 2020 Interpolation or up-sampling is the specific inverse of decimation. It is a data saving operation, in that all examples of x[n] are available in the extended signal y[n]. Interpolation works by adding (L–1) zero-valued examples for each input sample. We will be using the interp() function to interpolate a signal. It is used to increase the sample rate of a signal by an integer factor. Syntax: a = interp(x, r) Parameter: x: input signal r: interpolation factor Return Value: Returns interpolated signal MATLAB code for interpolation of a signal: MATLAB % time vectort = 0 : .00025 : 1; # input signalx = sin(2 * pi * 50 * t) + sin(2 * pi * 100 * t); % increase the sample rate of i/p signal by factor of 4y = interp(x, 4); subplot(2, 2, 1); % plot few samples of the Original signalstem(x(1 : 75)) title('Original Signal'); subplot(2, 2, 2); % plots few samples of the up-sampled signalstem(y(1 : 75)); title('Interpolated Signal'); Output: MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Docker - COPY Instruction Decision Tree Introduction with example ML | Monte Carlo Tree Search (MCTS) Getting started with Machine Learning How to Run a Python Script using Docker? Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 280, "s": 28, "text": "Interpolation or up-sampling is the specific inverse of decimation. It is a data saving operation, in that all examples of x[n] are available in the extended signal y[n]. Interpolation works by adding (L–1) zero-valued examples for each input sample. " }, { "code": null, "e": 417, "s": 280, "text": "We will be using the interp() function to interpolate a signal. It is used to increase the sample rate of a signal by an integer factor." }, { "code": null, "e": 455, "s": 417, "text": "Syntax: a = interp(x, r) Parameter: " }, { "code": null, "e": 471, "s": 455, "text": "x: input signal" }, { "code": null, "e": 495, "s": 471, "text": "r: interpolation factor" }, { "code": null, "e": 539, "s": 495, "text": "Return Value: Returns interpolated signal " }, { "code": null, "e": 582, "s": 539, "text": "MATLAB code for interpolation of a signal:" }, { "code": null, "e": 589, "s": 582, "text": "MATLAB" }, { "code": "% time vectort = 0 : .00025 : 1; # input signalx = sin(2 * pi * 50 * t) + sin(2 * pi * 100 * t); % increase the sample rate of i/p signal by factor of 4y = interp(x, 4); subplot(2, 2, 1); % plot few samples of the Original signalstem(x(1 : 75)) title('Original Signal'); subplot(2, 2, 2); % plots few samples of the up-sampled signalstem(y(1 : 75)); title('Interpolated Signal');", "e": 976, "s": 589, "text": null }, { "code": null, "e": 984, "s": 976, "text": "Output:" }, { "code": null, "e": 991, "s": 984, "text": "MATLAB" }, { "code": null, "e": 1017, "s": 991, "text": "Advanced Computer Subject" }, { "code": null, "e": 1115, "s": 1017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1138, "s": 1115, "text": "System Design Tutorial" }, { "code": null, "e": 1161, "s": 1138, "text": "ML | Linear Regression" }, { "code": null, "e": 1187, "s": 1161, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1227, "s": 1187, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 1263, "s": 1227, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 1301, "s": 1263, "text": "Getting started with Machine Learning" }, { "code": null, "e": 1342, "s": 1301, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 1366, "s": 1342, "text": "Markov Decision Process" }, { "code": null, "e": 1402, "s": 1366, "text": "Basics of API Testing Using Postman" } ]
Using range in switch case in C/C++
In C or C++, we have used the switch-case statement. In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. The syntax of using range in Case is like below − case low ... high After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value. In the following program, we will see what will be the output for the range based case statement. #include <stdio.h> main() { int data[10] = { 5, 4, 10, 25, 60, 47, 23, 80, 14, 11}; int i; for(i = 0; i < 10; i++) { switch (data[i]) { case 1 ... 10: printf("%d in range 1 to 10\n", data[i]); break; case 11 ... 20: printf("%d in range 11 to 20\n", data[i]); break; case 21 ... 30: printf("%d in range 21 to 30\n", data[i]); break; case 31 ... 40: printf("%d in range 31 to 40\n", data[i]); break; default: printf("%d Exceeds the range\n", data[i]); break; } } } 5 in range 1 to 10 4 in range 1 to 10 10 in range 1 to 10 25 in range 21 to 30 60 Exceeds the range 47 Exceeds the range 23 in range 21 to 30 80 Exceeds the range 14 in range 11 to 20 11 in range 11 to 20
[ { "code": null, "e": 1398, "s": 1187, "text": "In C or C++, we have used the switch-case statement. In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement." }, { "code": null, "e": 1448, "s": 1398, "text": "The syntax of using range in Case is like below −" }, { "code": null, "e": 1466, "s": 1448, "text": "case low ... high" }, { "code": null, "e": 1589, "s": 1466, "text": "After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value." }, { "code": null, "e": 1687, "s": 1589, "text": "In the following program, we will see what will be the output for the range based case statement." }, { "code": null, "e": 2324, "s": 1687, "text": "#include <stdio.h>\nmain() {\n int data[10] = { 5, 4, 10, 25, 60, 47, 23, 80, 14, 11};\n int i;\n for(i = 0; i < 10; i++) {\n switch (data[i]) {\n case 1 ... 10:\n printf(\"%d in range 1 to 10\\n\", data[i]);\n break;\n case 11 ... 20:\n printf(\"%d in range 11 to 20\\n\", data[i]);\n break;\n case 21 ... 30:\n printf(\"%d in range 21 to 30\\n\", data[i]);\n break;\n case 31 ... 40:\n printf(\"%d in range 31 to 40\\n\", data[i]);\n break;\n default:\n printf(\"%d Exceeds the range\\n\", data[i]);\n break;\n }\n }\n}" }, { "code": null, "e": 2529, "s": 2324, "text": "5 in range 1 to 10\n4 in range 1 to 10\n10 in range 1 to 10\n25 in range 21 to 30\n60 Exceeds the range\n47 Exceeds the range\n23 in range 21 to 30\n80 Exceeds the range\n14 in range 11 to 20\n11 in range 11 to 20" } ]
Bucket Sort
22 Oct, 2021 Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem. Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently?A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn. Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers. The idea is to use bucket sort. Following is bucket algorithm. bucketSort(arr[], n) 1) Create n empty buckets (Or lists). 2) Do following for every array element arr[i]. .......a) Insert arr[i] into bucket[n*array[i]] 3) Sort individual buckets using insertion sort. 4) Concatenate all sorted buckets. Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time. The O(1) is easily possible if we use a linked list to represent a bucket (In the following code, C++ vector is used for simplicity). Step 4 also takes O(n) time as there will be n items in all buckets. The main step to analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed (please refer CLRS book for more details)Following is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ program to sort an// array using bucket sort#include <algorithm>#include <iostream>#include <vector>using namespace std; // Function to sort arr[] of// size n using bucket sortvoid bucketSort(float arr[], int n){ // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements // in different buckets for (int i = 0; i < n; i++) { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j];} /* Driver program to test above function */int main(){ float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); cout << "Sorted array is \n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to sort an array// using bucket sortimport java.util.*;import java.util.Collections; class GFG { // Function to sort arr[] of size n // using bucket sort static void bucketSort(float arr[], int n) { if (n <= 0) return; // 1) Create n empty buckets @SuppressWarnings("unchecked") Vector<Float>[] buckets = new Vector[n]; for (int i = 0; i < n; i++) { buckets[i] = new Vector<Float>(); } // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { float idx = arr[i] * n; buckets[(int)idx].add(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) { Collections.sort(buckets[i]); } // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < buckets[i].size(); j++) { arr[index++] = buckets[i].get(j); } } } // Driver code public static void main(String args[]) { float arr[] = { (float)0.897, (float)0.565, (float)0.656, (float)0.1234, (float)0.665, (float)0.3434 }; int n = arr.length; bucketSort(arr, n); System.out.println("Sorted array is "); for (float el : arr) { System.out.print(el + " "); } }} // This code is contributed by Himangshu Shekhar Jha # Python3 program to sort an array# using bucket sortdef insertionSort(b): for i in range(1, len(b)): up = b[i] j = i - 1 while j >= 0 and b[j] > up: b[j + 1] = b[j] j -= 1 b[j + 1] = up return b def bucketSort(x): arr = [] slot_num = 10 # 10 means 10 slots, each # slot's size is 0.1 for i in range(slot_num): arr.append([]) # Put array elements in different buckets for j in x: index_b = int(slot_num * j) arr[index_b].append(j) # Sort individual buckets for i in range(slot_num): arr[i] = insertionSort(arr[i]) # concatenate the result k = 0 for i in range(slot_num): for j in range(len(arr[i])): x[k] = arr[i][j] k += 1 return x # Driver Codex = [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434]print("Sorted Array is")print(bucketSort(x)) # This code is contributed by# Oneil Hsiao // C# program to sort an array// using bucket sortusing System;using System.Collections;using System.Collections.Generic;class GFG { // Function to sort arr[] of size n // using bucket sort static void bucketSort(float []arr, int n) { if (n <= 0) return; // 1) Create n empty buckets List<float>[] buckets = new List<float>[n]; for (int i = 0; i < n; i++) { buckets[i] = new List<float>(); } // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { float idx = arr[i] * n; buckets[(int)idx].Add(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) { buckets[i].Sort(); } // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < buckets[i].Count; j++) { arr[index++] = buckets[i][j]; } } } // Driver code public static void Main() { float []arr = { (float)0.897, (float)0.565, (float)0.656, (float)0.1234, (float)0.665, (float)0.3434 }; int n = arr.Length; bucketSort(arr, n); Console.WriteLine("Sorted array is "); foreach(float el in arr) { Console.Write(el + " "); } }} // This code is contributed by rutvik_56 <script>// Javascript program to sort an array// using bucket sort // Function to sort arr[] of size n// using bucket sortfunction bucketSort(arr,n){ if (n <= 0) return; // 1) Create n empty buckets let buckets = new Array(n); for (let i = 0; i < n; i++) { buckets[i] = []; } // 2) Put array elements in different buckets for (let i = 0; i < n; i++) { let idx = arr[i] * n; buckets[Math.floor(idx)].push(arr[i]); } // 3) Sort individual buckets for (let i = 0; i < n; i++) { buckets[i].sort(function(a,b){return a-b;}); } // 4) Concatenate all buckets into arr[] let index = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < buckets[i].length; j++) { arr[index++] = buckets[i][j]; } }} // Driver codelet arr = [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434];let n = arr.length;bucketSort(arr, n); document.write("Sorted array is <br>");for (let el of arr.values()) { document.write(el + " ");} // This code is contributed by unknown2108</script> Sorted array is 0.1234 0.3434 0.565 0.656 0.665 0.897 Algorithm : Find maximum element and minimum of the arrayCalculate the range of each bucket Find maximum element and minimum of the array Calculate the range of each bucket range = (max - min) / n n is the number of buckets 3. Create n buckets of calculated range 4. Scatter the array elements to these buckets BucketIndex = ( arr[i] - min ) / range 5. Now sort each bucket individually 6. Gather the sorted elements from buckets to original array Input : Unsorted array: [ 9.8 , 0.6 , 10.1 , 1.9 , 3.07 , 3.04 , 5.0 , 8.0 , 4.8 , 7.68 ] No of buckets : 5 Output : Sorted array: [ 0.6 , 1.9 , 3.04 , 3.07 , 4.8 , 5.0 , 7.68 , 8.0 , 9.8 , 10.1 ] Input : Unsorted array: [0.49 , 5.9 , 3.4 , 1.11 , 4.5 , 6.6 , 2.0] No of buckets: 3 Output : Sorted array: [0.49 , 1.11 , 2.0 , 3.4 , 4.5 , 5.9 , 6.6] Code : Python3 # Python program for the above approach # Bucket sort for numbers# having integer partdef bucketSort(arr, noOfBuckets): max_ele = max(arr) min_ele = min(arr) # range(for buckets) rnge = (max_ele - min_ele) / noOfBuckets temp = [] # create empty buckets for i in range(noOfBuckets): temp.append([]) # scatter the array elements # into the correct bucket for i in range(len(arr)): diff = (arr[i] - min_ele) / rnge - int((arr[i] - min_ele) / rnge) # append the boundary elements to the lower array if(diff == 0 and arr[i] != min_ele): temp[int((arr[i] - min_ele) / rnge) - 1].append(arr[i]) else: temp[int((arr[i] - min_ele) / rnge)].append(arr[i]) # Sort each bucket individually for i in range(len(temp)): if len(temp[i]) != 0: temp[i].sort() # Gather sorted elements # to the original array k = 0 for lst in temp: if lst: for i in lst: arr[k] = i k = k+1 # Driver Codearr = [9.8, 0.6, 10.1, 1.9, 3.07, 3.04, 5.0, 8.0, 4.8, 7.68]noOfBuckets = 5bucketSort(arr, noOfBuckets)print("Sorted array: ", arr) # This code is contributed by# Vinita Yadav Sorted array: [0.6, 1.9, 3.04, 3.07, 4.8, 5.0, 7.68, 8.0, 9.8, 10.1] Bucket Sort To Sort an Array with Negative NumbersReferences: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest http://en.wikipedia.org/wiki/Bucket_sort https://youtu.be/VuXbEb5ywrUSnapshots: Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Selection Sort Bubble Sort Insertion Sort Merge Sort Heap Sort QuickSort Radix Sort Counting Sort ShellSort Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above OneilHsiao himangshushekharjha Akanksha_Rai architbubber vinita07 rutvik_56 arorakashish0911 unknown2108 asmitwrites Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count Inversions in an array | Set 1 (Using Merge Sort) Merge two sorted arrays Sort an array of 0s, 1s and 2s | Dutch National Flag problem Chocolate Distribution Problem Find a triplet that sum to a given value k largest(or smallest) elements in an array sort() in Python Merge Sort for Linked Lists Minimum number of swaps required to sort an array Longest Consecutive Subsequence
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Oct, 2021" }, { "code": null, "e": 777, "s": 52, "text": "Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem. Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently?A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn. Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers. The idea is to use bucket sort. Following is bucket algorithm." }, { "code": null, "e": 1016, "s": 777, "text": "bucketSort(arr[], n)\n1) Create n empty buckets (Or lists).\n2) Do following for every array element arr[i].\n.......a) Insert arr[i] into bucket[n*array[i]]\n3) Sort individual buckets using insertion sort.\n4) Concatenate all sorted buckets." }, { "code": null, "e": 1575, "s": 1016, "text": "Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time. The O(1) is easily possible if we use a linked list to represent a bucket (In the following code, C++ vector is used for simplicity). Step 4 also takes O(n) time as there will be n items in all buckets. The main step to analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed (please refer CLRS book for more details)Following is the implementation of the above algorithm. " }, { "code": null, "e": 1579, "s": 1575, "text": "C++" }, { "code": null, "e": 1584, "s": 1579, "text": "Java" }, { "code": null, "e": 1592, "s": 1584, "text": "Python3" }, { "code": null, "e": 1595, "s": 1592, "text": "C#" }, { "code": null, "e": 1606, "s": 1595, "text": "Javascript" }, { "code": "// C++ program to sort an// array using bucket sort#include <algorithm>#include <iostream>#include <vector>using namespace std; // Function to sort arr[] of// size n using bucket sortvoid bucketSort(float arr[], int n){ // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements // in different buckets for (int i = 0; i < n; i++) { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j];} /* Driver program to test above function */int main(){ float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); cout << \"Sorted array is \\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 2638, "s": 1606, "text": null }, { "code": "// Java program to sort an array// using bucket sortimport java.util.*;import java.util.Collections; class GFG { // Function to sort arr[] of size n // using bucket sort static void bucketSort(float arr[], int n) { if (n <= 0) return; // 1) Create n empty buckets @SuppressWarnings(\"unchecked\") Vector<Float>[] buckets = new Vector[n]; for (int i = 0; i < n; i++) { buckets[i] = new Vector<Float>(); } // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { float idx = arr[i] * n; buckets[(int)idx].add(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) { Collections.sort(buckets[i]); } // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < buckets[i].size(); j++) { arr[index++] = buckets[i].get(j); } } } // Driver code public static void main(String args[]) { float arr[] = { (float)0.897, (float)0.565, (float)0.656, (float)0.1234, (float)0.665, (float)0.3434 }; int n = arr.length; bucketSort(arr, n); System.out.println(\"Sorted array is \"); for (float el : arr) { System.out.print(el + \" \"); } }} // This code is contributed by Himangshu Shekhar Jha", "e": 4125, "s": 2638, "text": null }, { "code": "# Python3 program to sort an array# using bucket sortdef insertionSort(b): for i in range(1, len(b)): up = b[i] j = i - 1 while j >= 0 and b[j] > up: b[j + 1] = b[j] j -= 1 b[j + 1] = up return b def bucketSort(x): arr = [] slot_num = 10 # 10 means 10 slots, each # slot's size is 0.1 for i in range(slot_num): arr.append([]) # Put array elements in different buckets for j in x: index_b = int(slot_num * j) arr[index_b].append(j) # Sort individual buckets for i in range(slot_num): arr[i] = insertionSort(arr[i]) # concatenate the result k = 0 for i in range(slot_num): for j in range(len(arr[i])): x[k] = arr[i][j] k += 1 return x # Driver Codex = [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434]print(\"Sorted Array is\")print(bucketSort(x)) # This code is contributed by# Oneil Hsiao", "e": 5117, "s": 4125, "text": null }, { "code": "// C# program to sort an array// using bucket sortusing System;using System.Collections;using System.Collections.Generic;class GFG { // Function to sort arr[] of size n // using bucket sort static void bucketSort(float []arr, int n) { if (n <= 0) return; // 1) Create n empty buckets List<float>[] buckets = new List<float>[n]; for (int i = 0; i < n; i++) { buckets[i] = new List<float>(); } // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { float idx = arr[i] * n; buckets[(int)idx].Add(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) { buckets[i].Sort(); } // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < buckets[i].Count; j++) { arr[index++] = buckets[i][j]; } } } // Driver code public static void Main() { float []arr = { (float)0.897, (float)0.565, (float)0.656, (float)0.1234, (float)0.665, (float)0.3434 }; int n = arr.Length; bucketSort(arr, n); Console.WriteLine(\"Sorted array is \"); foreach(float el in arr) { Console.Write(el + \" \"); } }} // This code is contributed by rutvik_56", "e": 6378, "s": 5117, "text": null }, { "code": "<script>// Javascript program to sort an array// using bucket sort // Function to sort arr[] of size n// using bucket sortfunction bucketSort(arr,n){ if (n <= 0) return; // 1) Create n empty buckets let buckets = new Array(n); for (let i = 0; i < n; i++) { buckets[i] = []; } // 2) Put array elements in different buckets for (let i = 0; i < n; i++) { let idx = arr[i] * n; buckets[Math.floor(idx)].push(arr[i]); } // 3) Sort individual buckets for (let i = 0; i < n; i++) { buckets[i].sort(function(a,b){return a-b;}); } // 4) Concatenate all buckets into arr[] let index = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < buckets[i].length; j++) { arr[index++] = buckets[i][j]; } }} // Driver codelet arr = [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434];let n = arr.length;bucketSort(arr, n); document.write(\"Sorted array is <br>\");for (let el of arr.values()) { document.write(el + \" \");} // This code is contributed by unknown2108</script>", "e": 7559, "s": 6378, "text": null }, { "code": null, "e": 7615, "s": 7559, "text": "Sorted array is \n0.1234 0.3434 0.565 0.656 0.665 0.897 " }, { "code": null, "e": 7628, "s": 7615, "text": "Algorithm : " }, { "code": null, "e": 7708, "s": 7628, "text": "Find maximum element and minimum of the arrayCalculate the range of each bucket" }, { "code": null, "e": 7754, "s": 7708, "text": "Find maximum element and minimum of the array" }, { "code": null, "e": 7789, "s": 7754, "text": "Calculate the range of each bucket" }, { "code": null, "e": 7860, "s": 7789, "text": " range = (max - min) / n\n n is the number of buckets" }, { "code": null, "e": 7908, "s": 7860, "text": " 3. Create n buckets of calculated range" }, { "code": null, "e": 7963, "s": 7908, "text": " 4. Scatter the array elements to these buckets" }, { "code": null, "e": 8012, "s": 7963, "text": " BucketIndex = ( arr[i] - min ) / range" }, { "code": null, "e": 8057, "s": 8012, "text": " 5. Now sort each bucket individually" }, { "code": null, "e": 8126, "s": 8057, "text": " 6. Gather the sorted elements from buckets to original array" }, { "code": null, "e": 8334, "s": 8126, "text": "Input : \nUnsorted array: [ 9.8 , 0.6 , 10.1 , 1.9 , 3.07 , 3.04 , 5.0 , 8.0 , 4.8 , 7.68 ]\nNo of buckets : 5\n\nOutput : \nSorted array: [ 0.6 , 1.9 , 3.04 , 3.07 , 4.8 , 5.0 , 7.68 , 8.0 , 9.8 , 10.1 ]" }, { "code": null, "e": 8496, "s": 8334, "text": "Input : \nUnsorted array: [0.49 , 5.9 , 3.4 , 1.11 , 4.5 , 6.6 , 2.0]\nNo of buckets: 3\n\nOutput : \nSorted array: [0.49 , 1.11 , 2.0 , 3.4 , 4.5 , 5.9 , 6.6]" }, { "code": null, "e": 8503, "s": 8496, "text": "Code :" }, { "code": null, "e": 8511, "s": 8503, "text": "Python3" }, { "code": "# Python program for the above approach # Bucket sort for numbers# having integer partdef bucketSort(arr, noOfBuckets): max_ele = max(arr) min_ele = min(arr) # range(for buckets) rnge = (max_ele - min_ele) / noOfBuckets temp = [] # create empty buckets for i in range(noOfBuckets): temp.append([]) # scatter the array elements # into the correct bucket for i in range(len(arr)): diff = (arr[i] - min_ele) / rnge - int((arr[i] - min_ele) / rnge) # append the boundary elements to the lower array if(diff == 0 and arr[i] != min_ele): temp[int((arr[i] - min_ele) / rnge) - 1].append(arr[i]) else: temp[int((arr[i] - min_ele) / rnge)].append(arr[i]) # Sort each bucket individually for i in range(len(temp)): if len(temp[i]) != 0: temp[i].sort() # Gather sorted elements # to the original array k = 0 for lst in temp: if lst: for i in lst: arr[k] = i k = k+1 # Driver Codearr = [9.8, 0.6, 10.1, 1.9, 3.07, 3.04, 5.0, 8.0, 4.8, 7.68]noOfBuckets = 5bucketSort(arr, noOfBuckets)print(\"Sorted array: \", arr) # This code is contributed by# Vinita Yadav", "e": 9748, "s": 8511, "text": null }, { "code": null, "e": 9818, "s": 9748, "text": "Sorted array: [0.6, 1.9, 3.04, 3.07, 4.8, 5.0, 7.68, 8.0, 9.8, 10.1]" }, { "code": null, "e": 10078, "s": 9818, "text": "Bucket Sort To Sort an Array with Negative NumbersReferences: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest http://en.wikipedia.org/wiki/Bucket_sort https://youtu.be/VuXbEb5ywrUSnapshots: " }, { "code": null, "e": 10132, "s": 10078, "text": "Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: " }, { "code": null, "e": 10147, "s": 10132, "text": "Selection Sort" }, { "code": null, "e": 10159, "s": 10147, "text": "Bubble Sort" }, { "code": null, "e": 10174, "s": 10159, "text": "Insertion Sort" }, { "code": null, "e": 10185, "s": 10174, "text": "Merge Sort" }, { "code": null, "e": 10195, "s": 10185, "text": "Heap Sort" }, { "code": null, "e": 10205, "s": 10195, "text": "QuickSort" }, { "code": null, "e": 10216, "s": 10205, "text": "Radix Sort" }, { "code": null, "e": 10230, "s": 10216, "text": "Counting Sort" }, { "code": null, "e": 10240, "s": 10230, "text": "ShellSort" }, { "code": null, "e": 10364, "s": 10240, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 10375, "s": 10364, "text": "OneilHsiao" }, { "code": null, "e": 10395, "s": 10375, "text": "himangshushekharjha" }, { "code": null, "e": 10408, "s": 10395, "text": "Akanksha_Rai" }, { "code": null, "e": 10421, "s": 10408, "text": "architbubber" }, { "code": null, "e": 10430, "s": 10421, "text": "vinita07" }, { "code": null, "e": 10440, "s": 10430, "text": "rutvik_56" }, { "code": null, "e": 10457, "s": 10440, "text": "arorakashish0911" }, { "code": null, "e": 10469, "s": 10457, "text": "unknown2108" }, { "code": null, "e": 10481, "s": 10469, "text": "asmitwrites" }, { "code": null, "e": 10489, "s": 10481, "text": "Sorting" }, { "code": null, "e": 10497, "s": 10489, "text": "Sorting" }, { "code": null, "e": 10595, "s": 10497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10651, "s": 10595, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 10675, "s": 10651, "text": "Merge two sorted arrays" }, { "code": null, "e": 10736, "s": 10675, "text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem" }, { "code": null, "e": 10767, "s": 10736, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 10808, "s": 10767, "text": "Find a triplet that sum to a given value" }, { "code": null, "e": 10852, "s": 10808, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 10869, "s": 10852, "text": "sort() in Python" }, { "code": null, "e": 10897, "s": 10869, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 10947, "s": 10897, "text": "Minimum number of swaps required to sort an array" } ]
Lodash _.isObject() Method
05 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.isObject() method is used to find whether the given value is an object or not. It returns a Boolean value True if the given value parameter is an object and returns False otherwise. Syntax: _.isObject(value) Parameters: This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value to check. Return Value: This method returns true if the value is an object, else false. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.isObject() // method console.log(_.isObject('GeeksforGeeks')); console.log(_.isObject(1)); console.log(_.isObject([1, 2, 3])); Output: false false true Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.isObject() // method console.log(_.isObject({})); console.log(_.isObject(null)); console.log(_.isObject(_.noop)); Output: true false true JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 168, "s": 28, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 357, "s": 168, "text": "The _.isObject() method is used to find whether the given value is an object or not. It returns a Boolean value True if the given value parameter is an object and returns False otherwise. " }, { "code": null, "e": 365, "s": 357, "text": "Syntax:" }, { "code": null, "e": 383, "s": 365, "text": "_.isObject(value)" }, { "code": null, "e": 474, "s": 383, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 522, "s": 474, "text": "value: This parameter holds the value to check." }, { "code": null, "e": 600, "s": 522, "text": "Return Value: This method returns true if the value is an object, else false." }, { "code": null, "e": 697, "s": 600, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file." }, { "code": null, "e": 708, "s": 697, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isObject() // method console.log(_.isObject('GeeksforGeeks')); console.log(_.isObject(1)); console.log(_.isObject([1, 2, 3]));", "e": 918, "s": 708, "text": null }, { "code": null, "e": 926, "s": 918, "text": "Output:" }, { "code": null, "e": 943, "s": 926, "text": "false\nfalse\ntrue" }, { "code": null, "e": 956, "s": 943, "text": "Example 2: " }, { "code": null, "e": 967, "s": 956, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isObject() // method console.log(_.isObject({})); console.log(_.isObject(null)); console.log(_.isObject(_.noop)); ", "e": 1165, "s": 967, "text": null }, { "code": null, "e": 1173, "s": 1165, "text": "Output:" }, { "code": null, "e": 1189, "s": 1173, "text": "true\nfalse\ntrue" }, { "code": null, "e": 1207, "s": 1189, "text": "JavaScript-Lodash" }, { "code": null, "e": 1218, "s": 1207, "text": "JavaScript" }, { "code": null, "e": 1235, "s": 1218, "text": "Web Technologies" }, { "code": null, "e": 1333, "s": 1235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1394, "s": 1333, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1466, "s": 1394, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1506, "s": 1466, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1547, "s": 1506, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1593, "s": 1547, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 1655, "s": 1593, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1688, "s": 1655, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1749, "s": 1688, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1799, "s": 1749, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Mathematics | Power Set and its Properties
23 Feb, 2022 Prerequisite – Introduction of Set theory, Set Operations (Set theory) For a given set S, Power set P(S) or 2^S represents the set containing all possible subsets of S as its elements. For example, S = {1, 2, 3} P(S) = {ɸ, {1}, {2}, {3} {1,2}, {1,3}, {2,3}, {1,2,3}} Number of Elements in Power Set – For a given set S with n elements, number of elements in P(S) is 2^n. As each element has two possibilities (present or absent}, possible subsets are 2×2×2.. n times = 2^n. Therefore, power set contains 2^n elements. Note – Power set of a finite set is finite. Set S is an element of power set of S which can be written as S ɛ P(S). Empty Set ɸ is an element of power set of S which can be written as ɸ ɛ P(S). Empty set ɸ is subset of power set of S which can be written as ɸ ⊂ P(S). Let us discuss the questions based on power set. Q1. The cardinality of the power set of {0, 1, 2 . . ., 10} is _________. (A) 1024 (B) 1023 (C) 2048 (D) 2043 Solution: The cardinality of a set is the number of elements contained. For a set S with n elements, its power set contains 2^n elements. For n = 11, size of power set is 2^11 = 2048. Q2. For a set A, the power set of A is denoted by 2^A. If A = {5, {6}, {7}}, which of the following options are True. I.Φ ε 2 A II. Φ⊆ 2 A III. {5,{6}} ε 2 A IV. {5,{6}} ⊆ 2 A (A) I and III only (B) II and III only (C) I, II and III only (D) I, II and IV only Explanation: The set A has 5, {6}, {7} has its elements. Therefore, the power set of A is: 2^S = {ɸ, {5}, {{6}}, {{7}}, {5,{6}}, {5,{7}}, {{6},{7}}, {5,{6},{7}} } Statement I is true as we can see ɸ is an element of 2^S. Statement II is true as empty set ɸ is subset of every set. Statement III is true as {5,{6}} is an element of 2^S. However, statement IV is not true as {5,{6}} is an element of 2^S and not a subset. Therefore, correct option is (C). Q3. Let P(S) denotes the power set of set S. Which of the following is always true? (a) P(P(S))=P(S) (b) P(S) ∩ P(P(S)) = { Φ } (c) P(S) ∩ S = P(S) (d) S ∉ P(S) (A) a (B) b (C) c (D) d Solution: Let us assume set S ={1, 2}. Therefore P(S) = { ɸ, {1}, {2}, {1,2}} Option (a) is false as P(S) has 2^2 = 4 elements and P(P(S)) has 2^4 = 16 elements and they are not equivalent. Option (b) is true as intersection of P(P(S) )and P(S) is empty set. Option (c) is false as intersection of S and P(S) is empty set. Option (d) is false as S is an element of P(S). Countable set and its power set – A set is called countable when its element can be counted. A countable set can be finite or infinite. For example, set S1 = {a, e, i, o, u} representing vowels is a countably finite set. However, S2 = {1, 2, 3......} representing set of natural numbers is a countably infinite set. Note – Power set of countably finite set is finite and hence countable. For example, set S1 representing vowels has 5 elements and its power set contains 2^5 = 32 elements. Therefore, it is finite and hence countable. Power set of countably infinite set is uncountable. For example, set S2 representing set of natural numbers is countably infinite. However, its power set is uncountable. Uncountable set and its power set – A set is called uncountable when its element can’t be counted. An uncountable set can be always infinite. For example, set S3 containing all real numbers between 1 and 10 is uncountable. Note – Power set of uncountable set is always uncountable. For example, set S3 representing all real numbers between 1 and 10 is uncountable. Therefore, power set of uncountable set is also uncountable. Let us discuss gate questions on this. Q4. Let ∑ be a finite non-empty alphabet and let 2^∑* be the power set of ∑*. Which of the following is true? (A). Both 2^∑* and ∑* are countable (B). 2^∑* is countable and ∑* is uncountable (C). 2^∑* is uncountable and ∑* is countable (D). Both 2^∑* and ∑* are uncountable Solution: Let ∑ = {a, b} then ∑* = { ε, a, b, aa, ba, bb, ...................}. As we can see, ∑* is countably infinite and hence countable. But power set of countably infinite set is uncountable. Therefore, 2^∑* is uncountable. So, the correct option is (C). hell_yeah1 HanzalaSohrab nilanjanad17 phanee5 Discrete Mathematics Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Feb, 2022" }, { "code": null, "e": 321, "s": 53, "text": "Prerequisite – Introduction of Set theory, Set Operations (Set theory) For a given set S, Power set P(S) or 2^S represents the set containing all possible subsets of S as its elements. For example, S = {1, 2, 3} P(S) = {ɸ, {1}, {2}, {3} {1,2}, {1,3}, {2,3}, {1,2,3}} " }, { "code": null, "e": 573, "s": 321, "text": "Number of Elements in Power Set – For a given set S with n elements, number of elements in P(S) is 2^n. As each element has two possibilities (present or absent}, possible subsets are 2×2×2.. n times = 2^n. Therefore, power set contains 2^n elements. " }, { "code": null, "e": 581, "s": 573, "text": "Note – " }, { "code": null, "e": 618, "s": 581, "text": "Power set of a finite set is finite." }, { "code": null, "e": 690, "s": 618, "text": "Set S is an element of power set of S which can be written as S ɛ P(S)." }, { "code": null, "e": 768, "s": 690, "text": "Empty Set ɸ is an element of power set of S which can be written as ɸ ɛ P(S)." }, { "code": null, "e": 842, "s": 768, "text": "Empty set ɸ is subset of power set of S which can be written as ɸ ⊂ P(S)." }, { "code": null, "e": 892, "s": 842, "text": "Let us discuss the questions based on power set. " }, { "code": null, "e": 1003, "s": 892, "text": "Q1. The cardinality of the power set of {0, 1, 2 . . ., 10} is _________. (A) 1024 (B) 1023 (C) 2048 (D) 2043 " }, { "code": null, "e": 1188, "s": 1003, "text": "Solution: The cardinality of a set is the number of elements contained. For a set S with n elements, its power set contains 2^n elements. For n = 11, size of power set is 2^11 = 2048. " }, { "code": null, "e": 1307, "s": 1188, "text": "Q2. For a set A, the power set of A is denoted by 2^A. If A = {5, {6}, {7}}, which of the following options are True. " }, { "code": null, "e": 1387, "s": 1307, "text": "I.Φ ε 2 A II. Φ⊆ 2 A III. {5,{6}} ε 2 A IV. {5,{6}} ⊆ 2 A " }, { "code": null, "e": 1472, "s": 1387, "text": "(A) I and III only (B) II and III only (C) I, II and III only (D) I, II and IV only " }, { "code": null, "e": 1564, "s": 1472, "text": "Explanation: The set A has 5, {6}, {7} has its elements. Therefore, the power set of A is: " }, { "code": null, "e": 1637, "s": 1564, "text": "2^S = {ɸ, {5}, {{6}}, {{7}}, {5,{6}}, {5,{7}}, {{6},{7}}, {5,{6},{7}} } " }, { "code": null, "e": 1929, "s": 1637, "text": "Statement I is true as we can see ɸ is an element of 2^S. Statement II is true as empty set ɸ is subset of every set. Statement III is true as {5,{6}} is an element of 2^S. However, statement IV is not true as {5,{6}} is an element of 2^S and not a subset. Therefore, correct option is (C). " }, { "code": null, "e": 2015, "s": 1929, "text": "Q3. Let P(S) denotes the power set of set S. Which of the following is always true? " }, { "code": null, "e": 2108, "s": 2015, "text": "(a) P(P(S))=P(S) (b) P(S) ∩ P(P(S)) = { Φ }\n(c) P(S) ∩ S = P(S) (d) S ∉ P(S)" }, { "code": null, "e": 2133, "s": 2108, "text": "(A) a (B) b (C) c (D) d " }, { "code": null, "e": 2505, "s": 2133, "text": "Solution: Let us assume set S ={1, 2}. Therefore P(S) = { ɸ, {1}, {2}, {1,2}} Option (a) is false as P(S) has 2^2 = 4 elements and P(P(S)) has 2^4 = 16 elements and they are not equivalent. Option (b) is true as intersection of P(P(S) )and P(S) is empty set. Option (c) is false as intersection of S and P(S) is empty set. Option (d) is false as S is an element of P(S). " }, { "code": null, "e": 2822, "s": 2505, "text": "Countable set and its power set – A set is called countable when its element can be counted. A countable set can be finite or infinite. For example, set S1 = {a, e, i, o, u} representing vowels is a countably finite set. However, S2 = {1, 2, 3......} representing set of natural numbers is a countably infinite set. " }, { "code": null, "e": 2830, "s": 2822, "text": "Note – " }, { "code": null, "e": 3041, "s": 2830, "text": "Power set of countably finite set is finite and hence countable. For example, set S1 representing vowels has 5 elements and its power set contains 2^5 = 32 elements. Therefore, it is finite and hence countable." }, { "code": null, "e": 3211, "s": 3041, "text": "Power set of countably infinite set is uncountable. For example, set S2 representing set of natural numbers is countably infinite. However, its power set is uncountable." }, { "code": null, "e": 3435, "s": 3211, "text": "Uncountable set and its power set – A set is called uncountable when its element can’t be counted. An uncountable set can be always infinite. For example, set S3 containing all real numbers between 1 and 10 is uncountable. " }, { "code": null, "e": 3443, "s": 3435, "text": "Note – " }, { "code": null, "e": 3641, "s": 3443, "text": "Power set of uncountable set is always uncountable. For example, set S3 representing all real numbers between 1 and 10 is uncountable. Therefore, power set of uncountable set is also uncountable. " }, { "code": null, "e": 3681, "s": 3641, "text": "Let us discuss gate questions on this. " }, { "code": null, "e": 3793, "s": 3681, "text": "Q4. Let ∑ be a finite non-empty alphabet and let 2^∑* be the power set of ∑*. Which of the following is true? " }, { "code": null, "e": 3964, "s": 3793, "text": "(A). Both 2^∑* and ∑* are countable \n(B). 2^∑* is countable and ∑* is uncountable\n(C). 2^∑* is uncountable and ∑* is countable \n(D). Both 2^∑* and ∑* are uncountable" }, { "code": null, "e": 4225, "s": 3964, "text": "Solution: Let ∑ = {a, b} then ∑* = { ε, a, b, aa, ba, bb, ...................}. As we can see, ∑* is countably infinite and hence countable. But power set of countably infinite set is uncountable. Therefore, 2^∑* is uncountable. So, the correct option is (C). " }, { "code": null, "e": 4236, "s": 4225, "text": "hell_yeah1" }, { "code": null, "e": 4250, "s": 4236, "text": "HanzalaSohrab" }, { "code": null, "e": 4263, "s": 4250, "text": "nilanjanad17" }, { "code": null, "e": 4271, "s": 4263, "text": "phanee5" }, { "code": null, "e": 4292, "s": 4271, "text": "Discrete Mathematics" }, { "code": null, "e": 4316, "s": 4292, "text": "Engineering Mathematics" }, { "code": null, "e": 4324, "s": 4316, "text": "GATE CS" }, { "code": null, "e": 4422, "s": 4324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4444, "s": 4422, "text": "Inequalities in LaTeX" }, { "code": null, "e": 4503, "s": 4444, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 4526, "s": 4503, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 4549, "s": 4526, "text": "Set Notations in LaTeX" }, { "code": null, "e": 4570, "s": 4549, "text": "Activation Functions" }, { "code": null, "e": 4590, "s": 4570, "text": "Layers of OSI Model" }, { "code": null, "e": 4614, "s": 4590, "text": "ACID Properties in DBMS" }, { "code": null, "e": 4627, "s": 4614, "text": "TCP/IP Model" }, { "code": null, "e": 4654, "s": 4627, "text": "Types of Operating Systems" } ]
Angular7 - Modules
Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application. In case you are developing a website, the header, footer, left, center and the right section become part of a module. To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; @NgModule({ declarations: [ AppComponent, NewCmpComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The NgModule needs to be imported as follows − import { NgModule } from '@angular/core'; The structure for the ngmodule is as shown below − @NgModule({ declarations: [ AppComponent, NewCmpComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations, imports, providers and bootstrap. It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below − declarations: [ AppComponent, NewCmpComponent ] It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule, we see the Browser Module imported. In case your application needs forms, you can include the module with the below code − import { FormsModule } from '@angular/forms'; The import in the @NgModule will be like the following − imports: [ BrowserModule, FormsModule ] This will include the services created. This includes the main app component for starting the execution. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2204, "s": 2061, "text": "Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application." }, { "code": null, "e": 2322, "s": 2204, "text": "In case you are developing a website, the header, footer, left, center and the right section become part of a module." }, { "code": null, "e": 2514, "s": 2322, "text": "To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows −" }, { "code": null, "e": 3004, "s": 2514, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\n\n@NgModule({\n declarations: [\n AppComponent,\n NewCmpComponent\n ],\n imports: [\n BrowserModule,\n AppRoutingModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 3051, "s": 3004, "text": "The NgModule needs to be imported as follows −" }, { "code": null, "e": 3094, "s": 3051, "text": "import { NgModule } from '@angular/core';\n" }, { "code": null, "e": 3145, "s": 3094, "text": "The structure for the ngmodule is as shown below −" }, { "code": null, "e": 3347, "s": 3145, "text": "@NgModule({ \n declarations: [\n AppComponent, \n NewCmpComponent \n ],\n imports: [ \n BrowserModule, \n AppRoutingModule \n ], \n providers: [], \n bootstrap: [AppComponent] \n})" }, { "code": null, "e": 3453, "s": 3347, "text": "It starts with @NgModule and contains an object which has declarations, imports, providers and bootstrap." }, { "code": null, "e": 3620, "s": 3453, "text": "It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below −" }, { "code": null, "e": 3679, "s": 3620, "text": "declarations: [ \n AppComponent, \n NewCmpComponent \n]\n" }, { "code": null, "e": 3973, "s": 3679, "text": "It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule, we see the Browser Module imported. In case your application needs forms, you can include the module with the below code −" }, { "code": null, "e": 4020, "s": 3973, "text": "import { FormsModule } from '@angular/forms';\n" }, { "code": null, "e": 4077, "s": 4020, "text": "The import in the @NgModule will be like the following −" }, { "code": null, "e": 4127, "s": 4077, "text": "imports: [ \n BrowserModule, \n FormsModule \n]\n" }, { "code": null, "e": 4167, "s": 4127, "text": "This will include the services created." }, { "code": null, "e": 4232, "s": 4167, "text": "This includes the main app component for starting the execution." }, { "code": null, "e": 4267, "s": 4232, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4281, "s": 4267, "text": " Anadi Sharma" }, { "code": null, "e": 4316, "s": 4281, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4330, "s": 4316, "text": " Anadi Sharma" }, { "code": null, "e": 4365, "s": 4330, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4385, "s": 4365, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4420, "s": 4385, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4437, "s": 4420, "text": " Frahaan Hussain" }, { "code": null, "e": 4470, "s": 4437, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4482, "s": 4470, "text": " Senol Atac" }, { "code": null, "e": 4517, "s": 4482, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4529, "s": 4517, "text": " Senol Atac" }, { "code": null, "e": 4536, "s": 4529, "text": " Print" }, { "code": null, "e": 4547, "s": 4536, "text": " Add Notes" } ]
Find maximum value from a VARCHAR column in MySQL
To find maximum value, use MAX() along with CAST(), since the values are of VARCHAR type. Let us first create a table − mysql> create table DemoTable2030 -> ( -> Value varchar(20) -> ); Query OK, 0 rows affected (0.44 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2030 values('8'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2030 values('1'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable2030 values('10001'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable2030 values('901'); Query OK, 1 row affected (0.22 sec) Display all records from the table using select statement &miuns; mysql> select *from DemoTable2030 This will produce the following output − +-------+ | Value | +-------+ | 8 | | 1 | | 10001 | | 901 | +-------+ 4 rows in set (0.00 sec) Following is the query to find maximum value from a VARCHAR column − mysql> select max(cast(Value as unsigned)) from DemoTable2030; This will produce the following output − +------------------------------+ | max(cast(Value as unsigned)) | +------------------------------+ | 10001 | +------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1182, "s": 1062, "text": "To find maximum value, use MAX() along with CAST(), since the values are of VARCHAR type. Let us first create a table −" }, { "code": null, "e": 1294, "s": 1182, "text": "mysql> create table DemoTable2030\n -> (\n -> Value varchar(20)\n -> );\nQuery OK, 0 rows affected (0.44 sec)" }, { "code": null, "e": 1350, "s": 1294, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1687, "s": 1350, "text": "mysql> insert into DemoTable2030 values('8');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable2030 values('1');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable2030 values('10001');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable2030 values('901');\nQuery OK, 1 row affected (0.22 sec)" }, { "code": null, "e": 1753, "s": 1687, "text": "Display all records from the table using select statement &miuns;" }, { "code": null, "e": 1787, "s": 1753, "text": "mysql> select *from DemoTable2030" }, { "code": null, "e": 1828, "s": 1787, "text": "This will produce the following output −" }, { "code": null, "e": 1933, "s": 1828, "text": "+-------+\n| Value |\n+-------+\n| 8 |\n| 1 |\n| 10001 |\n| 901 |\n+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2002, "s": 1933, "text": "Following is the query to find maximum value from a VARCHAR column −" }, { "code": null, "e": 2065, "s": 2002, "text": "mysql> select max(cast(Value as unsigned)) from DemoTable2030;" }, { "code": null, "e": 2106, "s": 2065, "text": "This will produce the following output −" }, { "code": null, "e": 2295, "s": 2106, "text": "+------------------------------+\n| max(cast(Value as unsigned)) |\n+------------------------------+\n| 10001 |\n+------------------------------+\n1 row in set (0.00 sec)" } ]
Python - Check if all elements in a List are same
Sometimes we come across the need to check if we have one single value repeated in a list as list elements. We can check for such scenario using the below python programs. There are different approaches. In this method we grab the first element from the list and use a traditional for loop to keep comparing each element with the first element. If the value does not match for any element then we come out of the loop and the result is false. Live Demo List = ['Mon','Mon','Mon','Mon'] result = True # Get the first element first_element = List[0] # Compares all the elements with the first element for word in List: if first_element != word: result = False print("All elements are not equal") break else: result = True if result: print("All elements are equal") Running the above code gives us the following result − All elements are equal All elements are equal All elements are equal All elements are equal The all() method applies the comparison for each element in the list. It is similar to what we have done in first approach but instead of for loop, we are using the all() method. Live Demo List = ['Mon','Mon','Tue','Mon'] # Uisng all()method result = all(element == List[0] for element in List) if (result): print("All the elements are Equal") else: print("All Elements are not equal") Running the above code gives us the following result − All the elements are not Equal The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic. Live Demo List = ['Mon','Mon','Mon','Mon'] # Result from count matches with result from len() result = List.count(List[0]) == len(List) if (result): print("All the elements are Equal") else: print("Elements are not equal") Running the above code gives us the following result − All the elements are Equal
[ { "code": null, "e": 1266, "s": 1062, "text": "Sometimes we come across the need to check if we have one single value repeated in a list as list elements. We can check for such scenario using the below python programs. There are different approaches." }, { "code": null, "e": 1505, "s": 1266, "text": "In this method we grab the first element from the list and use a traditional for loop to keep comparing each element with the first element. If the value does not match for any element then we come out of the loop and the result is false." }, { "code": null, "e": 1516, "s": 1505, "text": " Live Demo" }, { "code": null, "e": 1865, "s": 1516, "text": "List = ['Mon','Mon','Mon','Mon']\nresult = True\n# Get the first element\nfirst_element = List[0]\n# Compares all the elements with the first element\nfor word in List:\n if first_element != word:\n result = False\n print(\"All elements are not equal\")\n break\n else:\n result = True\n if result:\n print(\"All elements are equal\")" }, { "code": null, "e": 1920, "s": 1865, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2014, "s": 1920, "text": "All elements are equal\nAll elements are equal \nAll elements are equal \nAll elements are equal" }, { "code": null, "e": 2193, "s": 2014, "text": "The all() method applies the comparison for each element in the list. It is similar to what we have done in first approach but instead of for loop, we are using the all() method." }, { "code": null, "e": 2204, "s": 2193, "text": " Live Demo" }, { "code": null, "e": 2407, "s": 2204, "text": "List = ['Mon','Mon','Tue','Mon']\n# Uisng all()method\nresult = all(element == List[0] for element in List)\nif (result):\n print(\"All the elements are Equal\")\nelse:\n print(\"All Elements are not equal\")" }, { "code": null, "e": 2462, "s": 2407, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2493, "s": 2462, "text": "All the elements are not Equal" }, { "code": null, "e": 2800, "s": 2493, "text": "The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic." }, { "code": null, "e": 2811, "s": 2800, "text": " Live Demo" }, { "code": null, "e": 3030, "s": 2811, "text": "List = ['Mon','Mon','Mon','Mon']\n# Result from count matches with result from len()\nresult = List.count(List[0]) == len(List)\nif (result):\n print(\"All the elements are Equal\")\nelse:\n print(\"Elements are not equal\")" }, { "code": null, "e": 3085, "s": 3030, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3112, "s": 3085, "text": "All the elements are Equal" } ]
Java String subSequence() method with Examples - GeeksforGeeks
04 Dec, 2018 The Java.lang.String.subSequence() is a built-in function in Java that returns a CharSequence. CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at (end-1). The length (in chars) of the returned sequence is (end-start, so if start == end then an empty sequence is returned. Syntax: public CharSequence subSequence(int start, int end) Parameters: start - This is the index from where the subsequence starts, it is inclusive. end - This is the index where the subsequence ends, it is exclusive. Returns:It returns the specified subsequence in range [start, end). Errors and Exceptions:IndexOutOfBoundsException – It throws this error if start or end are negative, if end is greater than length(), or if start is greater than end. Program 1: To show working of Java.lang.String.subSequence() function. // Java program to demonstrate working// of Java.lang.String.subSequence() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = "Welcome to geeksforgeeks"; // prints the subsequence from 0-7, exclusive 7th index System.out.print("Returns: "); System.out.println(Str.subSequence(0, 7)); System.out.print("Returns: "); System.out.println(Str.subSequence(10, 24)); }} Output: Returns: Welcome Returns: geeksforgeeks Program 2: To show error of Java.lang.String.subSequence() function when index is negative // Java program to demonstrate error// of Java.lang.String.subSequence() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = "Welcome to geeksforgeeks"; // throws an error as index is negative System.out.print("Returns: "); System.out.println(Str.subSequence(-1, 7)); }} Output: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1960) at java.lang.String.subSequence(String.java:2003) at Gfg.main(File.java:15) Program 3: To show error of Java.lang.String.subSequence() function when index is out of range. // Java program to demonstrate error// of Java.lang.String.subSequence() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = "Welcome to geeksforgeeks"; // throws an error as end is out of range System.out.print("Returns: "); System.out.println(Str.subSequence(10, 50)); }} Output: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 50 at java.lang.String.substring(String.java:1963) at java.lang.String.subSequence(String.java:2003) at Gfg.main(File.java:16) Java-Functions Java-lang package Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24635, "s": 24607, "text": "\n04 Dec, 2018" }, { "code": null, "e": 25007, "s": 24635, "text": "The Java.lang.String.subSequence() is a built-in function in Java that returns a CharSequence. CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at (end-1). The length (in chars) of the returned sequence is (end-start, so if start == end then an empty sequence is returned." }, { "code": null, "e": 25015, "s": 25007, "text": "Syntax:" }, { "code": null, "e": 25229, "s": 25015, "text": "public CharSequence subSequence(int start, int end) \nParameters: \nstart - This is the index from where the subsequence starts, it is inclusive.\nend - This is the index where the subsequence ends, it is exclusive.\n" }, { "code": null, "e": 25297, "s": 25229, "text": "Returns:It returns the specified subsequence in range [start, end)." }, { "code": null, "e": 25464, "s": 25297, "text": "Errors and Exceptions:IndexOutOfBoundsException – It throws this error if start or end are negative, if end is greater than length(), or if start is greater than end." }, { "code": null, "e": 25535, "s": 25464, "text": "Program 1: To show working of Java.lang.String.subSequence() function." }, { "code": "// Java program to demonstrate working// of Java.lang.String.subSequence() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = \"Welcome to geeksforgeeks\"; // prints the subsequence from 0-7, exclusive 7th index System.out.print(\"Returns: \"); System.out.println(Str.subSequence(0, 7)); System.out.print(\"Returns: \"); System.out.println(Str.subSequence(10, 24)); }}", "e": 26020, "s": 25535, "text": null }, { "code": null, "e": 26028, "s": 26020, "text": "Output:" }, { "code": null, "e": 26070, "s": 26028, "text": "Returns: Welcome\nReturns: geeksforgeeks\n" }, { "code": null, "e": 26161, "s": 26070, "text": "Program 2: To show error of Java.lang.String.subSequence() function when index is negative" }, { "code": "// Java program to demonstrate error// of Java.lang.String.subSequence() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = \"Welcome to geeksforgeeks\"; // throws an error as index is negative System.out.print(\"Returns: \"); System.out.println(Str.subSequence(-1, 7)); }}", "e": 26537, "s": 26161, "text": null }, { "code": null, "e": 26545, "s": 26537, "text": "Output:" }, { "code": null, "e": 26783, "s": 26545, "text": "Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: \nString index out of range: -1\n at java.lang.String.substring(String.java:1960)\n at java.lang.String.subSequence(String.java:2003)\n at Gfg.main(File.java:15)\n" }, { "code": null, "e": 26879, "s": 26783, "text": "Program 3: To show error of Java.lang.String.subSequence() function when index is out of range." }, { "code": "// Java program to demonstrate error// of Java.lang.String.subSequence() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = \"Welcome to geeksforgeeks\"; // throws an error as end is out of range System.out.print(\"Returns: \"); System.out.println(Str.subSequence(10, 50)); }}", "e": 27258, "s": 26879, "text": null }, { "code": null, "e": 27266, "s": 27258, "text": "Output:" }, { "code": null, "e": 27504, "s": 27266, "text": "Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: \nString index out of range: 50\n at java.lang.String.substring(String.java:1963)\n at java.lang.String.subSequence(String.java:2003)\n at Gfg.main(File.java:16)\n" }, { "code": null, "e": 27519, "s": 27504, "text": "Java-Functions" }, { "code": null, "e": 27537, "s": 27519, "text": "Java-lang package" }, { "code": null, "e": 27550, "s": 27537, "text": "Java-Strings" }, { "code": null, "e": 27555, "s": 27550, "text": "Java" }, { "code": null, "e": 27568, "s": 27555, "text": "Java-Strings" }, { "code": null, "e": 27573, "s": 27568, "text": "Java" }, { "code": null, "e": 27671, "s": 27573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27680, "s": 27671, "text": "Comments" }, { "code": null, "e": 27693, "s": 27680, "text": "Old Comments" }, { "code": null, "e": 27744, "s": 27693, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27774, "s": 27744, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27805, "s": 27774, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27837, "s": 27805, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27856, "s": 27837, "text": "Interfaces in Java" }, { "code": null, "e": 27874, "s": 27856, "text": "ArrayList in Java" }, { "code": null, "e": 27906, "s": 27874, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27926, "s": 27906, "text": "Stack Class in Java" }, { "code": null, "e": 27950, "s": 27926, "text": "Singleton Class in Java" } ]
Rexx - do Loop
The do loop is used to execute a number of statements for a certain number of times. The number of times that the statement needs to be executed is determined by the value passed to the do loop. The syntax of the do loop statement is as follows − do count statement #1 statement #2 ... End Statement#1 and Statement#2 are a series of a block of statements that get executed in the do loop. The count variable symbolizes the number of times the do loop needs to be executed. The following diagram shows the diagrammatic explanation of this loop. The key point to note about this loop is that the do loop will execute based on the value of the count variable. The following program is an example of a do loop statement. /* Main program */ do 5 say "hello" end The following key points need to be noted about the above program − The count in the above case is 5. So the do loop will be run for 5 times. The count in the above case is 5. So the do loop will be run for 5 times. In the do loop, the phrase hello is displayed to the console. In the do loop, the phrase hello is displayed to the console. The output of the above program will be − hello hello hello hello hello Print Add Notes Bookmark this page
[ { "code": null, "e": 2534, "s": 2339, "text": "The do loop is used to execute a number of statements for a certain number of times. The number of times that the statement needs to be executed is determined by the value passed to the do loop." }, { "code": null, "e": 2586, "s": 2534, "text": "The syntax of the do loop statement is as follows −" }, { "code": null, "e": 2644, "s": 2586, "text": "do count \n statement #1 \n statement #2 \n ... \nEnd \n" }, { "code": null, "e": 2828, "s": 2644, "text": "Statement#1 and Statement#2 are a series of a block of statements that get executed in the do loop. The count variable symbolizes the number of times the do loop needs to be executed." }, { "code": null, "e": 2899, "s": 2828, "text": "The following diagram shows the diagrammatic explanation of this loop." }, { "code": null, "e": 3012, "s": 2899, "text": "The key point to note about this loop is that the do loop will execute based on the value of the count variable." }, { "code": null, "e": 3072, "s": 3012, "text": "The following program is an example of a do loop statement." }, { "code": null, "e": 3119, "s": 3072, "text": "/* Main program */ \ndo 5 \n say \"hello\" \nend " }, { "code": null, "e": 3187, "s": 3119, "text": "The following key points need to be noted about the above program −" }, { "code": null, "e": 3261, "s": 3187, "text": "The count in the above case is 5. So the do loop will be run for 5 times." }, { "code": null, "e": 3335, "s": 3261, "text": "The count in the above case is 5. So the do loop will be run for 5 times." }, { "code": null, "e": 3397, "s": 3335, "text": "In the do loop, the phrase hello is displayed to the console." }, { "code": null, "e": 3459, "s": 3397, "text": "In the do loop, the phrase hello is displayed to the console." }, { "code": null, "e": 3501, "s": 3459, "text": "The output of the above program will be −" }, { "code": null, "e": 3537, "s": 3501, "text": "hello \nhello \nhello \nhello \nhello \n" }, { "code": null, "e": 3544, "s": 3537, "text": " Print" }, { "code": null, "e": 3555, "s": 3544, "text": " Add Notes" } ]
PHP | join() Function
08 Jan, 2018 The join() function is built-in function in PHP and is used to join an array of elements which are separated by a string. Syntax string join( $separator, $array) Parameter: The join() function accepts two parameter out of which one is optional and one is mandatory. $separator : This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the $separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string) $array : The array whose value is to be joined to form a string. Return Type: The return type of join() function is string. It will return the joined string formed from the elements of $array. Examples: Input : join(array('Geeks','for','Geeks') Output : GeeksforGeeks Input : join("-",array('Geeks','for','Geeks') Output : Geeks-for-Geeks Below program illustrates the working of join() function in PHP: <?php // PHP Code to implement join function $InputArray = array('Geeks','for','Geeks'); // Join without separator print_r(join($InputArray)); print_r("\n"); // Join with separator print_r(join("-",$InputArray));?> Output: GeeksforGeeks Geeks-for-Geeks Functions PHP-string Web Technologies Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to create footer to stay at the bottom of a Web page? Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? File uploading in React.js
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2018" }, { "code": null, "e": 150, "s": 28, "text": "The join() function is built-in function in PHP and is used to join an array of elements which are separated by a string." }, { "code": null, "e": 157, "s": 150, "text": "Syntax" }, { "code": null, "e": 190, "s": 157, "text": "string join( $separator, $array)" }, { "code": null, "e": 294, "s": 190, "text": "Parameter: The join() function accepts two parameter out of which one is optional and one is mandatory." }, { "code": null, "e": 554, "s": 294, "text": "$separator : This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the $separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string)" }, { "code": null, "e": 619, "s": 554, "text": "$array : The array whose value is to be joined to form a string." }, { "code": null, "e": 747, "s": 619, "text": "Return Type: The return type of join() function is string. It will return the joined string formed from the elements of $array." }, { "code": null, "e": 757, "s": 747, "text": "Examples:" }, { "code": null, "e": 895, "s": 757, "text": "Input : join(array('Geeks','for','Geeks')\nOutput : GeeksforGeeks\n\nInput : join(\"-\",array('Geeks','for','Geeks')\nOutput : Geeks-for-Geeks\n" }, { "code": null, "e": 960, "s": 895, "text": "Below program illustrates the working of join() function in PHP:" }, { "code": "<?php // PHP Code to implement join function $InputArray = array('Geeks','for','Geeks'); // Join without separator print_r(join($InputArray)); print_r(\"\\n\"); // Join with separator print_r(join(\"-\",$InputArray));?>", "e": 1220, "s": 960, "text": null }, { "code": null, "e": 1228, "s": 1220, "text": "Output:" }, { "code": null, "e": 1259, "s": 1228, "text": "GeeksforGeeks\nGeeks-for-Geeks\n" }, { "code": null, "e": 1269, "s": 1259, "text": "Functions" }, { "code": null, "e": 1280, "s": 1269, "text": "PHP-string" }, { "code": null, "e": 1297, "s": 1280, "text": "Web Technologies" }, { "code": null, "e": 1307, "s": 1297, "text": "Functions" }, { "code": null, "e": 1405, "s": 1307, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1466, "s": 1405, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1509, "s": 1466, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1581, "s": 1509, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1621, "s": 1581, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1645, "s": 1621, "text": "REST API (Introduction)" }, { "code": null, "e": 1678, "s": 1645, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1736, "s": 1678, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 1777, "s": 1736, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1823, "s": 1777, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Edge detection using in-built function in MATLAB
25 Aug, 2021 Edge detection: In an image, an edge is a curve that follows a path of rapid change in intensity of that image. Edges are often associated with the boundaries of the object in a scene environment. Edge detection is used to identify the edges in an image to make image processing easy. Edge detection works by detecting discontinuities in brightness. Edge detection is mainly used for image segmentation and data extraction in areas such as image processing, computer vision, and machine vision. To find edges, you can use the in-built edge function edge(image, Edge detector) of Matlab. This in-built function looks for places in the image where the intensity changes rapidly, using one of these two criteria: Places where the first derivative of the intensity is larger in magnitude than some threshold value. Places where the second derivative of the intensity has a zero crossing. Edge detectors provide several derivative estimators, each of which implements one of the above stated definitions. For some of these estimators, you can specify whether the operation should be sensitive to vertical edges, horizontal edges, or both. Edge estimators return a binary image containing 1’s where edges are found and 0’s elsewhere. The most powerful edge-detection technique that edge provides is the Canny method. The Canny method differs from the other edge-detection methods in that it uses two different types of thresholds levels to detect strong and weak edges. The Canny edge detection method includes the weak edges in the output only if they are connected to strong edges. This method is, therefore, less likely to be affected by noise, and more likely to detect true weak edges. There are many Edge detection in-built functions are available in Matlab like: Sobel edge detector Prewitt edge detector Robert edge detector Log edge detector Zerocross edge detector Canny edge detector Edge detection using MATLAB library function. Matlab % importing the imageI = rgb2gray(imread("flowers.jpg"));subplot(2, 4, 1),imshow(I);title("Gray Scale Image"); % Sobel Edge DetectionJ = edge(I, 'Sobel');subplot(2, 4, 2),imshow(J);title("Sobel"); % Prewitt Edge detectionK = edge(I, 'Prewitt');subplot(2, 4, 3),imshow(K);title("Prewitt"); % Robert Edge DetectionL = edge(I, 'Roberts');subplot(2, 4, 4),imshow(L);title("Robert"); % Log Edge DetectionM = edge(I, 'log');subplot(2, 4, 5),imshow(M);title("Log"); % Zerocross Edge DetectionM = edge(I, 'zerocross');subplot(2, 4, 6),imshow(M);title("Zerocross"); % Canny Edge DetectionN = edge(I, 'Canny');subplot(2, 4, 7),imshow(N);title("Canny"); Output: sagartomar9927 Image-Processing MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture Fuzzy Logic | Introduction Mounting a Volume Inside Docker Container
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Aug, 2021" }, { "code": null, "e": 549, "s": 53, "text": "Edge detection: In an image, an edge is a curve that follows a path of rapid change in intensity of that image. Edges are often associated with the boundaries of the object in a scene environment. Edge detection is used to identify the edges in an image to make image processing easy. Edge detection works by detecting discontinuities in brightness. Edge detection is mainly used for image segmentation and data extraction in areas such as image processing, computer vision, and machine vision. " }, { "code": null, "e": 766, "s": 549, "text": "To find edges, you can use the in-built edge function edge(image, Edge detector) of Matlab. This in-built function looks for places in the image where the intensity changes rapidly, using one of these two criteria: " }, { "code": null, "e": 867, "s": 766, "text": "Places where the first derivative of the intensity is larger in magnitude than some threshold value." }, { "code": null, "e": 940, "s": 867, "text": "Places where the second derivative of the intensity has a zero crossing." }, { "code": null, "e": 1285, "s": 940, "text": "Edge detectors provide several derivative estimators, each of which implements one of the above stated definitions. For some of these estimators, you can specify whether the operation should be sensitive to vertical edges, horizontal edges, or both. Edge estimators return a binary image containing 1’s where edges are found and 0’s elsewhere. " }, { "code": null, "e": 1743, "s": 1285, "text": "The most powerful edge-detection technique that edge provides is the Canny method. The Canny method differs from the other edge-detection methods in that it uses two different types of thresholds levels to detect strong and weak edges. The Canny edge detection method includes the weak edges in the output only if they are connected to strong edges. This method is, therefore, less likely to be affected by noise, and more likely to detect true weak edges. " }, { "code": null, "e": 1824, "s": 1743, "text": "There are many Edge detection in-built functions are available in Matlab like: " }, { "code": null, "e": 1844, "s": 1824, "text": "Sobel edge detector" }, { "code": null, "e": 1866, "s": 1844, "text": "Prewitt edge detector" }, { "code": null, "e": 1887, "s": 1866, "text": "Robert edge detector" }, { "code": null, "e": 1905, "s": 1887, "text": "Log edge detector" }, { "code": null, "e": 1929, "s": 1905, "text": "Zerocross edge detector" }, { "code": null, "e": 1949, "s": 1929, "text": "Canny edge detector" }, { "code": null, "e": 1996, "s": 1949, "text": "Edge detection using MATLAB library function. " }, { "code": null, "e": 2003, "s": 1996, "text": "Matlab" }, { "code": "% importing the imageI = rgb2gray(imread(\"flowers.jpg\"));subplot(2, 4, 1),imshow(I);title(\"Gray Scale Image\"); % Sobel Edge DetectionJ = edge(I, 'Sobel');subplot(2, 4, 2),imshow(J);title(\"Sobel\"); % Prewitt Edge detectionK = edge(I, 'Prewitt');subplot(2, 4, 3),imshow(K);title(\"Prewitt\"); % Robert Edge DetectionL = edge(I, 'Roberts');subplot(2, 4, 4),imshow(L);title(\"Robert\"); % Log Edge DetectionM = edge(I, 'log');subplot(2, 4, 5),imshow(M);title(\"Log\"); % Zerocross Edge DetectionM = edge(I, 'zerocross');subplot(2, 4, 6),imshow(M);title(\"Zerocross\"); % Canny Edge DetectionN = edge(I, 'Canny');subplot(2, 4, 7),imshow(N);title(\"Canny\");", "e": 2646, "s": 2003, "text": null }, { "code": null, "e": 2654, "s": 2646, "text": "Output:" }, { "code": null, "e": 2671, "s": 2656, "text": "sagartomar9927" }, { "code": null, "e": 2688, "s": 2671, "text": "Image-Processing" }, { "code": null, "e": 2695, "s": 2688, "text": "MATLAB" }, { "code": null, "e": 2721, "s": 2695, "text": "Advanced Computer Subject" }, { "code": null, "e": 2819, "s": 2721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2855, "s": 2819, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 2879, "s": 2855, "text": "Markov Decision Process" }, { "code": null, "e": 2915, "s": 2879, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 2959, "s": 2915, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 2994, "s": 2959, "text": "Getting Started with System Design" }, { "code": null, "e": 3035, "s": 2994, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 3083, "s": 3035, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 3124, "s": 3083, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 3151, "s": 3124, "text": "Fuzzy Logic | Introduction" } ]
Object Oriented Programming in PHP
We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects. Before we go in detail, lets define important terms related to Object Oriented Programming. Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object. Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object. Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance. Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance. Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created. Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created. Member function − These are the function defined inside a class and are used to access object data. Member function − These are the function defined inside a class and are used to access object data. Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class. Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class. Parent class − A class that is inherited from by another class. This is also called a base class or super class. Parent class − A class that is inherited from by another class. This is also called a base class or super class. Child Class − A class that inherits from another class. This is also called a subclass or derived class. Child Class − A class that inherits from another class. This is also called a subclass or derived class. Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task. Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task. Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation. Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation. Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted). Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted). Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object. Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object. Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class. Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class. Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope. Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope. The general form for defining a new class in PHP is as follows − <?php class phpClass { var $var1; var $var2 = "constant string"; function myfunc ($arg1, $arg2) { [..] } [..] } ?> Here is the description of each line − The special form class, followed by the name of the class that you want to define. The special form class, followed by the name of the class that you want to define. A set of braces enclosing any number of variable declarations and function definitions. A set of braces enclosing any number of variable declarations and function definitions. Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value. Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value. Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data. Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data. Here is an example which defines a class of Books type − <?php class Books { /* Member variables */ var $price; var $title; /* Member functions */ function setPrice($par){ $this->price = $par; } function getPrice(){ echo $this->price ."<br/>"; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title ." <br/>"; } } ?> The variable $this is a special variable and it refers to the same object ie. itself. Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator. $physics = new Books; $maths = new Books; $chemistry = new Books; Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables. After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set title and prices for the three books by calling member functions. $physics->setTitle( "Physics for High School" ); $chemistry->setTitle( "Advanced Chemistry" ); $maths->setTitle( "Algebra" ); $physics->setPrice( 10 ); $chemistry->setPrice( 15 ); $maths->setPrice( 7 ); Now you call another member functions to get the values set by in above example − $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice(); This will produce the following result − Physics for High School Advanced Chemistry Algebra 10 15 7 Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions. PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function. Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation. function __construct( $par1, $par2 ) { $this->title = $par1; $this->price = $par2; } Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below − $physics = new Books( "Physics for High School", 10 ); $maths = new Books ( "Advanced Chemistry", 15 ); $chemistry = new Books ("Algebra", 7 ); /* Get those set values */ $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice(); This will produce the following result − Physics for High School Advanced Chemistry Algebra 10 15 7 Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor. PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows − class Child extends Parent { <definition body> } The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics − Automatically has all the member variable declarations of the parent class. Automatically has all the member variable declarations of the parent class. Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent. Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent. Following example inherit Books class and adds more functionality based on the requirement. class Novel extends Books { var $publisher; function setPublisher($par){ $this->publisher = $par; } function getPublisher(){ echo $this->publisher. "<br />"; } } Now apart from inherited functions, class Novel keeps two additional member functions. Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class. In the following example getPrice and getTitle functions are overridden to return some values. function getPrice() { echo $this->price . "<br/>"; return $this->price; } function getTitle(){ echo $this->title . "<br/>"; return $this->title; } Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations − From outside the class in which it is declared From outside the class in which it is declared From within the class in which it is declared From within the class in which it is declared From within another class that implements the class in which it is declared From within another class that implements the class in which it is declared Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected. By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class. A class member can be made private by using private keyword infront of the member. class MyClass { private $car = "skoda"; $driver = "SRK"; function __construct($par) { // Statements here run every time // an instance of the class // is created. } function myPublicFunction() { return("I'm visible!"); } private function myPrivateFunction() { return("I'm not visible outside!"); } } When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private. A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member. Here is different version of MyClass − class MyClass { protected $car = "skoda"; $driver = "SRK"; function __construct($par) { // Statements here run every time // an instance of the class // is created. } function myPublicFunction() { return("I'm visible!"); } protected function myPrivateFunction() { return("I'm visible in child class!"); } } Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers. As of PHP5, it is possible to define an interface, like this − interface Mail { public function sendMail(); } Then, if another class implemented that interface, like this − class Report implements Mail { // sendMail() Definition goes here } A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change. Declaring one constant is easy, as is done in this version of MyClass − class MyClass { const requiredMargin = 1.7; function __construct($incomingValue) { // Statements here run every time // an instance of the class // is created. } } In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do. An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this − When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility. abstract class MyAbstractClass { abstract function myAbstractFunction() { } } Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class. Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can). Try out following example − <?php class Foo { public static $my_static = 'foo'; public function staticValue() { return self::$my_static; } } print Foo::$my_static . "\n"; $foo = new Foo(); print $foo->staticValue() . "\n"; ?> PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. Following example results in Fatal error: Cannot override final method BaseClass::moreTesting() <?php class BaseClass { public function test() { echo "BaseClass::test() called<br>"; } final public function moreTesting() { echo "BaseClass::moreTesting() called<br>"; } } class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called<br>"; } } ?> Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example − class Name { var $_firstName; var $_lastName; function Name($first_name, $last_name) { $this->_firstName = $first_name; $this->_lastName = $last_name; } function toString() { return($this->_lastName .", " .$this->_firstName); } } class NameSub1 extends Name { var $_middleInitial; function NameSub1($first_name, $middle_initial, $last_name) { Name::Name($first_name, $last_name); $this->_middleInitial = $middle_initial; } function toString() { return(Name::toString() . " " . $this->_middleInitial); } } In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent function that it overrides. NOTE − A constructor can be defined with the same name as the name of a class. It is defined in above example.
[ { "code": null, "e": 3205, "s": 2891, "text": "We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects." }, { "code": null, "e": 3297, "s": 3205, "text": "Before we go in detail, lets define important terms related to Object Oriented Programming." }, { "code": null, "e": 3503, "s": 3297, "text": "Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object." }, { "code": null, "e": 3709, "s": 3503, "text": "Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object." }, { "code": null, "e": 3889, "s": 3709, "text": "Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance." }, { "code": null, "e": 4069, "s": 3889, "text": "Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance." }, { "code": null, "e": 4311, "s": 4069, "text": "Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created." }, { "code": null, "e": 4553, "s": 4311, "text": "Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created." }, { "code": null, "e": 4653, "s": 4553, "text": "Member function − These are the function defined inside a class and are used to access object data." }, { "code": null, "e": 4753, "s": 4653, "text": "Member function − These are the function defined inside a class and are used to access object data." }, { "code": null, "e": 4963, "s": 4753, "text": "Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class." }, { "code": null, "e": 5173, "s": 4963, "text": "Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class." }, { "code": null, "e": 5286, "s": 5173, "text": "Parent class − A class that is inherited from by another class. This is also called a base class or super class." }, { "code": null, "e": 5399, "s": 5286, "text": "Parent class − A class that is inherited from by another class. This is also called a base class or super class." }, { "code": null, "e": 5504, "s": 5399, "text": "Child Class − A class that inherits from another class. This is also called a subclass or derived class." }, { "code": null, "e": 5609, "s": 5504, "text": "Child Class − A class that inherits from another class. This is also called a subclass or derived class." }, { "code": null, "e": 5827, "s": 5609, "text": "Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task." }, { "code": null, "e": 6045, "s": 5827, "text": "Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task." }, { "code": null, "e": 6264, "s": 6045, "text": "Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation." }, { "code": null, "e": 6483, "s": 6264, "text": "Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation." }, { "code": null, "e": 6590, "s": 6483, "text": "Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted)." }, { "code": null, "e": 6697, "s": 6590, "text": "Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted)." }, { "code": null, "e": 6816, "s": 6697, "text": "Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object." }, { "code": null, "e": 6935, "s": 6816, "text": "Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object." }, { "code": null, "e": 7073, "s": 6935, "text": "Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class." }, { "code": null, "e": 7211, "s": 7073, "text": "Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class." }, { "code": null, "e": 7348, "s": 7211, "text": "Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope." }, { "code": null, "e": 7485, "s": 7348, "text": "Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope." }, { "code": null, "e": 7550, "s": 7485, "text": "The general form for defining a new class in PHP is as follows −" }, { "code": null, "e": 7717, "s": 7550, "text": "<?php\n class phpClass {\n var $var1;\n var $var2 = \"constant string\";\n \n function myfunc ($arg1, $arg2) {\n [..]\n }\n [..]\n }\n?>" }, { "code": null, "e": 7756, "s": 7717, "text": "Here is the description of each line −" }, { "code": null, "e": 7839, "s": 7756, "text": "The special form class, followed by the name of the class that you want to define." }, { "code": null, "e": 7922, "s": 7839, "text": "The special form class, followed by the name of the class that you want to define." }, { "code": null, "e": 8010, "s": 7922, "text": "A set of braces enclosing any number of variable declarations and function definitions." }, { "code": null, "e": 8098, "s": 8010, "text": "A set of braces enclosing any number of variable declarations and function definitions." }, { "code": null, "e": 8268, "s": 8098, "text": "Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value." }, { "code": null, "e": 8438, "s": 8268, "text": "Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value." }, { "code": null, "e": 8574, "s": 8438, "text": "Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data." }, { "code": null, "e": 8710, "s": 8574, "text": "Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data." }, { "code": null, "e": 8767, "s": 8710, "text": "Here is an example which defines a class of Books type −" }, { "code": null, "e": 9203, "s": 8767, "text": "<?php\n class Books {\n /* Member variables */\n var $price;\n var $title;\n \n /* Member functions */\n function setPrice($par){\n $this->price = $par;\n }\n \n function getPrice(){\n echo $this->price .\"<br/>\";\n }\n \n function setTitle($par){\n $this->title = $par;\n }\n \n function getTitle(){\n echo $this->title .\" <br/>\";\n }\n }\n?>" }, { "code": null, "e": 9289, "s": 9203, "text": "The variable $this is a special variable and it refers to the same object ie. itself." }, { "code": null, "e": 9454, "s": 9289, "text": "Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator." }, { "code": null, "e": 9521, "s": 9454, "text": "$physics = new Books;\n$maths = new Books;\n$chemistry = new Books;\n" }, { "code": null, "e": 9728, "s": 9521, "text": "Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables." }, { "code": null, "e": 9907, "s": 9728, "text": "After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only." }, { "code": null, "e": 10008, "s": 9907, "text": "Following example shows how to set title and prices for the three books by calling member functions." }, { "code": null, "e": 10212, "s": 10008, "text": "$physics->setTitle( \"Physics for High School\" );\n$chemistry->setTitle( \"Advanced Chemistry\" );\n$maths->setTitle( \"Algebra\" );\n\n$physics->setPrice( 10 );\n$chemistry->setPrice( 15 );\n$maths->setPrice( 7 );" }, { "code": null, "e": 10294, "s": 10212, "text": "Now you call another member functions to get the values set by in above example −" }, { "code": null, "e": 10426, "s": 10294, "text": "$physics->getTitle();\n$chemistry->getTitle();\n$maths->getTitle();\n$physics->getPrice();\n$chemistry->getPrice();\n$maths->getPrice();" }, { "code": null, "e": 10467, "s": 10426, "text": "This will produce the following result −" }, { "code": null, "e": 10527, "s": 10467, "text": "Physics for High School\nAdvanced Chemistry\nAlgebra\n10\n15\n7\n" }, { "code": null, "e": 10746, "s": 10527, "text": "Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions. " }, { "code": null, "e": 10898, "s": 10746, "text": "PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function." }, { "code": null, "e": 11044, "s": 10898, "text": "Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation." }, { "code": null, "e": 11136, "s": 11044, "text": "function __construct( $par1, $par2 ) {\n $this->title = $par1;\n $this->price = $par2;\n}\n" }, { "code": null, "e": 11324, "s": 11136, "text": "Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below −" }, { "code": null, "e": 11629, "s": 11324, "text": "$physics = new Books( \"Physics for High School\", 10 );\n$maths = new Books ( \"Advanced Chemistry\", 15 );\n$chemistry = new Books (\"Algebra\", 7 );\n\n/* Get those set values */\n$physics->getTitle();\n$chemistry->getTitle();\n$maths->getTitle();\n\n$physics->getPrice();\n$chemistry->getPrice();\n$maths->getPrice();" }, { "code": null, "e": 11670, "s": 11629, "text": "This will produce the following result −" }, { "code": null, "e": 11742, "s": 11670, "text": " Physics for High School\n Advanced Chemistry\n Algebra\n 10\n 15\n 7\n" }, { "code": null, "e": 11892, "s": 11742, "text": "Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor." }, { "code": null, "e": 12024, "s": 11892, "text": "PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −" }, { "code": null, "e": 12077, "s": 12024, "text": "class Child extends Parent {\n <definition body>\n}\n" }, { "code": null, "e": 12194, "s": 12077, "text": "The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −" }, { "code": null, "e": 12270, "s": 12194, "text": "Automatically has all the member variable declarations of the parent class." }, { "code": null, "e": 12346, "s": 12270, "text": "Automatically has all the member variable declarations of the parent class." }, { "code": null, "e": 12488, "s": 12346, "text": "Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent." }, { "code": null, "e": 12630, "s": 12488, "text": "Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent." }, { "code": null, "e": 12722, "s": 12630, "text": "Following example inherit Books class and adds more functionality based on the requirement." }, { "code": null, "e": 12919, "s": 12722, "text": "class Novel extends Books {\n var $publisher;\n \n function setPublisher($par){\n $this->publisher = $par;\n }\n \n function getPublisher(){\n echo $this->publisher. \"<br />\";\n }\n}" }, { "code": null, "e": 13006, "s": 12919, "text": "Now apart from inherited functions, class Novel keeps two additional member functions." }, { "code": null, "e": 13193, "s": 13006, "text": "Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class." }, { "code": null, "e": 13288, "s": 13193, "text": "In the following example getPrice and getTitle functions are overridden to return some values." }, { "code": null, "e": 13451, "s": 13288, "text": "function getPrice() {\n echo $this->price . \"<br/>\";\n return $this->price;\n}\n \nfunction getTitle(){\n echo $this->title . \"<br/>\";\n return $this->title;\n}" }, { "code": null, "e": 13595, "s": 13451, "text": "Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −" }, { "code": null, "e": 13642, "s": 13595, "text": "From outside the class in which it is declared" }, { "code": null, "e": 13689, "s": 13642, "text": "From outside the class in which it is declared" }, { "code": null, "e": 13735, "s": 13689, "text": "From within the class in which it is declared" }, { "code": null, "e": 13781, "s": 13735, "text": "From within the class in which it is declared" }, { "code": null, "e": 13857, "s": 13781, "text": "From within another class that implements the class in which it is declared" }, { "code": null, "e": 13933, "s": 13857, "text": "From within another class that implements the class in which it is declared" }, { "code": null, "e": 14106, "s": 13933, "text": "Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected." }, { "code": null, "e": 14353, "s": 14106, "text": "By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class." }, { "code": null, "e": 14436, "s": 14353, "text": "A class member can be made private by using private keyword infront of the member." }, { "code": null, "e": 14803, "s": 14436, "text": "class MyClass {\n private $car = \"skoda\";\n $driver = \"SRK\";\n \n function __construct($par) {\n // Statements here run every time\n // an instance of the class\n // is created.\n }\n \n function myPublicFunction() {\n return(\"I'm visible!\");\n }\n \n private function myPrivateFunction() {\n return(\"I'm not visible outside!\");\n }\n}" }, { "code": null, "e": 15047, "s": 14803, "text": "When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private." }, { "code": null, "e": 15339, "s": 15047, "text": "A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member." }, { "code": null, "e": 15378, "s": 15339, "text": "Here is different version of MyClass −" }, { "code": null, "e": 15749, "s": 15378, "text": "class MyClass {\n protected $car = \"skoda\";\n $driver = \"SRK\";\n\n function __construct($par) {\n // Statements here run every time\n // an instance of the class\n // is created.\n }\n \n function myPublicFunction() {\n return(\"I'm visible!\");\n }\n \n protected function myPrivateFunction() {\n return(\"I'm visible in child class!\");\n }\n}" }, { "code": null, "e": 15990, "s": 15749, "text": "Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers." }, { "code": null, "e": 16053, "s": 15990, "text": "As of PHP5, it is possible to define an interface, like this −" }, { "code": null, "e": 16103, "s": 16053, "text": "interface Mail {\n public function sendMail();\n}" }, { "code": null, "e": 16166, "s": 16103, "text": "Then, if another class implemented that interface, like this −" }, { "code": null, "e": 16237, "s": 16166, "text": "class Report implements Mail {\n // sendMail() Definition goes here\n}" }, { "code": null, "e": 16420, "s": 16237, "text": "A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change." }, { "code": null, "e": 16492, "s": 16420, "text": "Declaring one constant is easy, as is done in this version of MyClass −" }, { "code": null, "e": 16687, "s": 16492, "text": "class MyClass {\n const requiredMargin = 1.7;\n \n function __construct($incomingValue) {\n // Statements here run every time\n // an instance of the class\n // is created.\n }\n}" }, { "code": null, "e": 16923, "s": 16687, "text": "In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do." }, { "code": null, "e": 17062, "s": 16923, "text": "An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this −" }, { "code": null, "e": 17264, "s": 17062, "text": "When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility." }, { "code": null, "e": 17348, "s": 17264, "text": "abstract class MyAbstractClass {\n abstract function myAbstractFunction() {\n }\n}" }, { "code": null, "e": 17534, "s": 17348, "text": "Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class." }, { "code": null, "e": 17760, "s": 17534, "text": "Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can)." }, { "code": null, "e": 17788, "s": 17760, "text": "Try out following example −" }, { "code": null, "e": 18042, "s": 17788, "text": "<?php\n class Foo {\n public static $my_static = 'foo';\n \n public function staticValue() {\n return self::$my_static;\n }\n }\n\t\n print Foo::$my_static . \"\\n\";\n $foo = new Foo();\n \n print $foo->staticValue() . \"\\n\";\n?>\t" }, { "code": null, "e": 18243, "s": 18042, "text": "PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended." }, { "code": null, "e": 18339, "s": 18243, "text": "Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()" }, { "code": null, "e": 18721, "s": 18339, "text": "<?php\n\n class BaseClass {\n public function test() {\n echo \"BaseClass::test() called<br>\";\n }\n \n final public function moreTesting() {\n echo \"BaseClass::moreTesting() called<br>\";\n }\n }\n \n class ChildClass extends BaseClass {\n public function moreTesting() {\n echo \"ChildClass::moreTesting() called<br>\";\n }\n }\n?>" }, { "code": null, "e": 18958, "s": 18721, "text": "Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example −" }, { "code": null, "e": 19548, "s": 18958, "text": "class Name {\n var $_firstName;\n var $_lastName;\n \n function Name($first_name, $last_name) {\n $this->_firstName = $first_name;\n $this->_lastName = $last_name;\n }\n \n function toString() {\n return($this->_lastName .\", \" .$this->_firstName);\n }\n}\nclass NameSub1 extends Name {\n var $_middleInitial;\n \n function NameSub1($first_name, $middle_initial, $last_name) {\n Name::Name($first_name, $last_name);\n $this->_middleInitial = $middle_initial;\n }\n \n function toString() {\n return(Name::toString() . \" \" . $this->_middleInitial);\n }\n}" }, { "code": null, "e": 19998, "s": 19548, "text": "In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent function that it overrides." } ]
Instagram-explore module in Python
20 Aug, 2020 instagram-explore module is an Instagram scrapping module. Run the following pip command : pip install instagram-explore This module has 8 functions currently for exploring Instagram: Getting user informationGetting tagGetting user imagesGetting locationsLocationLocation imagesMediaMedia images Getting user information Getting tag Getting user images Getting locations Location Location images Media Media images Example 1 : To get information about a user we will use the user() method. ie.user("username", max_id = None) It will give html of page i.e. the homepage of the Instagram profile Python3 # import the modulesimport instagram_explore as ieimport json # search user nameresult = ie.user('timesofindia') parsed_data= json.dumps(result, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data[15:400]) Output : “biography”: “The Times of India is India\u2019s most-read English newspaper and World\u2019s largest-selling English newspaper – A Times Internet Limited Product”, “blocked_by_viewer”: false, “business_category_name”: “Publishers”, “business_email”: “[email protected]”, “category_enum”: “BROADCASTING_MEDIA_PRODUCTION”, “connected_fb_p Example 2 : Getting user images If account is private – > Null is returned else links of images are returned sorted as latest. Python3 # importing the modulesimport instagram_explore as ieimport json res = ie.user_images('timesofindia') parsed_data = json.dumps(res, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data) Output : Here only one link is being displayed. https://scontent-del1-1.cdninstagram.com/v/t51.2885-15/fr/e15/s1080x1080/117758575_167564261503193_2290116502716246854_n.jpg?_nc_ht=scontent-del1-1.cdninstagram.com&_nc_cat=105&_nc_ohc=4Yds4Fv58wUAX-4Pgra&oh=eaa3b5b243433239e134e427f340049c&oe=5F666630 Example 3 : Searching Tags By the tag() function, we will get information about the searched tag variable = ie.tag("Name_of_tag", max_id = None) Python3 # importing the modulesimport instagram_explore as ieimport json # using the tag methodresult = ie.tag('Binod') parsed_data = json.dumps(result, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data) Output : Example 4 : Getting images by tag Python3 # importing the modulesimport instagram_explore as ieimport json # Search user nameresult = ie.tag_images('Binod') parsed_data = json.dumps(result, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data) Output : . python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2020" }, { "code": null, "e": 87, "s": 28, "text": "instagram-explore module is an Instagram scrapping module." }, { "code": null, "e": 119, "s": 87, "text": "Run the following pip command :" }, { "code": null, "e": 150, "s": 119, "text": "pip install instagram-explore\n" }, { "code": null, "e": 213, "s": 150, "text": "This module has 8 functions currently for exploring Instagram:" }, { "code": null, "e": 325, "s": 213, "text": "Getting user informationGetting tagGetting user imagesGetting locationsLocationLocation imagesMediaMedia images" }, { "code": null, "e": 350, "s": 325, "text": "Getting user information" }, { "code": null, "e": 362, "s": 350, "text": "Getting tag" }, { "code": null, "e": 382, "s": 362, "text": "Getting user images" }, { "code": null, "e": 400, "s": 382, "text": "Getting locations" }, { "code": null, "e": 409, "s": 400, "text": "Location" }, { "code": null, "e": 425, "s": 409, "text": "Location images" }, { "code": null, "e": 431, "s": 425, "text": "Media" }, { "code": null, "e": 444, "s": 431, "text": "Media images" }, { "code": null, "e": 519, "s": 444, "text": "Example 1 : To get information about a user we will use the user() method." }, { "code": null, "e": 555, "s": 519, "text": "ie.user(\"username\", max_id = None)\n" }, { "code": null, "e": 624, "s": 555, "text": "It will give html of page i.e. the homepage of the Instagram profile" }, { "code": null, "e": 632, "s": 624, "text": "Python3" }, { "code": "# import the modulesimport instagram_explore as ieimport json # search user nameresult = ie.user('timesofindia') parsed_data= json.dumps(result, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data[15:400])", "e": 881, "s": 632, "text": null }, { "code": null, "e": 890, "s": 881, "text": "Output :" }, { "code": null, "e": 1056, "s": 890, "text": " “biography”: “The Times of India is India\\u2019s most-read English newspaper and World\\u2019s largest-selling English newspaper – A Times Internet Limited Product”," }, { "code": null, "e": 1091, "s": 1056, "text": " “blocked_by_viewer”: false," }, { "code": null, "e": 1138, "s": 1091, "text": " “business_category_name”: “Publishers”," }, { "code": null, "e": 1191, "s": 1138, "text": " “business_email”: “[email protected]”," }, { "code": null, "e": 1248, "s": 1191, "text": " “category_enum”: “BROADCASTING_MEDIA_PRODUCTION”," }, { "code": null, "e": 1271, "s": 1248, "text": " “connected_fb_p" }, { "code": null, "e": 1303, "s": 1271, "text": "Example 2 : Getting user images" }, { "code": null, "e": 1398, "s": 1303, "text": "If account is private – > Null is returned else links of images are returned sorted as latest." }, { "code": null, "e": 1406, "s": 1398, "text": "Python3" }, { "code": "# importing the modulesimport instagram_explore as ieimport json res = ie.user_images('timesofindia') parsed_data = json.dumps(res, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data)", "e": 1634, "s": 1406, "text": null }, { "code": null, "e": 1643, "s": 1634, "text": "Output :" }, { "code": null, "e": 1682, "s": 1643, "text": "Here only one link is being displayed." }, { "code": null, "e": 1935, "s": 1682, "text": "https://scontent-del1-1.cdninstagram.com/v/t51.2885-15/fr/e15/s1080x1080/117758575_167564261503193_2290116502716246854_n.jpg?_nc_ht=scontent-del1-1.cdninstagram.com&_nc_cat=105&_nc_ohc=4Yds4Fv58wUAX-4Pgra&oh=eaa3b5b243433239e134e427f340049c&oe=5F666630" }, { "code": null, "e": 1963, "s": 1935, "text": "Example 3 : Searching Tags " }, { "code": null, "e": 2034, "s": 1963, "text": "By the tag() function, we will get information about the searched tag " }, { "code": null, "e": 2083, "s": 2034, "text": "variable = ie.tag(\"Name_of_tag\", max_id = None)\n" }, { "code": null, "e": 2091, "s": 2083, "text": "Python3" }, { "code": "# importing the modulesimport instagram_explore as ieimport json # using the tag methodresult = ie.tag('Binod') parsed_data = json.dumps(result, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data)", "e": 2334, "s": 2091, "text": null }, { "code": null, "e": 2344, "s": 2334, "text": "Output : " }, { "code": null, "e": 2378, "s": 2344, "text": "Example 4 : Getting images by tag" }, { "code": null, "e": 2386, "s": 2378, "text": "Python3" }, { "code": "# importing the modulesimport instagram_explore as ieimport json # Search user nameresult = ie.tag_images('Binod') parsed_data = json.dumps(result, indent = 4, sort_keys = True) # displaying the dataprint(parsed_data)", "e": 2632, "s": 2386, "text": null }, { "code": null, "e": 2641, "s": 2632, "text": "Output :" }, { "code": null, "e": 2643, "s": 2641, "text": "." }, { "code": null, "e": 2658, "s": 2643, "text": "python-modules" }, { "code": null, "e": 2665, "s": 2658, "text": "Python" }, { "code": null, "e": 2763, "s": 2665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2781, "s": 2763, "text": "Python Dictionary" }, { "code": null, "e": 2823, "s": 2781, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2845, "s": 2823, "text": "Enumerate() in Python" }, { "code": null, "e": 2880, "s": 2845, "text": "Read a file line by line in Python" }, { "code": null, "e": 2906, "s": 2880, "text": "Python String | replace()" }, { "code": null, "e": 2938, "s": 2906, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2967, "s": 2938, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2994, "s": 2967, "text": "Python Classes and Objects" }, { "code": null, "e": 3024, "s": 2994, "text": "Iterate over a list in Python" } ]
Python | Random Password Generator using Tkinter
13 May, 2022 With growing technology, everything has relied on data, and securing this data is the main concern. Passwords are meant to keep the data safe that we upload on the Internet. An easy password can be hacked easily and all personal information can be misused. In order to prevent such things and keep the data safe, it is necessary to keep our passwords very strong. Let’s create a simple application that can randomly generate strong passwords using the Python Tkinter module.This application can generate a random password, with the combination of letters, numerics, and special characters. One can mention the length of the password based on requirement and can also select the strength of the password. Example 1 Modules needed: import random import pyperclip from tkinter import * from tkinter.ttk import * Python3 # Python program to generate random# password using Tkinter moduleimport randomimport pyperclipfrom tkinter import *from tkinter.ttk import * # Function for calculation of password def low(): entry.delete(0, END) # Get the length of password length = var1.get() lower = "abcdefghijklmnopqrstuvwxyz" upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !@#$%^&*()" password = "" # if strength selected is low if var.get() == 1: for i in range(0, length): password = password + random.choice(lower) return password # if strength selected is medium elif var.get() == 0: for i in range(0, length): password = password + random.choice(upper) return password # if strength selected is strong elif var.get() == 3: for i in range(0, length): password = password + random.choice(digits) return password else: print("Please choose an option") # Function for generation of passworddef generate(): password1 = low() entry.insert(10, password1) # Function for copying password to clipboarddef copy1(): random_password = entry.get() pyperclip.copy(random_password) # Main Function # create GUI windowroot = Tk()var = IntVar()var1 = IntVar() # Title of your GUI windowroot.title("Random Password Generator") # create label and entry to show# password generatedRandom_password = Label(root, text="Password")Random_password.grid(row=0)entry = Entry(root)entry.grid(row=0, column=1) # create label for length of passwordc_label = Label(root, text="Length")c_label.grid(row=1) # create Buttons Copy which will copy# password to clipboard and Generate# which will generate the passwordcopy_button = Button(root, text="Copy", command=copy1)copy_button.grid(row=0, column=2)generate_button = Button(root, text="Generate", command=generate)generate_button.grid(row=0, column=3) # Radio Buttons for deciding the# strength of password# Default strength is Mediumradio_low = Radiobutton(root, text="Low", variable=var, value=1)radio_low.grid(row=1, column=2, sticky='E')radio_middle = Radiobutton(root, text="Medium", variable=var, value=0)radio_middle.grid(row=1, column=3, sticky='E')radio_strong = Radiobutton(root, text="Strong", variable=var, value=3)radio_strong.grid(row=1, column=4, sticky='E')combo = Combobox(root, textvariable=var1) # Combo Box for length of your passwordcombo['values'] = (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, "Length")combo.current(0)combo.bind('<<ComboboxSelected>>')combo.grid(column=1, row=1) # start the GUIroot.mainloop() Output: Example 2: GUI Of Random Password Generator Using Python Python # pip install tkinterfrom tkinter import * # pip install pyperclipimport pyperclip import random root = Tk()root.geometry("700x300")passwrd = StringVar()passlen = IntVar()passlen.set(0) def generate(): # Function to generate the password pass1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')'] password = "" for x in range(passlen.get()): password = password + random.choice(pass1) passwrd.set(password) # function to copy the passcode def copyclipboard(): random_password = passwrd.get() pyperclip.copy(random_password)# Labels Label(root, text="Strong Password Generator", font="Courier 30 bold").pack()Label(root, text="GeeksForGeeks", font="Courier 20 italic").pack()Label(root, text="Enter the number to get password").pack(pady=3)Entry(root, textvariable=passlen).pack(pady=3)Button(root, text="Tap to get", command=generate).pack(pady=7)Entry(root, textvariable=passwrd).pack(pady=3)Button(root, text="Tap to copy clipboard", command=copyclipboard).pack()root.mainloop() Output: simranarora5sos ayushcoding100 python-utility Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 May, 2022" }, { "code": null, "e": 416, "s": 52, "text": "With growing technology, everything has relied on data, and securing this data is the main concern. Passwords are meant to keep the data safe that we upload on the Internet. An easy password can be hacked easily and all personal information can be misused. In order to prevent such things and keep the data safe, it is necessary to keep our passwords very strong." }, { "code": null, "e": 756, "s": 416, "text": "Let’s create a simple application that can randomly generate strong passwords using the Python Tkinter module.This application can generate a random password, with the combination of letters, numerics, and special characters. One can mention the length of the password based on requirement and can also select the strength of the password." }, { "code": null, "e": 766, "s": 756, "text": "Example 1" }, { "code": null, "e": 783, "s": 766, "text": "Modules needed: " }, { "code": null, "e": 862, "s": 783, "text": "import random\nimport pyperclip\nfrom tkinter import * from tkinter.ttk import *" }, { "code": null, "e": 870, "s": 862, "text": "Python3" }, { "code": "# Python program to generate random# password using Tkinter moduleimport randomimport pyperclipfrom tkinter import *from tkinter.ttk import * # Function for calculation of password def low(): entry.delete(0, END) # Get the length of password length = var1.get() lower = \"abcdefghijklmnopqrstuvwxyz\" upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\" digits = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !@#$%^&*()\" password = \"\" # if strength selected is low if var.get() == 1: for i in range(0, length): password = password + random.choice(lower) return password # if strength selected is medium elif var.get() == 0: for i in range(0, length): password = password + random.choice(upper) return password # if strength selected is strong elif var.get() == 3: for i in range(0, length): password = password + random.choice(digits) return password else: print(\"Please choose an option\") # Function for generation of passworddef generate(): password1 = low() entry.insert(10, password1) # Function for copying password to clipboarddef copy1(): random_password = entry.get() pyperclip.copy(random_password) # Main Function # create GUI windowroot = Tk()var = IntVar()var1 = IntVar() # Title of your GUI windowroot.title(\"Random Password Generator\") # create label and entry to show# password generatedRandom_password = Label(root, text=\"Password\")Random_password.grid(row=0)entry = Entry(root)entry.grid(row=0, column=1) # create label for length of passwordc_label = Label(root, text=\"Length\")c_label.grid(row=1) # create Buttons Copy which will copy# password to clipboard and Generate# which will generate the passwordcopy_button = Button(root, text=\"Copy\", command=copy1)copy_button.grid(row=0, column=2)generate_button = Button(root, text=\"Generate\", command=generate)generate_button.grid(row=0, column=3) # Radio Buttons for deciding the# strength of password# Default strength is Mediumradio_low = Radiobutton(root, text=\"Low\", variable=var, value=1)radio_low.grid(row=1, column=2, sticky='E')radio_middle = Radiobutton(root, text=\"Medium\", variable=var, value=0)radio_middle.grid(row=1, column=3, sticky='E')radio_strong = Radiobutton(root, text=\"Strong\", variable=var, value=3)radio_strong.grid(row=1, column=4, sticky='E')combo = Combobox(root, textvariable=var1) # Combo Box for length of your passwordcombo['values'] = (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, \"Length\")combo.current(0)combo.bind('<<ComboboxSelected>>')combo.grid(column=1, row=1) # start the GUIroot.mainloop()", "e": 3626, "s": 870, "text": null }, { "code": null, "e": 3636, "s": 3626, "text": "Output: " }, { "code": null, "e": 3696, "s": 3638, "text": "Example 2: GUI Of Random Password Generator Using Python " }, { "code": null, "e": 3703, "s": 3696, "text": "Python" }, { "code": "# pip install tkinterfrom tkinter import * # pip install pyperclipimport pyperclip import random root = Tk()root.geometry(\"700x300\")passwrd = StringVar()passlen = IntVar()passlen.set(0) def generate(): # Function to generate the password pass1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')'] password = \"\" for x in range(passlen.get()): password = password + random.choice(pass1) passwrd.set(password) # function to copy the passcode def copyclipboard(): random_password = passwrd.get() pyperclip.copy(random_password)# Labels Label(root, text=\"Strong Password Generator\", font=\"Courier 30 bold\").pack()Label(root, text=\"GeeksForGeeks\", font=\"Courier 20 italic\").pack()Label(root, text=\"Enter the number to get password\").pack(pady=3)Entry(root, textvariable=passlen).pack(pady=3)Button(root, text=\"Tap to get\", command=generate).pack(pady=7)Entry(root, textvariable=passwrd).pack(pady=3)Button(root, text=\"Tap to copy clipboard\", command=copyclipboard).pack()root.mainloop()", "e": 5112, "s": 3703, "text": null }, { "code": null, "e": 5120, "s": 5112, "text": "Output:" }, { "code": null, "e": 5138, "s": 5122, "text": "simranarora5sos" }, { "code": null, "e": 5153, "s": 5138, "text": "ayushcoding100" }, { "code": null, "e": 5168, "s": 5153, "text": "python-utility" }, { "code": null, "e": 5176, "s": 5168, "text": "Project" }, { "code": null, "e": 5183, "s": 5176, "text": "Python" } ]
How to create a canvas ellipse using Fabric.js ?
08 Feb, 2022 In this article, we are going to see how to create a canvas ellipse using FabricJS. The canvas means ellipse is movable and can be stretched according to requirement. Further, the ellipse can be customized when it comes to initial stroke color, fill color, stroke width or radius.Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our ellipse. After this, we will initialize instances of Canvas and Ellipse provided by FabricJS and render the Ellipse on the Canvas as given in the example below.Syntax: fabric.Ellipse({ rx: number, ry: number, radius: number, fill: string, stroke: string, strokeWidth: int }); Parameters: This function accepts six parameters as mentioned above and described below: rx: It specifies the horizontal radius. ry: It specifies the vertical radius. radius: It specifies the radius. fill: It specifies the fill colour. stroke: It specifies the stroke colour. strokeWidth: It specifies the width of stroke. Program: This example uses FabricJS to create simple editable canvas-like ellipse as given below: html <!DOCTYPE html><html> <head> <title> How to create a canvas-type ellipse with JavaScript? </title> <!-- Loading the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Initiate a Ellipse instance var ellipse = new fabric.Ellipse({ rx: 80, ry: 40, fill: '', stroke: 'green', strokeWidth: 3 }); // Render the Ellipse in canvas canvas.add(ellipse); </script></body> </html> Output: blalverma92 Fabric.js JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Feb, 2022" }, { "code": null, "e": 674, "s": 28, "text": "In this article, we are going to see how to create a canvas ellipse using FabricJS. The canvas means ellipse is movable and can be stretched according to requirement. Further, the ellipse can be customized when it comes to initial stroke color, fill color, stroke width or radius.Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our ellipse. After this, we will initialize instances of Canvas and Ellipse provided by FabricJS and render the Ellipse on the Canvas as given in the example below.Syntax: " }, { "code": null, "e": 864, "s": 674, "text": " fabric.Ellipse({\n rx: number,\n ry: number,\n radius: number,\n fill: string,\n stroke: string,\n strokeWidth: int\n }); " }, { "code": null, "e": 955, "s": 864, "text": "Parameters: This function accepts six parameters as mentioned above and described below: " }, { "code": null, "e": 995, "s": 955, "text": "rx: It specifies the horizontal radius." }, { "code": null, "e": 1033, "s": 995, "text": "ry: It specifies the vertical radius." }, { "code": null, "e": 1066, "s": 1033, "text": "radius: It specifies the radius." }, { "code": null, "e": 1102, "s": 1066, "text": "fill: It specifies the fill colour." }, { "code": null, "e": 1142, "s": 1102, "text": "stroke: It specifies the stroke colour." }, { "code": null, "e": 1189, "s": 1142, "text": "strokeWidth: It specifies the width of stroke." }, { "code": null, "e": 1289, "s": 1189, "text": "Program: This example uses FabricJS to create simple editable canvas-like ellipse as given below: " }, { "code": null, "e": 1294, "s": 1289, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create a canvas-type ellipse with JavaScript? </title> <!-- Loading the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000\"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Initiate a Ellipse instance var ellipse = new fabric.Ellipse({ rx: 80, ry: 40, fill: '', stroke: 'green', strokeWidth: 3 }); // Render the Ellipse in canvas canvas.add(ellipse); </script></body> </html>", "e": 2087, "s": 1294, "text": null }, { "code": null, "e": 2097, "s": 2087, "text": "Output: " }, { "code": null, "e": 2111, "s": 2099, "text": "blalverma92" }, { "code": null, "e": 2121, "s": 2111, "text": "Fabric.js" }, { "code": null, "e": 2137, "s": 2121, "text": "JavaScript-Misc" }, { "code": null, "e": 2148, "s": 2137, "text": "JavaScript" }, { "code": null, "e": 2165, "s": 2148, "text": "Web Technologies" } ]
StringBuffer toString() method in Java with Examples
04 Dec, 2018 The toString() method of StringBuffer class is the inbuilt method used to returns a string representing the data contained by StringBuffer Object. A new String object is created and initialized to get the character sequence from this StringBuffer object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String. Syntax: public abstract String toString() Return Value: This method returns the String representing the data contained by StringBuffer Object. Below programs illustrate the StringBuffer.toString() method: Example 1: // Java program to demonstrate// the toString() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("GeeksForGeeks"); // print string System.out.println("String contains = " + str.toString()); }} String contains = GeeksForGeeks Example 2: // Java program to demonstrate// the toString() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer( "Geeks for Geeks contribute"); // print string System.out.println("String contains = " + str.toString()); }} String contains = Geeks for Geeks contribute References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#toString() java-basics Java-Functions Java-lang package java-StringBuffer Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java Introduction to Java Constructors in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2018" }, { "code": null, "e": 423, "s": 28, "text": "The toString() method of StringBuffer class is the inbuilt method used to returns a string representing the data contained by StringBuffer Object. A new String object is created and initialized to get the character sequence from this StringBuffer object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String." }, { "code": null, "e": 431, "s": 423, "text": "Syntax:" }, { "code": null, "e": 465, "s": 431, "text": "public abstract String toString()" }, { "code": null, "e": 566, "s": 465, "text": "Return Value: This method returns the String representing the data contained by StringBuffer Object." }, { "code": null, "e": 628, "s": 566, "text": "Below programs illustrate the StringBuffer.toString() method:" }, { "code": null, "e": 639, "s": 628, "text": "Example 1:" }, { "code": "// Java program to demonstrate// the toString() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"GeeksForGeeks\"); // print string System.out.println(\"String contains = \" + str.toString()); }}", "e": 1033, "s": 639, "text": null }, { "code": null, "e": 1066, "s": 1033, "text": "String contains = GeeksForGeeks\n" }, { "code": null, "e": 1077, "s": 1066, "text": "Example 2:" }, { "code": "// Java program to demonstrate// the toString() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer( \"Geeks for Geeks contribute\"); // print string System.out.println(\"String contains = \" + str.toString()); }}", "e": 1500, "s": 1077, "text": null }, { "code": null, "e": 1546, "s": 1500, "text": "String contains = Geeks for Geeks contribute\n" }, { "code": null, "e": 1639, "s": 1546, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#toString()" }, { "code": null, "e": 1651, "s": 1639, "text": "java-basics" }, { "code": null, "e": 1666, "s": 1651, "text": "Java-Functions" }, { "code": null, "e": 1684, "s": 1666, "text": "Java-lang package" }, { "code": null, "e": 1702, "s": 1684, "text": "java-StringBuffer" }, { "code": null, "e": 1707, "s": 1702, "text": "Java" }, { "code": null, "e": 1712, "s": 1707, "text": "Java" }, { "code": null, "e": 1810, "s": 1712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1829, "s": 1810, "text": "Interfaces in Java" }, { "code": null, "e": 1847, "s": 1829, "text": "ArrayList in Java" }, { "code": null, "e": 1867, "s": 1847, "text": "Collections in Java" }, { "code": null, "e": 1882, "s": 1867, "text": "Stream In Java" }, { "code": null, "e": 1914, "s": 1882, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 1934, "s": 1914, "text": "Stack Class in Java" }, { "code": null, "e": 1958, "s": 1934, "text": "Singleton Class in Java" }, { "code": null, "e": 1970, "s": 1958, "text": "Set in Java" }, { "code": null, "e": 1991, "s": 1970, "text": "Introduction to Java" } ]
java.time.LocalDate.isBefore() Method Example
The java.time.LocalDate.isBefore(ChronoLocalDate other) method checks if this date is before the specified date. Following is the declaration for java.time.LocalDate.isBefore(ChronoLocalDate other) method. public boolean isBefore(ChronoLocalDate other) other − the other date to compare to, not null. true if this date is before the specified date. The following example shows the usage of java.time.LocalDate.isBefore(ChronoLocalDate other) method. package com.tutorialspoint; import java.time.LocalDate; public class LocalDateDemo { public static void main(String[] args) { LocalDate date = LocalDate.parse("2017-02-03"); LocalDate date1 = LocalDate.parse("2017-03-03"); System.out.println(date1.isBefore(date)); } } Let us compile and run the above program, this will produce the following result −
[ { "code": null, "e": 2162, "s": 2049, "text": "The java.time.LocalDate.isBefore(ChronoLocalDate other) method checks if this date is before the specified date." }, { "code": null, "e": 2255, "s": 2162, "text": "Following is the declaration for java.time.LocalDate.isBefore(ChronoLocalDate other) method." }, { "code": null, "e": 2303, "s": 2255, "text": "public boolean isBefore(ChronoLocalDate other)\n" }, { "code": null, "e": 2351, "s": 2303, "text": "other − the other date to compare to, not null." }, { "code": null, "e": 2399, "s": 2351, "text": "true if this date is before the specified date." }, { "code": null, "e": 2500, "s": 2399, "text": "The following example shows the usage of java.time.LocalDate.isBefore(ChronoLocalDate other) method." }, { "code": null, "e": 2801, "s": 2500, "text": "package com.tutorialspoint;\n\nimport java.time.LocalDate;\n\npublic class LocalDateDemo {\n public static void main(String[] args) {\n\t \n LocalDate date = LocalDate.parse(\"2017-02-03\");\n LocalDate date1 = LocalDate.parse(\"2017-03-03\");\n System.out.println(date1.isBefore(date)); \n }\n}" } ]
Why Linked List is implemented on Heap memory rather than Stack memory?
05 Jul, 2022 Pre-requisite: Linked List Data StructureStack vsHeap Memory Allocation The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind it. Stack vs Heap Memory The computer’s memory is divided into heap and stack memory segments. Stack memory segment is relatively small so it is mainly used for operations like recursion or control jump statements like goto statement. Due to the small size of the stack segment, it is not used for deep recursion levels as it may throw a stack overflow error. On the other hand, a linked list has the major advantage of dynamically expanding itself when needed without worrying about memory consumption. This is the reason why heap is preferred for storing linked list-object. Why linked list is not stored in stack memory? The question of why one cannot make a linked list with stack memory is due to the scope rules and automatic memory management on the stack. The basic idea of a linked list is to link nodes together based on their memory address. If each node is created on the stack then those nodes will be deleted after they go out of scope, so even if the user keeps pointers to their memory address it is not safe to assume that they won’t be overwritten by something else. The linked list can be implemented on the stack memory as well. Below is the C++ implementation of creating a linked list in stack memory: C++ Java C# Javascript // C++ program to implement// linked list in stack#include <iostream>using namespace std; // Structure of the linked liststruct Node { int data; struct Node* next; // Constructor Node(int x) { data = x; next = NULL; }}* head = NULL; // Function to print the linked listvoid printLinkedList(Node* head){ struct Node* temp = head; // Traversing linked list while (temp) { cout << temp->data << " "; temp = temp->next; }} // Driver codeint main(){ // Creation of linked list in stack struct Node first = Node(1); struct Node second = Node(2); struct Node third = Node(3); struct Node fourth = Node(4); head = &first; // 1 -> 2 -> 3 -> 4 first.next = &second; second.next = &third; third.next = &fourth; fourth.next = NULL; // Printing the elements of // a linked list printLinkedList(head); return 0;} // Java program to implement// linked list in stack import java.util.*; class GFG{ // Structure of the linked liststatic class Node { int data; Node next; // Constructor Node(int x) { data = x; next = null; }};static Node head = null; // Function to print the linked liststatic void printLinkedList(Node head){ Node temp = head; // Traversing linked list while (temp!=null) { System.out.print(temp.data+ " "); temp = temp.next; }} // Driver codepublic static void main(String[] args){ // Creation of linked list in stack Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; // Printing the elements of // a linked list printLinkedList(head); }} // This code contributed by shikhasingrajput // C# program to implement// linked list in stackusing System;using System.Collections.Generic; public class GFG{ // Structure of the linked list class Node { public int data; public Node next; // Constructor public Node(int x) { data = x; next = null; } }; static Node head = null; // Function to print the linked list static void printList(Node head) { Node temp = head; // Traversing linked list while (temp!=null) { Console.Write(temp.data+ " "); temp = temp.next; } } // Driver code public static void Main(String[] args) { // Creation of linked list in stack Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; // Printing the elements of // a linked list printList(head); }} // This code is contributed by shikhasingrajput <script>// Javascript program to implement// linked list in stack // Structure of the linked listclass Node { // Constructor constructor(x) { this.data = x; this.next = null; }} // Function to print the linked listfunction printLinkedList(head) { let temp = head; // Traversing linked list while (temp) { document.write(temp.data + " "); temp = temp.next; }} // Driver code // Creation of linked list in stacklet first = new Node(1);let second = new Node(2);let third = new Node(3);let fourth = new Node(4); head = first; // 1 -> 2 -> 3 -> 4first.next = second;second.next = third;third.next = fourth;fourth.next = null; // Printing the elements of// a linked listprintLinkedList(head); // This code is contributed by gfgking.</script> Output: 1 2 3 4 Condition when linked list implementation on the stack will not work: The above code won’t work if we write the logic of the creation of a linked list in a separate function and the logic of printing the elements of the linked list in a separate function. Below is its C++ implementation of the above concept: C++ Java C# Javascript // C++ program to implement// the above approach#include <iostream>using namespace std; // Structure of the linked liststruct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; }}* head = NULL; // Function to return the head pointer// of the created linked listNode* CreateLinkedList(){ struct Node first = Node(1); struct Node second = Node(2); struct Node third = Node(3); struct Node fourth = Node(4); head = &first; // 1->2->3->4 first.next = &second; second.next = &third; third.next = &fourth; fourth.next = NULL; return head;} // Function to print the linked listvoid printLinkedList(Node* head){ struct Node* temp = head; // Traversing linked list while (temp) { cout << temp->data << " "; temp = temp->next; }} // Driver Codeint main(){ struct Node* head = CreateLinkedList(); printLinkedList(head); return 0;} // Java program to implement// the above approach import java.util.*; class GFG{ // Structure of the linked liststatic class Node { int data; Node next; Node(int x) { data = x; next = null; }}static Node head = null; // Function to return the head pointer// of the created linked liststatic Node CreateLinkedList(){ Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; return head;} // Function to print the linked liststatic void printLinkedList(Node head){ Node temp = head; // Traversing linked list while (temp!=null) { System.out.print(temp.data+ " "); temp = temp.next; }} // Driver Codepublic static void main(String[] args){ Node head = CreateLinkedList(); printLinkedList(head);}} // This code is contributed by 29AjayKumar // C# program to implement// the above approach using System; public class GFG{ // Structure of the linked list class Node { public int data; public Node next; public Node(int x) { data = x; next = null; } } static Node head = null; // Function to return the head pointer // of the created linked list static Node CreateList() { Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; return head; } // Function to print the linked list static void printList(Node head) { Node temp = head; // Traversing linked list while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } } // Driver Code public static void Main(String[] args) { Node head = CreateList(); printList(head); }} // This code is contributed by shikhasingrajput <script> // javascript program to implement// the above approach // Structure of the linked list class Node { constructor( x) { this.data = x; this.next = null; } } var head = null; // Function to return the head pointer // of the created linked list function CreateLinkedList() { var first = new Node(1); var second = new Node(2); var third = new Node(3); var fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; return head; } // Function to print the linked list function printLinkedList( head) { var temp = head; // Traversing linked list while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Driver Code var head = CreateLinkedList(); printLinkedList(head); // This code contributed by shikhasingrajput</script> Explanation: The above code gives the verdict as SEGMENTATION FAULT. The reason behind it is that during the creation of the linked list in the stack memory, all the objects created by a function will be disappeared as the stack frame is popped whenever the function ends or returns. Refer to this article to know the reason behind the popping of stack frame whenever function ends. Why linked list is stored in heap memory? In a linked list, when there is a need to store more data, we can allocate the memory at run-time by using malloc or a new function in C/ C++. So dynamic memory allocation reserve size from heap area, therefore, a linked list is stored in heap memory.If there is a need to store linked lists in the stack area then implement linked lists without using malloc or a new function. Below is the C++ program to show how to implement a linked list in heap memory without throwing segmentation fault error: C++ Java C# Javascript // C++ program to implement// the above approach#include <iostream>using namespace std; // Structure of the linked liststruct Node { int data; struct Node* next;};struct Node* head = NULL; // Function to create nodes of// the linked listvoid CreateLinkedList(int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = head; head = new_node;} // Function to print the linked listvoid printLinkedList(){ struct Node* temp; temp = head; // Traversing linked list while (temp != NULL) { cout << temp->data << " "; temp = temp->next; }} // Driver Codeint main(){ CreateLinkedList(1); CreateLinkedList(2); CreateLinkedList(3); CreateLinkedList(4); printLinkedList(); return 0;} // Java program to implement// the above approachimport java.util.*;public class GFG{ // Structure of the linked liststatic class Node { int data; Node next;};static Node head = null; // Function to create nodes of// the linked liststatic void CreateLinkedList(int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node;} // Function to print the linked liststatic void printLinkedList(){ Node temp; temp = head; // Traversing linked list while (temp != null) { System.out.print(temp.data+ " "); temp = temp.next; }} // Driver Codepublic static void main(String[] args){ CreateLinkedList(1); CreateLinkedList(2); CreateLinkedList(3); CreateLinkedList(4); printLinkedList();}} // This code is contributed by 29AjayKumar // C# program to implement// the above approachusing System;using System.Collections.Generic; public class GFG { // Structure of the linked list public class Node { public int data; public Node next; }; static Node head = null; // Function to create nodes of // the linked list static void CreateList(int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; } // Function to print the linked list static void printList() { Node temp; temp = head; // Traversing linked list while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } } // Driver Code public static void Main(String[] args) { CreateList(1); CreateList(2); CreateList(3); CreateList(4); printList(); }} // This code is contributed by umadevi9616 <script>// javascript program to implement// the above approach // Structure of the linked list class Node { constructor(){ this.data = 0; this.next = null; } } var head = null; // Function to create nodes of // the linked list function CreateLinkedList(new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; } // Function to print the linked list function printLinkedList() { var temp; temp = head; // Traversing linked list while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Driver Code CreateLinkedList(1); CreateLinkedList(2); CreateLinkedList(3); CreateLinkedList(4); printLinkedList(); // This code is contributed by umadevi9616</script> Output: 4 3 2 1 Linked list in Stack vs Heap Memory sweetyty gfgking shikhasingrajput 29AjayKumar umadevi9616 sagartomar9927 surinderdawra388 memory-management Data Structures Heap Linked List Stack Data Structures Linked List Stack Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Hashing | A Complete Tutorial What is Data Structure: Types, Classifications and Applications TCS NQT Coding Sheet Find if there is a path between two vertices in an undirected graph HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 70, "s": 54, "text": "Pre-requisite: " }, { "code": null, "e": 127, "s": 70, "text": "Linked List Data StructureStack vsHeap Memory Allocation" }, { "code": null, "e": 409, "s": 127, "text": "The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind it." }, { "code": null, "e": 430, "s": 409, "text": "Stack vs Heap Memory" }, { "code": null, "e": 765, "s": 430, "text": "The computer’s memory is divided into heap and stack memory segments. Stack memory segment is relatively small so it is mainly used for operations like recursion or control jump statements like goto statement. Due to the small size of the stack segment, it is not used for deep recursion levels as it may throw a stack overflow error." }, { "code": null, "e": 982, "s": 765, "text": "On the other hand, a linked list has the major advantage of dynamically expanding itself when needed without worrying about memory consumption. This is the reason why heap is preferred for storing linked list-object." }, { "code": null, "e": 1029, "s": 982, "text": "Why linked list is not stored in stack memory?" }, { "code": null, "e": 1490, "s": 1029, "text": "The question of why one cannot make a linked list with stack memory is due to the scope rules and automatic memory management on the stack. The basic idea of a linked list is to link nodes together based on their memory address. If each node is created on the stack then those nodes will be deleted after they go out of scope, so even if the user keeps pointers to their memory address it is not safe to assume that they won’t be overwritten by something else." }, { "code": null, "e": 1629, "s": 1490, "text": "The linked list can be implemented on the stack memory as well. Below is the C++ implementation of creating a linked list in stack memory:" }, { "code": null, "e": 1633, "s": 1629, "text": "C++" }, { "code": null, "e": 1638, "s": 1633, "text": "Java" }, { "code": null, "e": 1641, "s": 1638, "text": "C#" }, { "code": null, "e": 1652, "s": 1641, "text": "Javascript" }, { "code": "// C++ program to implement// linked list in stack#include <iostream>using namespace std; // Structure of the linked liststruct Node { int data; struct Node* next; // Constructor Node(int x) { data = x; next = NULL; }}* head = NULL; // Function to print the linked listvoid printLinkedList(Node* head){ struct Node* temp = head; // Traversing linked list while (temp) { cout << temp->data << \" \"; temp = temp->next; }} // Driver codeint main(){ // Creation of linked list in stack struct Node first = Node(1); struct Node second = Node(2); struct Node third = Node(3); struct Node fourth = Node(4); head = &first; // 1 -> 2 -> 3 -> 4 first.next = &second; second.next = &third; third.next = &fourth; fourth.next = NULL; // Printing the elements of // a linked list printLinkedList(head); return 0;}", "e": 2560, "s": 1652, "text": null }, { "code": "// Java program to implement// linked list in stack import java.util.*; class GFG{ // Structure of the linked liststatic class Node { int data; Node next; // Constructor Node(int x) { data = x; next = null; }};static Node head = null; // Function to print the linked liststatic void printLinkedList(Node head){ Node temp = head; // Traversing linked list while (temp!=null) { System.out.print(temp.data+ \" \"); temp = temp.next; }} // Driver codepublic static void main(String[] args){ // Creation of linked list in stack Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; // Printing the elements of // a linked list printLinkedList(head); }} // This code contributed by shikhasingrajput", "e": 3517, "s": 2560, "text": null }, { "code": "// C# program to implement// linked list in stackusing System;using System.Collections.Generic; public class GFG{ // Structure of the linked list class Node { public int data; public Node next; // Constructor public Node(int x) { data = x; next = null; } }; static Node head = null; // Function to print the linked list static void printList(Node head) { Node temp = head; // Traversing linked list while (temp!=null) { Console.Write(temp.data+ \" \"); temp = temp.next; } } // Driver code public static void Main(String[] args) { // Creation of linked list in stack Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; // Printing the elements of // a linked list printList(head); }} // This code is contributed by shikhasingrajput", "e": 4524, "s": 3517, "text": null }, { "code": "<script>// Javascript program to implement// linked list in stack // Structure of the linked listclass Node { // Constructor constructor(x) { this.data = x; this.next = null; }} // Function to print the linked listfunction printLinkedList(head) { let temp = head; // Traversing linked list while (temp) { document.write(temp.data + \" \"); temp = temp.next; }} // Driver code // Creation of linked list in stacklet first = new Node(1);let second = new Node(2);let third = new Node(3);let fourth = new Node(4); head = first; // 1 -> 2 -> 3 -> 4first.next = second;second.next = third;third.next = fourth;fourth.next = null; // Printing the elements of// a linked listprintLinkedList(head); // This code is contributed by gfgking.</script>", "e": 5311, "s": 4524, "text": null }, { "code": null, "e": 5319, "s": 5311, "text": "Output:" }, { "code": null, "e": 5328, "s": 5319, "text": "1 2 3 4 " }, { "code": null, "e": 5398, "s": 5328, "text": "Condition when linked list implementation on the stack will not work:" }, { "code": null, "e": 5638, "s": 5398, "text": "The above code won’t work if we write the logic of the creation of a linked list in a separate function and the logic of printing the elements of the linked list in a separate function. Below is its C++ implementation of the above concept:" }, { "code": null, "e": 5642, "s": 5638, "text": "C++" }, { "code": null, "e": 5647, "s": 5642, "text": "Java" }, { "code": null, "e": 5650, "s": 5647, "text": "C#" }, { "code": null, "e": 5661, "s": 5650, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Structure of the linked liststruct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; }}* head = NULL; // Function to return the head pointer// of the created linked listNode* CreateLinkedList(){ struct Node first = Node(1); struct Node second = Node(2); struct Node third = Node(3); struct Node fourth = Node(4); head = &first; // 1->2->3->4 first.next = &second; second.next = &third; third.next = &fourth; fourth.next = NULL; return head;} // Function to print the linked listvoid printLinkedList(Node* head){ struct Node* temp = head; // Traversing linked list while (temp) { cout << temp->data << \" \"; temp = temp->next; }} // Driver Codeint main(){ struct Node* head = CreateLinkedList(); printLinkedList(head); return 0;}", "e": 6605, "s": 5661, "text": null }, { "code": "// Java program to implement// the above approach import java.util.*; class GFG{ // Structure of the linked liststatic class Node { int data; Node next; Node(int x) { data = x; next = null; }}static Node head = null; // Function to return the head pointer// of the created linked liststatic Node CreateLinkedList(){ Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; return head;} // Function to print the linked liststatic void printLinkedList(Node head){ Node temp = head; // Traversing linked list while (temp!=null) { System.out.print(temp.data+ \" \"); temp = temp.next; }} // Driver Codepublic static void main(String[] args){ Node head = CreateLinkedList(); printLinkedList(head);}} // This code is contributed by 29AjayKumar", "e": 7598, "s": 6605, "text": null }, { "code": "// C# program to implement// the above approach using System; public class GFG{ // Structure of the linked list class Node { public int data; public Node next; public Node(int x) { data = x; next = null; } } static Node head = null; // Function to return the head pointer // of the created linked list static Node CreateList() { Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; return head; } // Function to print the linked list static void printList(Node head) { Node temp = head; // Traversing linked list while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } } // Driver Code public static void Main(String[] args) { Node head = CreateList(); printList(head); }} // This code is contributed by shikhasingrajput", "e": 8611, "s": 7598, "text": null }, { "code": "<script> // javascript program to implement// the above approach // Structure of the linked list class Node { constructor( x) { this.data = x; this.next = null; } } var head = null; // Function to return the head pointer // of the created linked list function CreateLinkedList() { var first = new Node(1); var second = new Node(2); var third = new Node(3); var fourth = new Node(4); head = first; // 1.2.3.4 first.next = second; second.next = third; third.next = fourth; fourth.next = null; return head; } // Function to print the linked list function printLinkedList( head) { var temp = head; // Traversing linked list while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Driver Code var head = CreateLinkedList(); printLinkedList(head); // This code contributed by shikhasingrajput</script>", "e": 9666, "s": 8611, "text": null }, { "code": null, "e": 9679, "s": 9666, "text": "Explanation:" }, { "code": null, "e": 10049, "s": 9679, "text": "The above code gives the verdict as SEGMENTATION FAULT. The reason behind it is that during the creation of the linked list in the stack memory, all the objects created by a function will be disappeared as the stack frame is popped whenever the function ends or returns. Refer to this article to know the reason behind the popping of stack frame whenever function ends." }, { "code": null, "e": 10091, "s": 10049, "text": "Why linked list is stored in heap memory?" }, { "code": null, "e": 10469, "s": 10091, "text": "In a linked list, when there is a need to store more data, we can allocate the memory at run-time by using malloc or a new function in C/ C++. So dynamic memory allocation reserve size from heap area, therefore, a linked list is stored in heap memory.If there is a need to store linked lists in the stack area then implement linked lists without using malloc or a new function." }, { "code": null, "e": 10591, "s": 10469, "text": "Below is the C++ program to show how to implement a linked list in heap memory without throwing segmentation fault error:" }, { "code": null, "e": 10595, "s": 10591, "text": "C++" }, { "code": null, "e": 10600, "s": 10595, "text": "Java" }, { "code": null, "e": 10603, "s": 10600, "text": "C#" }, { "code": null, "e": 10614, "s": 10603, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Structure of the linked liststruct Node { int data; struct Node* next;};struct Node* head = NULL; // Function to create nodes of// the linked listvoid CreateLinkedList(int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = head; head = new_node;} // Function to print the linked listvoid printLinkedList(){ struct Node* temp; temp = head; // Traversing linked list while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; }} // Driver Codeint main(){ CreateLinkedList(1); CreateLinkedList(2); CreateLinkedList(3); CreateLinkedList(4); printLinkedList(); return 0;}", "e": 11419, "s": 10614, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;public class GFG{ // Structure of the linked liststatic class Node { int data; Node next;};static Node head = null; // Function to create nodes of// the linked liststatic void CreateLinkedList(int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node;} // Function to print the linked liststatic void printLinkedList(){ Node temp; temp = head; // Traversing linked list while (temp != null) { System.out.print(temp.data+ \" \"); temp = temp.next; }} // Driver Codepublic static void main(String[] args){ CreateLinkedList(1); CreateLinkedList(2); CreateLinkedList(3); CreateLinkedList(4); printLinkedList();}} // This code is contributed by 29AjayKumar", "e": 12249, "s": 11419, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; public class GFG { // Structure of the linked list public class Node { public int data; public Node next; }; static Node head = null; // Function to create nodes of // the linked list static void CreateList(int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; } // Function to print the linked list static void printList() { Node temp; temp = head; // Traversing linked list while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } } // Driver Code public static void Main(String[] args) { CreateList(1); CreateList(2); CreateList(3); CreateList(4); printList(); }} // This code is contributed by umadevi9616", "e": 13104, "s": 12249, "text": null }, { "code": "<script>// javascript program to implement// the above approach // Structure of the linked list class Node { constructor(){ this.data = 0; this.next = null; } } var head = null; // Function to create nodes of // the linked list function CreateLinkedList(new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; } // Function to print the linked list function printLinkedList() { var temp; temp = head; // Traversing linked list while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Driver Code CreateLinkedList(1); CreateLinkedList(2); CreateLinkedList(3); CreateLinkedList(4); printLinkedList(); // This code is contributed by umadevi9616</script>", "e": 14020, "s": 13104, "text": null }, { "code": null, "e": 14028, "s": 14020, "text": "Output:" }, { "code": null, "e": 14036, "s": 14028, "text": "4 3 2 1" }, { "code": null, "e": 14072, "s": 14036, "text": "Linked list in Stack vs Heap Memory" }, { "code": null, "e": 14081, "s": 14072, "text": "sweetyty" }, { "code": null, "e": 14089, "s": 14081, "text": "gfgking" }, { "code": null, "e": 14106, "s": 14089, "text": "shikhasingrajput" }, { "code": null, "e": 14118, "s": 14106, "text": "29AjayKumar" }, { "code": null, "e": 14130, "s": 14118, "text": "umadevi9616" }, { "code": null, "e": 14145, "s": 14130, "text": "sagartomar9927" }, { "code": null, "e": 14162, "s": 14145, "text": "surinderdawra388" }, { "code": null, "e": 14180, "s": 14162, "text": "memory-management" }, { "code": null, "e": 14196, "s": 14180, "text": "Data Structures" }, { "code": null, "e": 14201, "s": 14196, "text": "Heap" }, { "code": null, "e": 14213, "s": 14201, "text": "Linked List" }, { "code": null, "e": 14219, "s": 14213, "text": "Stack" }, { "code": null, "e": 14235, "s": 14219, "text": "Data Structures" }, { "code": null, "e": 14247, "s": 14235, "text": "Linked List" }, { "code": null, "e": 14253, "s": 14247, "text": "Stack" }, { "code": null, "e": 14258, "s": 14253, "text": "Heap" }, { "code": null, "e": 14356, "s": 14258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14388, "s": 14356, "text": "Introduction to Data Structures" }, { "code": null, "e": 14426, "s": 14388, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 14490, "s": 14426, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 14511, "s": 14490, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 14579, "s": 14511, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 14588, "s": 14579, "text": "HeapSort" }, { "code": null, "e": 14644, "s": 14588, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 14656, "s": 14644, "text": "Binary Heap" }, { "code": null, "e": 14688, "s": 14656, "text": "Introduction to Data Structures" } ]
Formatted Output in Java
String provides format() method can be used to print formatted output in java. String provides format() method can be used to print formatted output in java. System.out.printf() method can be used to print formatted output in java. System.out.printf() method can be used to print formatted output in java. Following example returns a formatted string value by using a specific locale, format and arguments in format() method import java.util.*; public class StringFormat { public static void main(String[] args) { double e = Math.E; System.out.format("%f%n", e); System.out.format(Locale.GERMANY, "%-10.4f%n%n", e); } } The above code sample will produce the following result. 2.718282 2,7183 The following is an another sample example of format strings. public class HelloWorld { public static void main(String []args) { String name = "Hello World"; String s1 = String.format("name %s", name); String s2 = String.format("value %f",32.33434); String s3 = String.format("value %32.12f",32.33434); System.out.print(s1); System.out.print("\n"); System.out.print(s2); System.out.print("\n"); System.out.print(s3); System.out.print("\n"); } } The above code sample will produce the following result. name Hello World value 32.334340 value 32.334340000000
[ { "code": null, "e": 1141, "s": 1062, "text": "String provides format() method can be used to print formatted output in java." }, { "code": null, "e": 1220, "s": 1141, "text": "String provides format() method can be used to print formatted output in java." }, { "code": null, "e": 1294, "s": 1220, "text": "System.out.printf() method can be used to print formatted output in java." }, { "code": null, "e": 1368, "s": 1294, "text": "System.out.printf() method can be used to print formatted output in java." }, { "code": null, "e": 1487, "s": 1368, "text": "Following example returns a formatted string value by using a specific locale, format and arguments in format() method" }, { "code": null, "e": 1708, "s": 1487, "text": "import java.util.*;\n\npublic class StringFormat {\n public static void main(String[] args) {\n\n double e = Math.E;\n System.out.format(\"%f%n\", e);\n System.out.format(Locale.GERMANY, \"%-10.4f%n%n\", e);\n }\n}" }, { "code": null, "e": 1765, "s": 1708, "text": "The above code sample will produce the following result." }, { "code": null, "e": 1781, "s": 1765, "text": "2.718282\n2,7183" }, { "code": null, "e": 1843, "s": 1781, "text": "The following is an another sample example of format strings." }, { "code": null, "e": 2293, "s": 1843, "text": "public class HelloWorld {\n public static void main(String []args) {\n\n String name = \"Hello World\";\n String s1 = String.format(\"name %s\", name);\n String s2 = String.format(\"value %f\",32.33434);\n String s3 = String.format(\"value %32.12f\",32.33434);\n System.out.print(s1);\n System.out.print(\"\\n\");\n System.out.print(s2);\n System.out.print(\"\\n\");\n System.out.print(s3);\n System.out.print(\"\\n\");\n }\n}" }, { "code": null, "e": 2350, "s": 2293, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2405, "s": 2350, "text": "name Hello World\nvalue 32.334340\nvalue 32.334340000000" } ]
chgrp - Unix, Linux Command
chgrp - To change group ownership. chgrp [Options]... {Group | --reference=File} File... 'chgrp' command changes the group ownership of each given File to Group (which can be either a group name or a numeric group id) or to match the same group as an existing reference file. To Make oracleadmin the owner of the database directory $ chgrp oracleadmin /usr/database 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10612, "s": 10577, "text": "chgrp - To change group ownership." }, { "code": null, "e": 10666, "s": 10612, "text": "chgrp [Options]... {Group | --reference=File} File..." }, { "code": null, "e": 10853, "s": 10666, "text": "'chgrp' command changes the group ownership of each given File to Group (which can be either a group name or a numeric group id) or to match the same group as an existing reference file." }, { "code": null, "e": 10909, "s": 10853, "text": "To Make oracleadmin the owner of the database directory" }, { "code": null, "e": 10944, "s": 10909, "text": "$ chgrp oracleadmin /usr/database\n" }, { "code": null, "e": 10979, "s": 10944, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11007, "s": 10979, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11041, "s": 11007, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11058, "s": 11041, "text": " Frahaan Hussain" }, { "code": null, "e": 11091, "s": 11058, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11102, "s": 11091, "text": " Pradeep D" }, { "code": null, "e": 11137, "s": 11102, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11153, "s": 11137, "text": " Musab Zayadneh" }, { "code": null, "e": 11186, "s": 11153, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11198, "s": 11186, "text": " GUHARAJANM" }, { "code": null, "e": 11230, "s": 11198, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11238, "s": 11230, "text": " Uplatz" }, { "code": null, "e": 11245, "s": 11238, "text": " Print" }, { "code": null, "e": 11256, "s": 11245, "text": " Add Notes" } ]
Python Comments - GeeksforGeeks
11 Apr, 2022 Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. Comments enhance the readability of the code and help the programmers to understand the code very carefully. There are three types of comments in Python – Single line Comments Multiline Comments Docstring Comments Python3 # Python program to demonstrate comments # sample commentname = "geeksforgeeks"print(name) Output: geeksforgeeks In the above example, it can be seen that comments are ignored by the interpreter during the execution of the program. Comments are generally used for the following purposes: Code Readability Explanation of the code or Metadata of the project Prevent execution of code To include resources There are three main kinds of comments in Python. They are: Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment: Example: Python3 # Print “GeeksforGeeks !” to consoleprint("GeeksforGeeks") GeeksforGeeks Python does not provide the option for multiline comments. However, there are different ways through which we can write multiline comments. We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered as a single-line comment. Python3 # Python program to demonstrate# multiline commentsprint("Multiline comments") Multiline comments Python ignores the string literals that are not assigned to a variable so we can use these string literals as a comment. Python3 'This will be ignored by Python' On executing the above code we can see that there will not be any output so we use the strings with triple quotes(“””) as multiline comments. Python3 """ Python program to demonstrate multiline comments"""print("Multiline comments") Multiline comments Python docstring is the string literals with triple quotes that are appeared right after the function. It is used to associate documentation that has been written with Python modules, functions, classes, and methods. It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the __doc__ attribute. Example: Python3 def multiply(a, b): """Multiplies the value of a and b""" return a*b # Print the docstring of multiply functionprint(multiply.__doc__) Output: Multiplies the value of a and b nikhilaggarwal3 yahiadjem python-basics python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23926, "s": 23898, "text": "\n11 Apr, 2022" }, { "code": null, "e": 24200, "s": 23926, "text": "Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. Comments enhance the readability of the code and help the programmers to understand the code very carefully. There are three types of comments in Python – " }, { "code": null, "e": 24221, "s": 24200, "text": "Single line Comments" }, { "code": null, "e": 24240, "s": 24221, "text": "Multiline Comments" }, { "code": null, "e": 24259, "s": 24240, "text": "Docstring Comments" }, { "code": null, "e": 24267, "s": 24259, "text": "Python3" }, { "code": "# Python program to demonstrate comments # sample commentname = \"geeksforgeeks\"print(name)", "e": 24358, "s": 24267, "text": null }, { "code": null, "e": 24367, "s": 24358, "text": "Output: " }, { "code": null, "e": 24381, "s": 24367, "text": "geeksforgeeks" }, { "code": null, "e": 24500, "s": 24381, "text": "In the above example, it can be seen that comments are ignored by the interpreter during the execution of the program." }, { "code": null, "e": 24557, "s": 24500, "text": "Comments are generally used for the following purposes: " }, { "code": null, "e": 24574, "s": 24557, "text": "Code Readability" }, { "code": null, "e": 24625, "s": 24574, "text": "Explanation of the code or Metadata of the project" }, { "code": null, "e": 24651, "s": 24625, "text": "Prevent execution of code" }, { "code": null, "e": 24672, "s": 24651, "text": "To include resources" }, { "code": null, "e": 24733, "s": 24672, "text": "There are three main kinds of comments in Python. They are: " }, { "code": null, "e": 25148, "s": 24733, "text": "Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:" }, { "code": null, "e": 25158, "s": 25148, "text": "Example: " }, { "code": null, "e": 25166, "s": 25158, "text": "Python3" }, { "code": "# Print “GeeksforGeeks !” to consoleprint(\"GeeksforGeeks\")", "e": 25225, "s": 25166, "text": null }, { "code": null, "e": 25239, "s": 25225, "text": "GeeksforGeeks" }, { "code": null, "e": 25379, "s": 25239, "text": "Python does not provide the option for multiline comments. However, there are different ways through which we can write multiline comments." }, { "code": null, "e": 25512, "s": 25379, "text": "We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered as a single-line comment." }, { "code": null, "e": 25520, "s": 25512, "text": "Python3" }, { "code": "# Python program to demonstrate# multiline commentsprint(\"Multiline comments\")", "e": 25599, "s": 25520, "text": null }, { "code": null, "e": 25618, "s": 25599, "text": "Multiline comments" }, { "code": null, "e": 25740, "s": 25618, "text": "Python ignores the string literals that are not assigned to a variable so we can use these string literals as a comment. " }, { "code": null, "e": 25748, "s": 25740, "text": "Python3" }, { "code": "'This will be ignored by Python'", "e": 25781, "s": 25748, "text": null }, { "code": null, "e": 25923, "s": 25781, "text": "On executing the above code we can see that there will not be any output so we use the strings with triple quotes(“””) as multiline comments." }, { "code": null, "e": 25931, "s": 25923, "text": "Python3" }, { "code": "\"\"\" Python program to demonstrate multiline comments\"\"\"print(\"Multiline comments\")", "e": 26014, "s": 25931, "text": null }, { "code": null, "e": 26033, "s": 26014, "text": "Multiline comments" }, { "code": null, "e": 26410, "s": 26033, "text": "Python docstring is the string literals with triple quotes that are appeared right after the function. It is used to associate documentation that has been written with Python modules, functions, classes, and methods. It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the __doc__ attribute." }, { "code": null, "e": 26419, "s": 26410, "text": "Example:" }, { "code": null, "e": 26427, "s": 26419, "text": "Python3" }, { "code": "def multiply(a, b): \"\"\"Multiplies the value of a and b\"\"\" return a*b # Print the docstring of multiply functionprint(multiply.__doc__)", "e": 26569, "s": 26427, "text": null }, { "code": null, "e": 26578, "s": 26569, "text": "Output: " }, { "code": null, "e": 26610, "s": 26578, "text": "Multiplies the value of a and b" }, { "code": null, "e": 26626, "s": 26610, "text": "nikhilaggarwal3" }, { "code": null, "e": 26636, "s": 26626, "text": "yahiadjem" }, { "code": null, "e": 26650, "s": 26636, "text": "python-basics" }, { "code": null, "e": 26665, "s": 26650, "text": "python-utility" }, { "code": null, "e": 26672, "s": 26665, "text": "Python" }, { "code": null, "e": 26770, "s": 26672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26779, "s": 26770, "text": "Comments" }, { "code": null, "e": 26792, "s": 26779, "text": "Old Comments" }, { "code": null, "e": 26824, "s": 26792, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26880, "s": 26824, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26922, "s": 26880, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26964, "s": 26922, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27000, "s": 26964, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27039, "s": 27000, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27061, "s": 27039, "text": "Defaultdict in Python" }, { "code": null, "e": 27092, "s": 27061, "text": "Python | os.path.join() method" }, { "code": null, "e": 27119, "s": 27092, "text": "Python Classes and Objects" } ]
Find a matrix or vector norm using NumPy - GeeksforGeeks
06 Jun, 2021 To find a matrix or vector norm we use function numpy.linalg.norm() of Python library Numpy. This function returns one of the seven matrix norms or one of the infinite vector norms depending upon the value of its parameters. Syntax: numpy.linalg.norm(x, ord=None, axis=None)Parameters: x: input ord: order of norm axis: None, returns either a vector or a matrix norm and if it is an integer value, it specifies the axis of x along which the vector norm will be computed Example 1: Python3 # import libraryimport numpy as np # initialize vectorvec = np.arange(10) # compute norm of vectorvec_norm = np.linalg.norm(vec) print("Vector norm:")print(vec_norm) Output: Vector norm: 16.881943016134134 The above code computes the vector norm of a vector of dimension (1, 10)Example 2: Python3 # import libraryimport numpy as np # initialize matrixmat = np.array([[ 1, 2, 3], [4, 5, 6]]) # compute norm of matrixmat_norm = np.linalg.norm(mat) print("Matrix norm:")print(mat_norm) Output: Matrix norm: 9.539392014169456 Here, we get the matrix norm for a matrix of dimension (2, 3)Example 3: To compute matrix norm along a particular axis – Python3 # import libraryimport numpy as np mat = np.array([[ 1, 2, 3], [4, 5, 6]]) # compute matrix num along axismat_norm = np.linalg.norm(mat, axis = 1) print("Matrix norm along particular axis :")print(mat_norm) Output: Matrix norm along particular axis : [3.74165739 8.77496439] This code generates a matrix norm and the output is also a matrix of shape (1, 2)Example 4: Python3 # import libraryimport numpy as np # initialize vectorvec = np.arange(9) # convert vector into matrixmat = vec.reshape((3, 3)) # compute norm of vectorvec_norm = np.linalg.norm(vec) print("Vector norm:")print(vec_norm) # computer norm of matrixmat_norm = np.linalg.norm(mat) print("Matrix norm:")print(mat_norm) Output: Vector norm: 14.2828568570857 Matrix norm: 14.2828568570857 From the above output, it is clear if we convert a vector into a matrix, or if both have same elements then their norm will be equal too. simmytarika5 Python numpy-Linear Algebra Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n06 Jun, 2021" }, { "code": null, "e": 24438, "s": 24212, "text": "To find a matrix or vector norm we use function numpy.linalg.norm() of Python library Numpy. This function returns one of the seven matrix norms or one of the infinite vector norms depending upon the value of its parameters. " }, { "code": null, "e": 24685, "s": 24438, "text": "Syntax: numpy.linalg.norm(x, ord=None, axis=None)Parameters: x: input ord: order of norm axis: None, returns either a vector or a matrix norm and if it is an integer value, it specifies the axis of x along which the vector norm will be computed " }, { "code": null, "e": 24698, "s": 24685, "text": "Example 1: " }, { "code": null, "e": 24706, "s": 24698, "text": "Python3" }, { "code": "# import libraryimport numpy as np # initialize vectorvec = np.arange(10) # compute norm of vectorvec_norm = np.linalg.norm(vec) print(\"Vector norm:\")print(vec_norm)", "e": 24872, "s": 24706, "text": null }, { "code": null, "e": 24881, "s": 24872, "text": "Output: " }, { "code": null, "e": 24913, "s": 24881, "text": "Vector norm:\n16.881943016134134" }, { "code": null, "e": 24998, "s": 24913, "text": "The above code computes the vector norm of a vector of dimension (1, 10)Example 2: " }, { "code": null, "e": 25006, "s": 24998, "text": "Python3" }, { "code": "# import libraryimport numpy as np # initialize matrixmat = np.array([[ 1, 2, 3], [4, 5, 6]]) # compute norm of matrixmat_norm = np.linalg.norm(mat) print(\"Matrix norm:\")print(mat_norm)", "e": 25206, "s": 25006, "text": null }, { "code": null, "e": 25215, "s": 25206, "text": "Output: " }, { "code": null, "e": 25246, "s": 25215, "text": "Matrix norm:\n9.539392014169456" }, { "code": null, "e": 25369, "s": 25246, "text": "Here, we get the matrix norm for a matrix of dimension (2, 3)Example 3: To compute matrix norm along a particular axis – " }, { "code": null, "e": 25377, "s": 25369, "text": "Python3" }, { "code": "# import libraryimport numpy as np mat = np.array([[ 1, 2, 3], [4, 5, 6]]) # compute matrix num along axismat_norm = np.linalg.norm(mat, axis = 1) print(\"Matrix norm along particular axis :\")print(mat_norm)", "e": 25599, "s": 25377, "text": null }, { "code": null, "e": 25608, "s": 25599, "text": "Output: " }, { "code": null, "e": 25668, "s": 25608, "text": "Matrix norm along particular axis :\n[3.74165739 8.77496439]" }, { "code": null, "e": 25762, "s": 25668, "text": "This code generates a matrix norm and the output is also a matrix of shape (1, 2)Example 4: " }, { "code": null, "e": 25770, "s": 25762, "text": "Python3" }, { "code": "# import libraryimport numpy as np # initialize vectorvec = np.arange(9) # convert vector into matrixmat = vec.reshape((3, 3)) # compute norm of vectorvec_norm = np.linalg.norm(vec) print(\"Vector norm:\")print(vec_norm) # computer norm of matrixmat_norm = np.linalg.norm(mat) print(\"Matrix norm:\")print(mat_norm)", "e": 26082, "s": 25770, "text": null }, { "code": null, "e": 26091, "s": 26082, "text": "Output: " }, { "code": null, "e": 26151, "s": 26091, "text": "Vector norm:\n14.2828568570857\nMatrix norm:\n14.2828568570857" }, { "code": null, "e": 26290, "s": 26151, "text": "From the above output, it is clear if we convert a vector into a matrix, or if both have same elements then their norm will be equal too. " }, { "code": null, "e": 26303, "s": 26290, "text": "simmytarika5" }, { "code": null, "e": 26331, "s": 26303, "text": "Python numpy-Linear Algebra" }, { "code": null, "e": 26344, "s": 26331, "text": "Python-numpy" }, { "code": null, "e": 26351, "s": 26344, "text": "Python" }, { "code": null, "e": 26449, "s": 26351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26458, "s": 26449, "text": "Comments" }, { "code": null, "e": 26471, "s": 26458, "text": "Old Comments" }, { "code": null, "e": 26503, "s": 26471, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26559, "s": 26503, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26580, "s": 26559, "text": "Python OOPs Concepts" }, { "code": null, "e": 26619, "s": 26580, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26661, "s": 26619, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26688, "s": 26661, "text": "Python Classes and Objects" }, { "code": null, "e": 26719, "s": 26688, "text": "Python | os.path.join() method" }, { "code": null, "e": 26761, "s": 26719, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26797, "s": 26761, "text": "Python | Pandas dataframe.groupby()" } ]
Your Ultimate Data Science Statistics & Mathematics Cheat Sheet | by Andre Ye | Towards Data Science
All images created by author unless stated otherwise. In data science, having a solid understanding of the statistics and mathematics of your data is essential to applying and interpreting machine learning methods appropriately and effectively. Classifier Metrics. Confusion matrix, sensitivity, recall, specificity, precision, F1 score. What they are, when to use them, how to implement them. Regressor Metrics. MAE, MSE, RMSE, MSLE, R2. What they are, when to use it, how to implement it. Statistical Indicators. Correlation coefficient, covariance, variance, standard deviation. How to use and interpret them. Types of Distributions. The three most common distributions, how to identify them. Classifier metrics are metrics used to evaluate the performance of machine learning classifiers — models that put each training example into one of several discrete categories. Confusion Matrix is a matrix used to indicate a classifier’s predictions on labels. It contains four cells, each corresponding to one combination of a predicted true or false and an actual true or false. Many classifier metrics are based on the confusion matrix, so it’s helpful to keep an image of it stored in your mind. Sensitivity/Recall is the number of positives that were accurately predicted. This is calculated as TP/(TP+FN) (note that false negatives are positives). Sensitivity is a good metric to use in contexts where correctly predicting positives is important, like medical diagnoses. In some cases, false positives can be dangerous, but it is generally agreed upon that false negatives (e.g. a diagnosis of ‘no cancer’ in someone who does have cancer) are more deadly. By having model maximize sensitivity, its ability to prioritize correctly classify positives is targeted. Specificity is the number of negatives that were accurately predicted, calculated as TN/(TN+FP) (note that false positives are actually negatives). Like sensitivity, specificity is a helpful metric in the scenario that accurately classifying negatives is more important than classifying positives. Precision can be thought of as the opposite of sensitivity or recall in that while sensitivity measures the proportion of actually true observations that were predicted as true, precision measures the proportion of predicted true observations that actually were true. This is measured as TP/(TP+FP). Precision and recall together provide a rounded view of a model’s performance. F1 Score combines precision and recall through the harmonic mean. The exact formula for it is (2 × precision × recall) / (precision + recall). The harmonic mean is used since it penalizes more extreme values, opposed to the mean, which is naïve in that it weights all errors the same. Detection/Accuracy Rate is the number of items correctly classified, calculated as the sum of True Positives and True Negatives divided by the sum of all four confusion matrix quadrants. This accuracy rate weights positives and negatives equally, instead of prioritizing one over the other. Using F1 Score vs Accuracy: The F1 score should be used when not making mistakes is more important (False Positives and False Negatives being penalized more heavily), whereas accuracy should be used when the model’s goal is to optimize performance. Both metrics are used based on context, and perform differently depending on the data. Generally, however, the F1-score is better for imbalanced classes (for example, cancer diagnoses, when there are vastly more negatives than positives) whereas accuracy is better for more balanced classes. Implementing metrics follows the following format. Discussed metric names in sklearn are: Confusion Matrix: confusion_matrix Sensitivity/Recall: recall_score Precision: precision_score F1 Score: f1_score Accuracy: accuracy_score Balanced Accuracy (for unevenly distributed classes): balanced_accuracy_score Regression metrics are used to measure how well a model that puts a training example on a continuous scale, such as determining the price of a house. Mean Absolute Error (MAE) is perhaps the most common and interpretable regression metric. MAE calculates the difference between each data point’s predicted y-value and the real y-value, then averages every difference (the difference being calculated as the absolute value of one value minus the other). Median Absolute Error is another metric of evaluating the average error. While it has the benefit of moving the error distribution lower by focusing on the middle error value, it also tends to ignore extremely high or low errors that are factored into the mean absolute error. Mean Square Error (MSE) is another commonly used regression metric that ‘punishes’ higher errors more. For example, an error (difference) of 2 would be weighted as 4, whereas an error of 5 would be weighted as 25, meaning that MSE finds the difference between the two errors as 21, whereas MAE weights the difference at its face value — 3. MSE calculates the square of each data point’s predicted y-value and real y-value, then averages the squares. Root Mean Square Error (RMSE) is used to give a level of interpretability that mean square error lacks. By square-rooting the MSE, we achieve a metric similar to MAE in that it is on a similar scale, while still weighting higher errors at higher levels. Mean Squared Logarithmic Error (MSLE) is another common variation of the mean absolute error. Because of the logarithmic nature of the error, MSLE only cares about the percent differences. This means that MSLE will treat small differences between small values (for example, 4 and 3) the same as large differences on a large scale (for example, 1200 and 900). R2 is a commonly used metric (where r is known as the correlation coefficient) which measures how much a regression model represents the proportion of the variance for a dependent variable which can be explained by the independent variables. In short, it is a good metric of how well the data fits the regression model. Implementing metrics follows the following format. Discussed metric names in sklearn are: Mean Absolute Error: mean_absolute_error Median Absolute Error: median_absolute_error Mean Squared Error: mean_squared_error Root Mean Squared Error: root_mean_squared_error Mean Squared Logarithmic Error: mean_squared_log_error R2: r2_score Correlation is a statistical measure of how well two variables fluctuate together. Positive correlations mean that two variables fluctuate together (a positive change in one is a positive change to another), whereas negative correlations mean that two variable change opposite one another (a positive change in one is a negative change in another). The correlation coefficient, from +1 to -1, is also known as R. The correlation coefficient can be accessed using the .corr() function through Pandas DataFrames. Consider the following two sequences: seq1 = [0,0.5,0.74,1.5,2.9]seq2 = [4,4.9,8.2,8.3,12.9] With the constructor table = pd.DataFrame({‘a’:seq1,’b’:seq2}), a DataFrame with the two sequences is created. Calling table.corr() yields a correlation table. For example, in the correlation table, sequences A and B have a correlation of 0.95. The correlation table is symmetric and equal to 1 when a sequence is compared against itself. Covariance is, similarly to correlation, a measure of the property of a function of retaining its form when the variables are linearly transformed. Unlike correlation, however, covariance can take on any number while correlation is limited between a range. Because of this, correlation is more useful for determining the strength of the relationship between two variables. Because covariance has units (unlike correlation) and is affected by changes in the center or scale, it is less widely used as a stand-alone statistic. However, covariance is used in many statistics formulas, and is a useful figure to know. This can be done in Python with numpy.cov(a,b)[0][1], where a and b are the sequences to be compared. Variance is a measure of expectation of the squared deviation of a random variable from its mean. It informally measures how far a set of numbers are spread out from their mean. Variance can be measured in the statistics library (import statistics) with statistics.variance(list). Standard Deviation is the square root of the variance, and is a more scaled statistic for how spread out a distribution is. Standard deviation can be measured in the statistics library with statistics.stdev(list). Knowing your distributions are very important when dealing with data analysis and understanding which statistical and machine learning methods to use. While there are several types of mathematically specialized distributions, most of them can fit into these three distributions. Uniform Distribution is the easiest distribution — it is completely flat, or truly random. For example, which number of dots a die landed on (from 1 to 6) recorded for each of 6000 throws would yields a flat distribution, with approximately 1000 throws per number of dots. Uniform distributions have useful properties — for example, read how the Allied forces saved countless lives in World War II using statistical attributes of uniform distributions. medium.com Normal Distribution is a very common distribution that resembles a curve (one name for the distribution is the ‘Bell Curve’). Besides its common use in data science, it is where most things in the universe can be described by, like IQ or salary. It is characterized by the following features: 68% of the data is within one standard deviation of the mean. 95% of the data is within two standard deviations of the mean. 99.7% of the data is within three standard deviations of the mean. Many machine learning algorithms require a normal distribution among the data. For example, logistic regression requires the residuals be normally distributed. This can be visualized and recognized with a residplot(). Information and examples of the usage of this and other statistical models can be found here. Poisson Distribution can be thought of as a generalization of the normal distribution; a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time or space if these events occur with a known constant mean rate and independently of the time since the last event. With changing values of λ, the Poisson distribution shifts the mean left or right, with the capability of creating left-skewed or right-skewed data. If you found this cheat sheet helpful, feel free to upvote and bookmark the page for easy reference. If you enjoyed this cheat sheet, you may be interested in applying your statistics knowledge in other cheat-sheets. If you would like to see additional topics discussed in this cheat-sheet, feel free to let me know in the responses!
[ { "code": null, "e": 226, "s": 172, "text": "All images created by author unless stated otherwise." }, { "code": null, "e": 417, "s": 226, "text": "In data science, having a solid understanding of the statistics and mathematics of your data is essential to applying and interpreting machine learning methods appropriately and effectively." }, { "code": null, "e": 566, "s": 417, "text": "Classifier Metrics. Confusion matrix, sensitivity, recall, specificity, precision, F1 score. What they are, when to use them, how to implement them." }, { "code": null, "e": 663, "s": 566, "text": "Regressor Metrics. MAE, MSE, RMSE, MSLE, R2. What they are, when to use it, how to implement it." }, { "code": null, "e": 785, "s": 663, "text": "Statistical Indicators. Correlation coefficient, covariance, variance, standard deviation. How to use and interpret them." }, { "code": null, "e": 868, "s": 785, "text": "Types of Distributions. The three most common distributions, how to identify them." }, { "code": null, "e": 1045, "s": 868, "text": "Classifier metrics are metrics used to evaluate the performance of machine learning classifiers — models that put each training example into one of several discrete categories." }, { "code": null, "e": 1368, "s": 1045, "text": "Confusion Matrix is a matrix used to indicate a classifier’s predictions on labels. It contains four cells, each corresponding to one combination of a predicted true or false and an actual true or false. Many classifier metrics are based on the confusion matrix, so it’s helpful to keep an image of it stored in your mind." }, { "code": null, "e": 1936, "s": 1368, "text": "Sensitivity/Recall is the number of positives that were accurately predicted. This is calculated as TP/(TP+FN) (note that false negatives are positives). Sensitivity is a good metric to use in contexts where correctly predicting positives is important, like medical diagnoses. In some cases, false positives can be dangerous, but it is generally agreed upon that false negatives (e.g. a diagnosis of ‘no cancer’ in someone who does have cancer) are more deadly. By having model maximize sensitivity, its ability to prioritize correctly classify positives is targeted." }, { "code": null, "e": 2234, "s": 1936, "text": "Specificity is the number of negatives that were accurately predicted, calculated as TN/(TN+FP) (note that false positives are actually negatives). Like sensitivity, specificity is a helpful metric in the scenario that accurately classifying negatives is more important than classifying positives." }, { "code": null, "e": 2613, "s": 2234, "text": "Precision can be thought of as the opposite of sensitivity or recall in that while sensitivity measures the proportion of actually true observations that were predicted as true, precision measures the proportion of predicted true observations that actually were true. This is measured as TP/(TP+FP). Precision and recall together provide a rounded view of a model’s performance." }, { "code": null, "e": 2899, "s": 2613, "text": "F1 Score combines precision and recall through the harmonic mean. The exact formula for it is (2 × precision × recall) / (precision + recall). The harmonic mean is used since it penalizes more extreme values, opposed to the mean, which is naïve in that it weights all errors the same." }, { "code": null, "e": 3190, "s": 2899, "text": "Detection/Accuracy Rate is the number of items correctly classified, calculated as the sum of True Positives and True Negatives divided by the sum of all four confusion matrix quadrants. This accuracy rate weights positives and negatives equally, instead of prioritizing one over the other." }, { "code": null, "e": 3731, "s": 3190, "text": "Using F1 Score vs Accuracy: The F1 score should be used when not making mistakes is more important (False Positives and False Negatives being penalized more heavily), whereas accuracy should be used when the model’s goal is to optimize performance. Both metrics are used based on context, and perform differently depending on the data. Generally, however, the F1-score is better for imbalanced classes (for example, cancer diagnoses, when there are vastly more negatives than positives) whereas accuracy is better for more balanced classes." }, { "code": null, "e": 3782, "s": 3731, "text": "Implementing metrics follows the following format." }, { "code": null, "e": 3821, "s": 3782, "text": "Discussed metric names in sklearn are:" }, { "code": null, "e": 3856, "s": 3821, "text": "Confusion Matrix: confusion_matrix" }, { "code": null, "e": 3889, "s": 3856, "text": "Sensitivity/Recall: recall_score" }, { "code": null, "e": 3916, "s": 3889, "text": "Precision: precision_score" }, { "code": null, "e": 3935, "s": 3916, "text": "F1 Score: f1_score" }, { "code": null, "e": 3960, "s": 3935, "text": "Accuracy: accuracy_score" }, { "code": null, "e": 4038, "s": 3960, "text": "Balanced Accuracy (for unevenly distributed classes): balanced_accuracy_score" }, { "code": null, "e": 4188, "s": 4038, "text": "Regression metrics are used to measure how well a model that puts a training example on a continuous scale, such as determining the price of a house." }, { "code": null, "e": 4491, "s": 4188, "text": "Mean Absolute Error (MAE) is perhaps the most common and interpretable regression metric. MAE calculates the difference between each data point’s predicted y-value and the real y-value, then averages every difference (the difference being calculated as the absolute value of one value minus the other)." }, { "code": null, "e": 4768, "s": 4491, "text": "Median Absolute Error is another metric of evaluating the average error. While it has the benefit of moving the error distribution lower by focusing on the middle error value, it also tends to ignore extremely high or low errors that are factored into the mean absolute error." }, { "code": null, "e": 5218, "s": 4768, "text": "Mean Square Error (MSE) is another commonly used regression metric that ‘punishes’ higher errors more. For example, an error (difference) of 2 would be weighted as 4, whereas an error of 5 would be weighted as 25, meaning that MSE finds the difference between the two errors as 21, whereas MAE weights the difference at its face value — 3. MSE calculates the square of each data point’s predicted y-value and real y-value, then averages the squares." }, { "code": null, "e": 5472, "s": 5218, "text": "Root Mean Square Error (RMSE) is used to give a level of interpretability that mean square error lacks. By square-rooting the MSE, we achieve a metric similar to MAE in that it is on a similar scale, while still weighting higher errors at higher levels." }, { "code": null, "e": 5831, "s": 5472, "text": "Mean Squared Logarithmic Error (MSLE) is another common variation of the mean absolute error. Because of the logarithmic nature of the error, MSLE only cares about the percent differences. This means that MSLE will treat small differences between small values (for example, 4 and 3) the same as large differences on a large scale (for example, 1200 and 900)." }, { "code": null, "e": 6151, "s": 5831, "text": "R2 is a commonly used metric (where r is known as the correlation coefficient) which measures how much a regression model represents the proportion of the variance for a dependent variable which can be explained by the independent variables. In short, it is a good metric of how well the data fits the regression model." }, { "code": null, "e": 6202, "s": 6151, "text": "Implementing metrics follows the following format." }, { "code": null, "e": 6241, "s": 6202, "text": "Discussed metric names in sklearn are:" }, { "code": null, "e": 6282, "s": 6241, "text": "Mean Absolute Error: mean_absolute_error" }, { "code": null, "e": 6327, "s": 6282, "text": "Median Absolute Error: median_absolute_error" }, { "code": null, "e": 6366, "s": 6327, "text": "Mean Squared Error: mean_squared_error" }, { "code": null, "e": 6415, "s": 6366, "text": "Root Mean Squared Error: root_mean_squared_error" }, { "code": null, "e": 6470, "s": 6415, "text": "Mean Squared Logarithmic Error: mean_squared_log_error" }, { "code": null, "e": 6483, "s": 6470, "text": "R2: r2_score" }, { "code": null, "e": 6896, "s": 6483, "text": "Correlation is a statistical measure of how well two variables fluctuate together. Positive correlations mean that two variables fluctuate together (a positive change in one is a positive change to another), whereas negative correlations mean that two variable change opposite one another (a positive change in one is a negative change in another). The correlation coefficient, from +1 to -1, is also known as R." }, { "code": null, "e": 7032, "s": 6896, "text": "The correlation coefficient can be accessed using the .corr() function through Pandas DataFrames. Consider the following two sequences:" }, { "code": null, "e": 7087, "s": 7032, "text": "seq1 = [0,0.5,0.74,1.5,2.9]seq2 = [4,4.9,8.2,8.3,12.9]" }, { "code": null, "e": 7247, "s": 7087, "text": "With the constructor table = pd.DataFrame({‘a’:seq1,’b’:seq2}), a DataFrame with the two sequences is created. Calling table.corr() yields a correlation table." }, { "code": null, "e": 7426, "s": 7247, "text": "For example, in the correlation table, sequences A and B have a correlation of 0.95. The correlation table is symmetric and equal to 1 when a sequence is compared against itself." }, { "code": null, "e": 8040, "s": 7426, "text": "Covariance is, similarly to correlation, a measure of the property of a function of retaining its form when the variables are linearly transformed. Unlike correlation, however, covariance can take on any number while correlation is limited between a range. Because of this, correlation is more useful for determining the strength of the relationship between two variables. Because covariance has units (unlike correlation) and is affected by changes in the center or scale, it is less widely used as a stand-alone statistic. However, covariance is used in many statistics formulas, and is a useful figure to know." }, { "code": null, "e": 8142, "s": 8040, "text": "This can be done in Python with numpy.cov(a,b)[0][1], where a and b are the sequences to be compared." }, { "code": null, "e": 8423, "s": 8142, "text": "Variance is a measure of expectation of the squared deviation of a random variable from its mean. It informally measures how far a set of numbers are spread out from their mean. Variance can be measured in the statistics library (import statistics) with statistics.variance(list)." }, { "code": null, "e": 8637, "s": 8423, "text": "Standard Deviation is the square root of the variance, and is a more scaled statistic for how spread out a distribution is. Standard deviation can be measured in the statistics library with statistics.stdev(list)." }, { "code": null, "e": 8788, "s": 8637, "text": "Knowing your distributions are very important when dealing with data analysis and understanding which statistical and machine learning methods to use." }, { "code": null, "e": 8916, "s": 8788, "text": "While there are several types of mathematically specialized distributions, most of them can fit into these three distributions." }, { "code": null, "e": 9369, "s": 8916, "text": "Uniform Distribution is the easiest distribution — it is completely flat, or truly random. For example, which number of dots a die landed on (from 1 to 6) recorded for each of 6000 throws would yields a flat distribution, with approximately 1000 throws per number of dots. Uniform distributions have useful properties — for example, read how the Allied forces saved countless lives in World War II using statistical attributes of uniform distributions." }, { "code": null, "e": 9380, "s": 9369, "text": "medium.com" }, { "code": null, "e": 9673, "s": 9380, "text": "Normal Distribution is a very common distribution that resembles a curve (one name for the distribution is the ‘Bell Curve’). Besides its common use in data science, it is where most things in the universe can be described by, like IQ or salary. It is characterized by the following features:" }, { "code": null, "e": 9735, "s": 9673, "text": "68% of the data is within one standard deviation of the mean." }, { "code": null, "e": 9798, "s": 9735, "text": "95% of the data is within two standard deviations of the mean." }, { "code": null, "e": 9865, "s": 9798, "text": "99.7% of the data is within three standard deviations of the mean." }, { "code": null, "e": 10177, "s": 9865, "text": "Many machine learning algorithms require a normal distribution among the data. For example, logistic regression requires the residuals be normally distributed. This can be visualized and recognized with a residplot(). Information and examples of the usage of this and other statistical models can be found here." }, { "code": null, "e": 10661, "s": 10177, "text": "Poisson Distribution can be thought of as a generalization of the normal distribution; a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time or space if these events occur with a known constant mean rate and independently of the time since the last event. With changing values of λ, the Poisson distribution shifts the mean left or right, with the capability of creating left-skewed or right-skewed data." } ]
How to read an image file in external storage with runtime permission in android?
This example demonstrates How to read an image file in external storage with runtime permission in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <Button android:id = "@+id/read" android:text = "read" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <ImageView android:id = "@+id/imageView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken image view and button. When user click on button, it will take data from external storage and append the data to Image view. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_REQUEST_CODE<100; Button read; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView<findViewById(R.id.imageView); read<findViewById(R.id.read); read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String state<Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { if (Build.VERSION.SDK_INT > = 23) { if (checkPermission()) { File dir<new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/images.jpeg"); if (dir.exists()) { Log.d("path", dir.toString()); BitmapFactory.Options options<new BitmapFactory.Options(); options.inPreferredConfig<Bitmap.Config.ARGB_8888; Bitmap bitmap<BitmapFactory.decodeFile(String.valueOf(dir), options); imageView.setImageBitmap(bitmap); } } else { requestPermission(); // Code for permission } } else { File dir<new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/images.jpeg"); if (dir.exists()) { Log.d("path", dir.toString()); BitmapFactory.Options options<new BitmapFactory.Options(); options.inPreferredConfig<Bitmap.Config.ARGB_8888; Bitmap bitmap<BitmapFactory.decodeFile(String.valueOf(dir), options); imageView.setImageBitmap(bitmap); } } } } }); } private boolean checkPermission() { int result<ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE); if (result<= PackageManager.PERMISSION_GRANTED) { return true; } else { return false; } } private void requestPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) { Toast.makeText(MainActivity.this, "Write External Storage permission allows us to read files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_CODE: if (grantResults.length > 0 &amp;&amp; grantResults[0]<= PackageManager.PERMISSION_GRANTED) { Log.e("value", "Permission Granted, Now you can use local drive ."); } else { Log.e("value", "Permission Denied, You cannot use local drive ."); } break; } } } Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, click on read button to show image from external storage as shown below – Click here to download the project code
[ { "code": null, "e": 1170, "s": 1062, "text": "This example demonstrates How to read an image file in external storage with runtime permission in android." }, { "code": null, "e": 1299, "s": 1170, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1364, "s": 1299, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2009, "s": 1364, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <Button\n android:id = \"@+id/read\"\n android:text = \"read\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <ImageView\n android:id = \"@+id/imageView\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2167, "s": 2009, "text": "In the above code, we have taken image view and button. When user click on button, it will take data from external storage and append the data to Image view." }, { "code": null, "e": 2224, "s": 2167, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6090, "s": 2224, "text": "package com.example.andy.myapplication;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.Toast;\nimport java.io.File;\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE<100;\n Button read;\n ImageView imageView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView<findViewById(R.id.imageView);\n read<findViewById(R.id.read);\n read.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String state<Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(state)) {\n if (Build.VERSION.SDK_INT > = 23) {\n if (checkPermission()) {\n File dir<new File(Environment.getExternalStorageDirectory().getAbsolutePath() + \"/images.jpeg\");\n if (dir.exists()) {\n Log.d(\"path\", dir.toString());\n BitmapFactory.Options options<new BitmapFactory.Options();\n options.inPreferredConfig<Bitmap.Config.ARGB_8888;\n Bitmap bitmap<BitmapFactory.decodeFile(String.valueOf(dir), options);\n imageView.setImageBitmap(bitmap);\n }\n } else {\n requestPermission(); // Code for permission\n }\n } else {\n File dir<new File(Environment.getExternalStorageDirectory().getAbsolutePath() + \"/images.jpeg\");\n if (dir.exists()) {\n Log.d(\"path\", dir.toString());\n BitmapFactory.Options options<new BitmapFactory.Options();\n options.inPreferredConfig<Bitmap.Config.ARGB_8888;\n Bitmap bitmap<BitmapFactory.decodeFile(String.valueOf(dir), options);\n imageView.setImageBitmap(bitmap);\n }\n }\n }\n }\n });\n }\n private boolean checkPermission() {\n int result<ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE);\n if (result<= PackageManager.PERMISSION_GRANTED) {\n return true;\n } else {\n return false;\n }\n }\n private void requestPermission() {\n if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {\n Toast.makeText(MainActivity.this, \"Write External Storage permission allows us to read files. Please allow this permission in App Settings.\", Toast.LENGTH_LONG).show();\n } else {\n ActivityCompat.requestPermissions(MainActivity.this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);\n }\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {\n switch (requestCode) {\n case PERMISSION_REQUEST_CODE:\n if (grantResults.length > 0 &amp;&amp; grantResults[0]<= PackageManager.PERMISSION_GRANTED) {\n Log.e(\"value\", \"Permission Granted, Now you can use local drive .\");\n } else {\n Log.e(\"value\", \"Permission Denied, You cannot use local drive .\");\n }\n break;\n }\n }\n}" }, { "code": null, "e": 6138, "s": 6090, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 7014, "s": 6138, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <uses-permission android:name = \"android.permission.READ_EXTERNAL_STORAGE\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 7361, "s": 7014, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 7456, "s": 7361, "text": "In the above result, click on read button to show image from external storage as shown below –" }, { "code": null, "e": 7496, "s": 7456, "text": "Click here to download the project code" } ]
Python Tkinter – How do I change the text size in a label widget?
Tkinter Label Widgets are used to create labels in a window. We can style the widgets using the tkinter.ttk package. In order to resize the font-size, font-family and font-style of Label widgets, we can use the inbuilt property of font(‘font-family font style’, font-size). In this example, we will create buttons that will modify the style of Label text such as font-size and font-style. #Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry of frame win.geometry("650x250") #Define all the functions def size_1(): text.config(font=('Helvatical bold',20)) def size_2(): text.config(font=('Helvetica bold',40)) #Create a Demo Label to which the changes has to be done text=Label(win, text="Hello World!") text.pack() #Create a frame frame= Frame(win) #Create a label Label(frame, text="Select the Font-Size").pack() #Create Buttons for styling the label button1= Button(frame, text="20", command= size_1) button1.pack(pady=10) button2= Button(frame, text="40", command=size_2) button2.pack(pady=10) frame.pack() win.mainloop() Running the above code will display a window containing a text Label. The buttons can be used to change the font-size of the text label. Now, select to change the font-size of the Text Label widget.
[ { "code": null, "e": 1336, "s": 1062, "text": "Tkinter Label Widgets are used to create labels in a window. We can style the widgets using the tkinter.ttk package. In order to resize the font-size, font-family and font-style of Label widgets, we can use the inbuilt property of font(‘font-family font style’, font-size)." }, { "code": null, "e": 1451, "s": 1336, "text": "In this example, we will create buttons that will modify the style of Label text such as font-size and font-style." }, { "code": null, "e": 2169, "s": 1451, "text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"650x250\")\n\n#Define all the functions\ndef size_1():\n text.config(font=('Helvatical bold',20))\n\ndef size_2():\n text.config(font=('Helvetica bold',40))\n\n#Create a Demo Label to which the changes has to be done\ntext=Label(win, text=\"Hello World!\")\ntext.pack()\n\n#Create a frame\nframe= Frame(win)\n\n#Create a label\nLabel(frame, text=\"Select the Font-Size\").pack()\n\n#Create Buttons for styling the label\nbutton1= Button(frame, text=\"20\", command= size_1)\nbutton1.pack(pady=10)\n\nbutton2= Button(frame, text=\"40\", command=size_2)\nbutton2.pack(pady=10)\n\nframe.pack()\nwin.mainloop()" }, { "code": null, "e": 2306, "s": 2169, "text": "Running the above code will display a window containing a text Label. The buttons can be used to change the font-size of the text label." }, { "code": null, "e": 2368, "s": 2306, "text": "Now, select to change the font-size of the Text Label widget." } ]
Find N-th term in the series 0, 4, 18, 48, 100 ... - GeeksforGeeks
06 Dec, 2021 Given a series 0, 4, 18, 48, 100 . . . and an integer N, the task is to find the N-th term of the series. Examples: Input: N = 4Output: 48Explanation: As given in the sequence we can see that 4th term is 48 Input: N = 6Output: 180 Approach: Consider the below observation: For N = 2, the 2nd term is 4, which can be represented as 8 – 4, i.e. 23 – 22 For N = 3, the 3rd term is 18, which can be represented as 27 – 9, i.e. 33 – 32 For N = 4, the 4th term is 18, which can be represented as 27 – 9, i.e. 43 – 42 . . . Similarly, The N-th term of this series can be represented as N3 – N2 So for any N, find the square of that N and subtract it from the cube of the number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to find Nth term of series// 0, 4, 18, ... #include <bits/stdc++.h>using namespace std; // Function to find N-th term// of the seriesint getNthTerm(int N){ // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N);} // Driver Codeint main(){ int N = 4; // Get the 8th term of the series cout << getNthTerm(N); return 0;} // Java code to find Nth term of series// 0, 4, 18, ...class GFG{ // Function to find N-th term // of the series public static int getNthTerm(int N) { // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N); } // Driver Code public static void main(String args[]) { int N = 4; // Get the 8th term of the series System.out.println(getNthTerm(N)); }} // This code is contributed by gfgking # Python code to find Nth term of series# 0, 4, 18, ... # Function to find N-th term# of the seriesdef getNthTerm(N): # (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N); # Driver CodeN = 4; # Get the 8th term of the seriesprint(getNthTerm(N)); # This code is contributed by gfgking // C# code to find Nth term of series// 0, 4, 18, ... using System;class GFG { // Function to find N-th term // of the series public static int getNthTerm(int N) { // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N); } // Driver Code public static void Main() { int N = 4; // Get the 8th term of the series Console.Write(getNthTerm(N)); }} // This code is contributed by gfgking <script>// Javascript code to find Nth term of series// 0, 4, 18, ... // Function to find N-th term// of the seriesfunction getNthTerm(N) { // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N);} // Driver Code let N = 4; // Get the 8th term of the seriesdocument.write(getNthTerm(N));// This code is contributed by gfgking</script> 48 Time complexity: O(1)Auxiliary space: O(1) gfgking maths-cube maths-perfect-square Sequence and Series Mathematical Pattern Searching Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Program to convert a given number to words Program to multiply two matrices Modular multiplicative inverse Program to print prime numbers from 1 to N. KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Check if a string is substring of another Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 24612, "s": 24584, "text": "\n06 Dec, 2021" }, { "code": null, "e": 24719, "s": 24612, "text": "Given a series 0, 4, 18, 48, 100 . . . and an integer N, the task is to find the N-th term of the series." }, { "code": null, "e": 24729, "s": 24719, "text": "Examples:" }, { "code": null, "e": 24820, "s": 24729, "text": "Input: N = 4Output: 48Explanation: As given in the sequence we can see that 4th term is 48" }, { "code": null, "e": 24844, "s": 24820, "text": "Input: N = 6Output: 180" }, { "code": null, "e": 24886, "s": 24844, "text": "Approach: Consider the below observation:" }, { "code": null, "e": 24964, "s": 24886, "text": "For N = 2, the 2nd term is 4, which can be represented as 8 – 4, i.e. 23 – 22" }, { "code": null, "e": 25044, "s": 24964, "text": "For N = 3, the 3rd term is 18, which can be represented as 27 – 9, i.e. 33 – 32" }, { "code": null, "e": 25124, "s": 25044, "text": "For N = 4, the 4th term is 18, which can be represented as 27 – 9, i.e. 43 – 42" }, { "code": null, "e": 25126, "s": 25124, "text": "." }, { "code": null, "e": 25128, "s": 25126, "text": "." }, { "code": null, "e": 25130, "s": 25128, "text": "." }, { "code": null, "e": 25200, "s": 25130, "text": "Similarly, The N-th term of this series can be represented as N3 – N2" }, { "code": null, "e": 25285, "s": 25200, "text": "So for any N, find the square of that N and subtract it from the cube of the number." }, { "code": null, "e": 25336, "s": 25285, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25340, "s": 25336, "text": "C++" }, { "code": null, "e": 25345, "s": 25340, "text": "Java" }, { "code": null, "e": 25353, "s": 25345, "text": "Python3" }, { "code": null, "e": 25356, "s": 25353, "text": "C#" }, { "code": null, "e": 25367, "s": 25356, "text": "Javascript" }, { "code": "// C++ code to find Nth term of series// 0, 4, 18, ... #include <bits/stdc++.h>using namespace std; // Function to find N-th term// of the seriesint getNthTerm(int N){ // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N);} // Driver Codeint main(){ int N = 4; // Get the 8th term of the series cout << getNthTerm(N); return 0;}", "e": 25721, "s": 25367, "text": null }, { "code": "// Java code to find Nth term of series// 0, 4, 18, ...class GFG{ // Function to find N-th term // of the series public static int getNthTerm(int N) { // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N); } // Driver Code public static void main(String args[]) { int N = 4; // Get the 8th term of the series System.out.println(getNthTerm(N)); }} // This code is contributed by gfgking", "e": 26189, "s": 25721, "text": null }, { "code": "# Python code to find Nth term of series# 0, 4, 18, ... # Function to find N-th term# of the seriesdef getNthTerm(N): # (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N); # Driver CodeN = 4; # Get the 8th term of the seriesprint(getNthTerm(N)); # This code is contributed by gfgking", "e": 26489, "s": 26189, "text": null }, { "code": "// C# code to find Nth term of series// 0, 4, 18, ... using System;class GFG { // Function to find N-th term // of the series public static int getNthTerm(int N) { // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N); } // Driver Code public static void Main() { int N = 4; // Get the 8th term of the series Console.Write(getNthTerm(N)); }} // This code is contributed by gfgking", "e": 26934, "s": 26489, "text": null }, { "code": "<script>// Javascript code to find Nth term of series// 0, 4, 18, ... // Function to find N-th term// of the seriesfunction getNthTerm(N) { // (pow(N, 3) - pow(N, 2)) return (N * N * N) - (N * N);} // Driver Code let N = 4; // Get the 8th term of the seriesdocument.write(getNthTerm(N));// This code is contributed by gfgking</script>", "e": 27283, "s": 26934, "text": null }, { "code": null, "e": 27289, "s": 27286, "text": "48" }, { "code": null, "e": 27334, "s": 27291, "text": "Time complexity: O(1)Auxiliary space: O(1)" }, { "code": null, "e": 27344, "s": 27336, "text": "gfgking" }, { "code": null, "e": 27355, "s": 27344, "text": "maths-cube" }, { "code": null, "e": 27376, "s": 27355, "text": "maths-perfect-square" }, { "code": null, "e": 27396, "s": 27376, "text": "Sequence and Series" }, { "code": null, "e": 27409, "s": 27396, "text": "Mathematical" }, { "code": null, "e": 27427, "s": 27409, "text": "Pattern Searching" }, { "code": null, "e": 27440, "s": 27427, "text": "Mathematical" }, { "code": null, "e": 27458, "s": 27440, "text": "Pattern Searching" }, { "code": null, "e": 27556, "s": 27458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27565, "s": 27556, "text": "Comments" }, { "code": null, "e": 27578, "s": 27565, "text": "Old Comments" }, { "code": null, "e": 27610, "s": 27578, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 27653, "s": 27610, "text": "Program to convert a given number to words" }, { "code": null, "e": 27686, "s": 27653, "text": "Program to multiply two matrices" }, { "code": null, "e": 27717, "s": 27686, "text": "Modular multiplicative inverse" }, { "code": null, "e": 27761, "s": 27717, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 27797, "s": 27761, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 27840, "s": 27797, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 27878, "s": 27840, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 27920, "s": 27878, "text": "Check if a string is substring of another" } ]
Java 8 Streams and its operations
Streams are sequences of objects from a source, which support aggregate operations. These were introduced in Java 8. With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source. Some operations on streams are − sorted − The sorted method is use to sort the stream lexicographically or in ascending order List id = Arrays.asList("Objects","Classes","Interfaces"); List output = id.stream().sorted().collect(Collectors.toList()); map − The map method maps the elements in the collection to other objects according to the Predicate passed as a parameter List list1= Arrays.asList(1,3,5,7); List finalList = list1.stream().map(a -> a * a * a).collect(Collectors.toList()); filter − The filter method is used to select elements according to the Predicate parameter passed List id = Arrays.asList(“Classes","Methods","Members"); List output = id.stream().filter(s -> s.startsWith("M")).collect(Collectors.toList()); The three operations above are intermediate operations. Now let us have a look at the terminal operations collect − The collect method returns the outcome of the intermediate operations List id = Arrays.asList(“Classes","Methods","Members"); List output = id.stream().filter(s -> s.startsWith("M")).collect(Collectors.toList()); forEach − This method iterates through every element in the stream List list1 = Arrays.asList(1,3,5,7); List finalList = list1.stream().map(a ->a * a * a).forEach(b->System.out.println(b)); Let us see an example which illustrates the use of Stream − Live Demo import java.util.*; import java.util.stream.*; public class Example { public static void main(String args[]) { List<Integer> list1 = Arrays.asList(11,22,44,21); //creating an integer list List<String> id = Arrays.asList("Objects","Classes","Methods"); //creating a String list // map method List<Integer> answer = list1.stream().map(x -> x*x).collect(Collectors.toList()); System.out.println(answer); // filter method List<String> output = id.stream().filter(x->x.startsWith("M")).collect(Collectors.toList()); System.out.println(output); } } [121, 484, 1936, 441] [Methods]
[ { "code": null, "e": 1179, "s": 1062, "text": "Streams are sequences of objects from a source, which support aggregate operations. These were introduced in Java 8." }, { "code": null, "e": 1251, "s": 1179, "text": "With Java 8, Collection interface has two methods to generate a Stream." }, { "code": null, "e": 1328, "s": 1251, "text": "stream() − Returns a sequential stream considering collection as its source." }, { "code": null, "e": 1405, "s": 1328, "text": "stream() − Returns a sequential stream considering collection as its source." }, { "code": null, "e": 1488, "s": 1405, "text": "parallelStream() − Returns a parallel Stream considering collection as its source." }, { "code": null, "e": 1571, "s": 1488, "text": "parallelStream() − Returns a parallel Stream considering collection as its source." }, { "code": null, "e": 1604, "s": 1571, "text": "Some operations on streams are −" }, { "code": null, "e": 1697, "s": 1604, "text": "sorted − The sorted method is use to sort the stream lexicographically or in ascending order" }, { "code": null, "e": 1821, "s": 1697, "text": "List id = Arrays.asList(\"Objects\",\"Classes\",\"Interfaces\");\nList output = id.stream().sorted().collect(Collectors.toList());" }, { "code": null, "e": 1944, "s": 1821, "text": "map − The map method maps the elements in the collection to other objects according to the Predicate passed as a parameter" }, { "code": null, "e": 2062, "s": 1944, "text": "List list1= Arrays.asList(1,3,5,7);\nList finalList = list1.stream().map(a -> a * a * a).collect(Collectors.toList());" }, { "code": null, "e": 2160, "s": 2062, "text": "filter − The filter method is used to select elements according to the Predicate parameter passed" }, { "code": null, "e": 2303, "s": 2160, "text": "List id = Arrays.asList(“Classes\",\"Methods\",\"Members\");\nList output = id.stream().filter(s -> s.startsWith(\"M\")).collect(Collectors.toList());" }, { "code": null, "e": 2409, "s": 2303, "text": "The three operations above are intermediate operations. Now let us have a look at the terminal operations" }, { "code": null, "e": 2489, "s": 2409, "text": "collect − The collect method returns the outcome of the intermediate operations" }, { "code": null, "e": 2632, "s": 2489, "text": "List id = Arrays.asList(“Classes\",\"Methods\",\"Members\");\nList output = id.stream().filter(s -> s.startsWith(\"M\")).collect(Collectors.toList());" }, { "code": null, "e": 2699, "s": 2632, "text": "forEach − This method iterates through every element in the stream" }, { "code": null, "e": 2822, "s": 2699, "text": "List list1 = Arrays.asList(1,3,5,7);\nList finalList = list1.stream().map(a ->a * a * a).forEach(b->System.out.println(b));" }, { "code": null, "e": 2882, "s": 2822, "text": "Let us see an example which illustrates the use of Stream −" }, { "code": null, "e": 2893, "s": 2882, "text": " Live Demo" }, { "code": null, "e": 3496, "s": 2893, "text": "import java.util.*;\nimport java.util.stream.*;\npublic class Example {\n public static void main(String args[]) {\n List<Integer> list1 = Arrays.asList(11,22,44,21); //creating an integer list\n List<String> id = Arrays.asList(\"Objects\",\"Classes\",\"Methods\");\n //creating a String list\n // map method\n List<Integer> answer = list1.stream().map(x -> x*x).collect(Collectors.toList());\n System.out.println(answer);\n // filter method\n List<String> output = id.stream().filter(x->x.startsWith(\"M\")).collect(Collectors.toList());\n System.out.println(output);\n }\n}" }, { "code": null, "e": 3528, "s": 3496, "text": "[121, 484, 1936, 441]\n[Methods]" } ]
When Data Science Meet Football (Part 1): Introduction | by Fahmi Nurfikri | Towards Data Science
The utilization of data in football (or soccer) has become very important to develop player skills or match analysis. Today, we can discuss the world of football in greater depth and detail than in the previous period. For those of you who are starting to explore data analytics in football, there are public data sets provided by third parties such as Wyscout and Opta. The dataset contains football match events (e.g., Players and matches statistics). We can explore the data as an effort to understand football data more deeply. In this section, we will examine the variables in conducting football analysis. Let’s get started, if you want to see the full code of this article, please visit my github. In this article, we will use the Jupyter Notebook as code editor. If you are not familiar with the Jupyter Notebook, you can see the following article. You are free to use another code editor, do not have to follow what I use. jupyter-notebook-beginner-guide.readthedocs.io First of all, we must download the required data. In this article, We will use the dataset used in the research of Pappalardo et al., (2019). You can download the dataset here. If you have downloaded the required dataset, the next step is to import the package that will be used. Here we will use the collections and json packages which are built-in functions of python and matplotlib and numpy. If you have not installed one or both of the packages that I mentioned last, please install them first using the commands below. $ pip install numpy$ pip install matplotlib After the package is installed, enter the package that was mentioned earlier. %matplotlib inlinefrom collections import defaultdictimport matplotlib.pyplot as pltimport numpy as npimport json We can load the dataset by writing the code below. Data sets are imported from the figshare repository and stored in JSON format. In this session, we import matches, players, competitions, and team data. You can also see this Github for reference and as an inspiration for me to make this article. def load_dataset(tournament): matches, events = {}, {} matches = json.load(open('./data/matches/matches_{}.json'.format(tournament))) events = json.load(open('./data/events/events_{}.json'.format(tournament))) players = json.load(open('./data/players.json')) competitions = json.load(open('./data/competitions.json')) teams = json.load(open('./data/teams.json')) return matches, events, players, competitions, teams After that, we define functions to get every data that we need. Start from matches and events. def get_match(matches, events): match_id2events = defaultdict(list) match_id2match = defaultdict(dict) for event in events: match_id = event['matchId'] match_id2events[match_id].append(event) for match in matches: match_id = match['wyId'] match_id2match[match_id] = match Player. def get_player(players): player_id2player = defaultdict(dict) for player in players: player_id = player['wyId'] player_id2player[player_id] = player return player_id2player Competitions. def get_competitions(competitions): competition_id2competition = defaultdict(dict) for competition in competitions: competition_id = competition['wyId'] competition_id2competition[competition_id] = competition return competition_id2competition Teams. def get_teams(teams): team_id2team = defaultdict(dict) for team in teams: team_id = team['wyId'] team_id2team[team_id] = team return team_id2team Now, everything is set. Let’s load the data. Here we will only use 2018 World Cup data, so we will enter the World_Cup parameter. matches, events, players, competitions, teams = load_dataset('World_Cup') After that, we change the data into the dictionary form. match_id2events, match_id2match = get_match(matches, events)player_id2player = get_player(players)competition_id2competition = get_competitions(competitions)team_id2team = get_teams(teams) Here we will try to see the structure of each data. For example, we can display player-related information with index 32777 (player_id2player[32777]) in our dictionary. As you can see, we might have a lot of information about the player, from the passport area information to the player’s identifier in the Wyscout system. {'passportArea': {'name': 'Turkey', 'id': '792', 'alpha3code': 'TUR', 'alpha2code': 'TR'}, 'weight': 78, 'firstName': 'Harun', 'middleName': '', 'lastName': 'Tekin', 'currentTeamId': 4502, 'birthDate': '1989-06-17', 'height': 187, 'role': {'code2': 'GK', 'code3': 'GKP', 'name': 'Goalkeeper'}, 'birthArea': {'name': 'Turkey', 'id': '792', 'alpha3code': 'TUR', 'alpha2code': 'TR'}, 'wyId': 32777, 'foot': 'right', 'shortName': 'H. Tekin', 'currentNationalTeamId': 4687} We can also explore the structure of other data using the code below. match_id2events[2058017] And this is the result. {'status': 'Played', 'roundId': 4165368, 'gameweek': 0, 'teamsData': {'9598': {'scoreET': 0, 'coachId': 122788, 'side': 'away', 'teamId': 9598, 'score': 2, 'scoreP': 0, 'hasFormation': 1, 'formation': {'bench': [{'playerId': 69964, 'assists': '0', 'goals': 'null', 'ownGoals': '0', 'redCards': '0', 'yellowCards': '0'},... 'seasonId': 10078, 'dateutc': '2018-07-15 15:00:00', 'winner': 4418, 'venue': 'Olimpiyskiy stadion Luzhniki', 'wyId': 2058017, 'label': 'France - Croatia, 4 - 2', 'date': 'July 15, 2018 at 5:00:00 PM GMT+2', 'groupName': '', 'referees': [{'refereeId': 378051, 'role': 'referee'}, {'refereeId': 378038, 'role': 'firstAssistant'}, {'refereeId': 378060, 'role': 'secondAssistant'}, {'refereeId': 377215, 'role': 'fourthOfficial'}], 'duration': 'Regular', 'competitionId': 28} You can try yourself for other data. If you need an example, I have provided it on Github. We can make interesting data analysis by plotting data to a more interactive view. For example, we can take all the heights of players and plot them into a histogram. heights = [player['height'] for player in player_id2player.values() if player['height'] > 0]fig,ax = plt.subplots(1,1)ax.hist(heights)ax.set_title('histogram of height')ax.set_xlabel('height [cm]')ax.set_ylabel('frequency')plt.show() This is the result. Or you can make this. Besides analyzing player statistics, we can also make other interesting analyzes by finding events in match data. Write the code below to create a function to identify the data structure of the match event. event_key = []sub_event_key = []for events in match_id2events.values(): for event in events: event_key.append(event['eventName']) sub_event_key.append(event['subEventName']) event_key = list(set(event_key))sub_event_key = list(set(sub_event_key))event_stats = []sub_event_stats = []for events in match_id2events.values(): event_stat = {key: 0 for key in event_key} sub_event_stat = {key: 0 for key in sub_event_key} for event in events: event_stat[event['eventName']] += 1 sub_event_stat[event['subEventName']] += 1 event_stats.append(event_stat) sub_event_stats.append(sub_event_stat) This is the result of the event_key variable. {'Duel', 'Foul', 'Free Kick', 'Goalkeeper leaving line', 'Offside', 'Others on the ball', 'Pass', 'Save attempt', 'Shot'} And this is the result of the sub_event_key variable. {'', 'Acceleration', 'Air duel', 'Clearance', 'Corner', 'Cross', 'Foul', 'Free Kick', 'Free kick cross', 'Free kick shot', 'Goal kick', 'Goalkeeper leaving line', 'Ground attacking duel', 'Ground defending duel', 'Ground loose ball duel', 'Hand foul', 'Hand pass', 'Head pass', 'High pass', 'Late card foul', 'Launch', 'Out of game foul', 'Penalty', 'Protest', 'Reflexes', 'Save attempt', 'Shot', 'Simple pass', 'Simulation', 'Smart pass', 'Throw in', 'Time lost foul', 'Touch', 'Violent Foul'} We can see that the match event has some interesting variables. We can analyze each variable to get a more significant match analysis. For example, we can print some event statistics in the first game of our dictionary (event_stats[0]). {'Goalkeeper leaving line': 0, 'Duel': 468, 'Free Kick': 105, 'Offside': 4, 'Others on the ball': 128, 'Foul': 32, 'Shot': 18, 'Pass': 827, 'Save attempt': 7} Just like before, we can also create a histogram of each variable in a match event to simplify the analysis process. Let’s make a histogram. pass_stat = [event['Pass'] for event in event_stats if 'Pass' in event]fig,ax = plt.subplots(1,1)ax.hist(pass_stat)ax.set_title("histogram of passes")ax.set_xlabel('passes')ax.set_yticks([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])ax.set_ylabel('frequency')plt.show() And this is the result. You can also make this. And the last, you also can create goal statistic. scores = []for match in match_id2match.values(): score = 0 for team in match['teamsData'].values(): score += team['score'] scores.append(score) Then use this code to see the statistics. scores = np.array(scores)fig,ax = plt.subplots(1,1)ax.hist(scores, bins = [0, 1, 2, 3, 4, 5, 6, 7])ax.set_title("histogram of goals")ax.set_xticks([0, 1, 2, 3, 4, 5, 6, 7])ax.set_xlabel('goals')ax.set_yticks([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])ax.set_ylabel('frequency')plt.show() And this is the result. The tutorial above is an introduction to how football analysis works. In the next article, we will explore more complex data. Pappalardo, Luca; Massucco, Emanuele (2019): Soccer match event dataset. figshare. Collection. https://doi.org/10.6084/m9.figshare.c.4415000.v5 Pappalardo et al., (2019) A public data set of spatio-temporal match events in soccer competitions, Nature Scientific Data 6:236, https://www.nature.com/articles/s41597-019-0247-7 Pappalardo et al. (2019) PlayeRank: Data-driven Performance Evaluation and Player Ranking in Soccer via a Machine Learning Approach. ACM Transactions on Intellingent Systems and Technologies (TIST) 10, 5, Article 59 (September 2019), 27 pages. DOI: https://doi.org/10.1145/3343172
[ { "code": null, "e": 543, "s": 172, "text": "The utilization of data in football (or soccer) has become very important to develop player skills or match analysis. Today, we can discuss the world of football in greater depth and detail than in the previous period. For those of you who are starting to explore data analytics in football, there are public data sets provided by third parties such as Wyscout and Opta." }, { "code": null, "e": 784, "s": 543, "text": "The dataset contains football match events (e.g., Players and matches statistics). We can explore the data as an effort to understand football data more deeply. In this section, we will examine the variables in conducting football analysis." }, { "code": null, "e": 1104, "s": 784, "text": "Let’s get started, if you want to see the full code of this article, please visit my github. In this article, we will use the Jupyter Notebook as code editor. If you are not familiar with the Jupyter Notebook, you can see the following article. You are free to use another code editor, do not have to follow what I use." }, { "code": null, "e": 1151, "s": 1104, "text": "jupyter-notebook-beginner-guide.readthedocs.io" }, { "code": null, "e": 1328, "s": 1151, "text": "First of all, we must download the required data. In this article, We will use the dataset used in the research of Pappalardo et al., (2019). You can download the dataset here." }, { "code": null, "e": 1547, "s": 1328, "text": "If you have downloaded the required dataset, the next step is to import the package that will be used. Here we will use the collections and json packages which are built-in functions of python and matplotlib and numpy." }, { "code": null, "e": 1676, "s": 1547, "text": "If you have not installed one or both of the packages that I mentioned last, please install them first using the commands below." }, { "code": null, "e": 1720, "s": 1676, "text": "$ pip install numpy$ pip install matplotlib" }, { "code": null, "e": 1798, "s": 1720, "text": "After the package is installed, enter the package that was mentioned earlier." }, { "code": null, "e": 1912, "s": 1798, "text": "%matplotlib inlinefrom collections import defaultdictimport matplotlib.pyplot as pltimport numpy as npimport json" }, { "code": null, "e": 2210, "s": 1912, "text": "We can load the dataset by writing the code below. Data sets are imported from the figshare repository and stored in JSON format. In this session, we import matches, players, competitions, and team data. You can also see this Github for reference and as an inspiration for me to make this article." }, { "code": null, "e": 2647, "s": 2210, "text": "def load_dataset(tournament): matches, events = {}, {} matches = json.load(open('./data/matches/matches_{}.json'.format(tournament))) events = json.load(open('./data/events/events_{}.json'.format(tournament))) players = json.load(open('./data/players.json')) competitions = json.load(open('./data/competitions.json')) teams = json.load(open('./data/teams.json')) return matches, events, players, competitions, teams" }, { "code": null, "e": 2742, "s": 2647, "text": "After that, we define functions to get every data that we need. Start from matches and events." }, { "code": null, "e": 3095, "s": 2742, "text": "def get_match(matches, events): match_id2events = defaultdict(list) match_id2match = defaultdict(dict) for event in events: match_id = event['matchId'] match_id2events[match_id].append(event) for match in matches: match_id = match['wyId'] match_id2match[match_id] = match" }, { "code": null, "e": 3103, "s": 3095, "text": "Player." }, { "code": null, "e": 3299, "s": 3103, "text": "def get_player(players): player_id2player = defaultdict(dict) for player in players: player_id = player['wyId'] player_id2player[player_id] = player return player_id2player" }, { "code": null, "e": 3313, "s": 3299, "text": "Competitions." }, { "code": null, "e": 3580, "s": 3313, "text": "def get_competitions(competitions): competition_id2competition = defaultdict(dict) for competition in competitions: competition_id = competition['wyId'] competition_id2competition[competition_id] = competition return competition_id2competition" }, { "code": null, "e": 3587, "s": 3580, "text": "Teams." }, { "code": null, "e": 3756, "s": 3587, "text": "def get_teams(teams): team_id2team = defaultdict(dict) for team in teams: team_id = team['wyId'] team_id2team[team_id] = team return team_id2team" }, { "code": null, "e": 3886, "s": 3756, "text": "Now, everything is set. Let’s load the data. Here we will only use 2018 World Cup data, so we will enter the World_Cup parameter." }, { "code": null, "e": 3960, "s": 3886, "text": "matches, events, players, competitions, teams = load_dataset('World_Cup')" }, { "code": null, "e": 4017, "s": 3960, "text": "After that, we change the data into the dictionary form." }, { "code": null, "e": 4206, "s": 4017, "text": "match_id2events, match_id2match = get_match(matches, events)player_id2player = get_player(players)competition_id2competition = get_competitions(competitions)team_id2team = get_teams(teams)" }, { "code": null, "e": 4529, "s": 4206, "text": "Here we will try to see the structure of each data. For example, we can display player-related information with index 32777 (player_id2player[32777]) in our dictionary. As you can see, we might have a lot of information about the player, from the passport area information to the player’s identifier in the Wyscout system." }, { "code": null, "e": 5004, "s": 4529, "text": "{'passportArea': {'name': 'Turkey', 'id': '792', 'alpha3code': 'TUR', 'alpha2code': 'TR'}, 'weight': 78, 'firstName': 'Harun', 'middleName': '', 'lastName': 'Tekin', 'currentTeamId': 4502, 'birthDate': '1989-06-17', 'height': 187, 'role': {'code2': 'GK', 'code3': 'GKP', 'name': 'Goalkeeper'}, 'birthArea': {'name': 'Turkey', 'id': '792', 'alpha3code': 'TUR', 'alpha2code': 'TR'}, 'wyId': 32777, 'foot': 'right', 'shortName': 'H. Tekin', 'currentNationalTeamId': 4687}" }, { "code": null, "e": 5074, "s": 5004, "text": "We can also explore the structure of other data using the code below." }, { "code": null, "e": 5099, "s": 5074, "text": "match_id2events[2058017]" }, { "code": null, "e": 5123, "s": 5099, "text": "And this is the result." }, { "code": null, "e": 5961, "s": 5123, "text": "{'status': 'Played', 'roundId': 4165368, 'gameweek': 0, 'teamsData': {'9598': {'scoreET': 0, 'coachId': 122788, 'side': 'away', 'teamId': 9598, 'score': 2, 'scoreP': 0, 'hasFormation': 1, 'formation': {'bench': [{'playerId': 69964, 'assists': '0', 'goals': 'null', 'ownGoals': '0', 'redCards': '0', 'yellowCards': '0'},... 'seasonId': 10078, 'dateutc': '2018-07-15 15:00:00', 'winner': 4418, 'venue': 'Olimpiyskiy stadion Luzhniki', 'wyId': 2058017, 'label': 'France - Croatia, 4 - 2', 'date': 'July 15, 2018 at 5:00:00 PM GMT+2', 'groupName': '', 'referees': [{'refereeId': 378051, 'role': 'referee'}, {'refereeId': 378038, 'role': 'firstAssistant'}, {'refereeId': 378060, 'role': 'secondAssistant'}, {'refereeId': 377215, 'role': 'fourthOfficial'}], 'duration': 'Regular', 'competitionId': 28}" }, { "code": null, "e": 6052, "s": 5961, "text": "You can try yourself for other data. If you need an example, I have provided it on Github." }, { "code": null, "e": 6219, "s": 6052, "text": "We can make interesting data analysis by plotting data to a more interactive view. For example, we can take all the heights of players and plot them into a histogram." }, { "code": null, "e": 6455, "s": 6219, "text": "heights = [player['height'] for player in player_id2player.values() if player['height'] > 0]fig,ax = plt.subplots(1,1)ax.hist(heights)ax.set_title('histogram of height')ax.set_xlabel('height [cm]')ax.set_ylabel('frequency')plt.show()" }, { "code": null, "e": 6475, "s": 6455, "text": "This is the result." }, { "code": null, "e": 6497, "s": 6475, "text": "Or you can make this." }, { "code": null, "e": 6704, "s": 6497, "text": "Besides analyzing player statistics, we can also make other interesting analyzes by finding events in match data. Write the code below to create a function to identify the data structure of the match event." }, { "code": null, "e": 7347, "s": 6704, "text": "event_key = []sub_event_key = []for events in match_id2events.values(): for event in events: event_key.append(event['eventName']) sub_event_key.append(event['subEventName']) event_key = list(set(event_key))sub_event_key = list(set(sub_event_key))event_stats = []sub_event_stats = []for events in match_id2events.values(): event_stat = {key: 0 for key in event_key} sub_event_stat = {key: 0 for key in sub_event_key} for event in events: event_stat[event['eventName']] += 1 sub_event_stat[event['subEventName']] += 1 event_stats.append(event_stat) sub_event_stats.append(sub_event_stat)" }, { "code": null, "e": 7393, "s": 7347, "text": "This is the result of the event_key variable." }, { "code": null, "e": 7515, "s": 7393, "text": "{'Duel', 'Foul', 'Free Kick', 'Goalkeeper leaving line', 'Offside', 'Others on the ball', 'Pass', 'Save attempt', 'Shot'}" }, { "code": null, "e": 7569, "s": 7515, "text": "And this is the result of the sub_event_key variable." }, { "code": null, "e": 8064, "s": 7569, "text": "{'', 'Acceleration', 'Air duel', 'Clearance', 'Corner', 'Cross', 'Foul', 'Free Kick', 'Free kick cross', 'Free kick shot', 'Goal kick', 'Goalkeeper leaving line', 'Ground attacking duel', 'Ground defending duel', 'Ground loose ball duel', 'Hand foul', 'Hand pass', 'Head pass', 'High pass', 'Late card foul', 'Launch', 'Out of game foul', 'Penalty', 'Protest', 'Reflexes', 'Save attempt', 'Shot', 'Simple pass', 'Simulation', 'Smart pass', 'Throw in', 'Time lost foul', 'Touch', 'Violent Foul'}" }, { "code": null, "e": 8301, "s": 8064, "text": "We can see that the match event has some interesting variables. We can analyze each variable to get a more significant match analysis. For example, we can print some event statistics in the first game of our dictionary (event_stats[0])." }, { "code": null, "e": 8460, "s": 8301, "text": "{'Goalkeeper leaving line': 0, 'Duel': 468, 'Free Kick': 105, 'Offside': 4, 'Others on the ball': 128, 'Foul': 32, 'Shot': 18, 'Pass': 827, 'Save attempt': 7}" }, { "code": null, "e": 8601, "s": 8460, "text": "Just like before, we can also create a histogram of each variable in a match event to simplify the analysis process. Let’s make a histogram." }, { "code": null, "e": 8865, "s": 8601, "text": "pass_stat = [event['Pass'] for event in event_stats if 'Pass' in event]fig,ax = plt.subplots(1,1)ax.hist(pass_stat)ax.set_title(\"histogram of passes\")ax.set_xlabel('passes')ax.set_yticks([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])ax.set_ylabel('frequency')plt.show()" }, { "code": null, "e": 8889, "s": 8865, "text": "And this is the result." }, { "code": null, "e": 8913, "s": 8889, "text": "You can also make this." }, { "code": null, "e": 8963, "s": 8913, "text": "And the last, you also can create goal statistic." }, { "code": null, "e": 9123, "s": 8963, "text": "scores = []for match in match_id2match.values(): score = 0 for team in match['teamsData'].values(): score += team['score'] scores.append(score)" }, { "code": null, "e": 9165, "s": 9123, "text": "Then use this code to see the statistics." }, { "code": null, "e": 9450, "s": 9165, "text": "scores = np.array(scores)fig,ax = plt.subplots(1,1)ax.hist(scores, bins = [0, 1, 2, 3, 4, 5, 6, 7])ax.set_title(\"histogram of goals\")ax.set_xticks([0, 1, 2, 3, 4, 5, 6, 7])ax.set_xlabel('goals')ax.set_yticks([0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])ax.set_ylabel('frequency')plt.show()" }, { "code": null, "e": 9474, "s": 9450, "text": "And this is the result." }, { "code": null, "e": 9600, "s": 9474, "text": "The tutorial above is an introduction to how football analysis works. In the next article, we will explore more complex data." }, { "code": null, "e": 9744, "s": 9600, "text": "Pappalardo, Luca; Massucco, Emanuele (2019): Soccer match event dataset. figshare. Collection. https://doi.org/10.6084/m9.figshare.c.4415000.v5" }, { "code": null, "e": 9924, "s": 9744, "text": "Pappalardo et al., (2019) A public data set of spatio-temporal match events in soccer competitions, Nature Scientific Data 6:236, https://www.nature.com/articles/s41597-019-0247-7" } ]
casefold() string in Python
This function is helpful in converting the letters of a word into lowercase. When applied to two strings it can match their values irrespective of the type up of the case of the letters. The below example we apply the casefold() function to a string and the result comes out in all lower case letters. string = "BestTutorials" # print lowercase string print(" lowercase string: ", string.casefold()) Running the above code gives us the following result − Lowercase String: besttutorials We can compare two strings which have same letters but in different cases after applying the casefold() function. The result of the comparison gives a match of equality to the two words. string1 = "Hello Tutorials" string2 = "hello tutorials" string3 = string1.casefold() if string2==string3: print("String2 and String3 are equal") elif string1 != string3: print("Strings are not equal") Running the above code gives us the following result − String2 and String3 are equal
[ { "code": null, "e": 1249, "s": 1062, "text": "This function is helpful in converting the letters of a word into lowercase. When applied to two strings it can match their values irrespective of the type up of the case of the letters." }, { "code": null, "e": 1364, "s": 1249, "text": "The below example we apply the casefold() function to a string and the result comes out in all lower case letters." }, { "code": null, "e": 1462, "s": 1364, "text": "string = \"BestTutorials\"\n# print lowercase string\nprint(\" lowercase string: \", string.casefold())" }, { "code": null, "e": 1517, "s": 1462, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1549, "s": 1517, "text": "Lowercase String: besttutorials" }, { "code": null, "e": 1736, "s": 1549, "text": "We can compare two strings which have same letters but in different cases after applying the casefold() function. The result of the comparison gives a match of equality to the two words." }, { "code": null, "e": 1943, "s": 1736, "text": "string1 = \"Hello Tutorials\"\nstring2 = \"hello tutorials\"\nstring3 = string1.casefold()\nif string2==string3:\n print(\"String2 and String3 are equal\")\nelif string1 != string3:\n print(\"Strings are not equal\")" }, { "code": null, "e": 1998, "s": 1943, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2028, "s": 1998, "text": "String2 and String3 are equal" } ]
Count Numbers with Unique Digits in C++
Suppose we have a non-negative integer n. We have to count all numbers with unique digits x, where x is in range 0 to 10^n. So if the number n is 2, then the result will be 91, as we want to find numbers from 0 to 100 without 11, 22, 33, 44, 55, 66, 77, 88, 99. To solve this, we will follow these steps − if n is 0, then return 1 if n is 0, then return 1 n := min of 10 and n n := min of 10 and n if n is 1, then return 10 if n is 1, then return 10 ans := 9 and ret := 10 ans := 9 and ret := 10 for i in range 2 to nans := ans * (9 – i + 2)ret := ret + ans for i in range 2 to n ans := ans * (9 – i + 2) ans := ans * (9 – i + 2) ret := ret + ans ret := ret + ans return ret return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int countNumbersWithUniqueDigits(int n) { if(n == 0)return 1; n = min(10, n); if(n == 1)return 10; int ans = 9; int ret = 10; for(int i = 2; i<= n; i++){ ans *= (9 - i + 2); ret += ans; } return ret; } }; main(){ Solution ob; cout << (ob.countNumbersWithUniqueDigits(3)); } 3 739
[ { "code": null, "e": 1324, "s": 1062, "text": "Suppose we have a non-negative integer n. We have to count all numbers with unique digits x, where x is in range 0 to 10^n. So if the number n is 2, then the result will be 91, as we want to find numbers from 0 to 100 without 11, 22, 33, 44, 55, 66, 77, 88, 99." }, { "code": null, "e": 1368, "s": 1324, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1393, "s": 1368, "text": "if n is 0, then return 1" }, { "code": null, "e": 1418, "s": 1393, "text": "if n is 0, then return 1" }, { "code": null, "e": 1439, "s": 1418, "text": "n := min of 10 and n" }, { "code": null, "e": 1460, "s": 1439, "text": "n := min of 10 and n" }, { "code": null, "e": 1486, "s": 1460, "text": "if n is 1, then return 10" }, { "code": null, "e": 1512, "s": 1486, "text": "if n is 1, then return 10" }, { "code": null, "e": 1535, "s": 1512, "text": "ans := 9 and ret := 10" }, { "code": null, "e": 1558, "s": 1535, "text": "ans := 9 and ret := 10" }, { "code": null, "e": 1620, "s": 1558, "text": "for i in range 2 to nans := ans * (9 – i + 2)ret := ret + ans" }, { "code": null, "e": 1642, "s": 1620, "text": "for i in range 2 to n" }, { "code": null, "e": 1667, "s": 1642, "text": "ans := ans * (9 – i + 2)" }, { "code": null, "e": 1692, "s": 1667, "text": "ans := ans * (9 – i + 2)" }, { "code": null, "e": 1709, "s": 1692, "text": "ret := ret + ans" }, { "code": null, "e": 1726, "s": 1709, "text": "ret := ret + ans" }, { "code": null, "e": 1737, "s": 1726, "text": "return ret" }, { "code": null, "e": 1748, "s": 1737, "text": "return ret" }, { "code": null, "e": 1820, "s": 1748, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1831, "s": 1820, "text": " Live Demo" }, { "code": null, "e": 2257, "s": 1831, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int countNumbersWithUniqueDigits(int n) {\n if(n == 0)return 1;\n n = min(10, n);\n if(n == 1)return 10;\n int ans = 9;\n int ret = 10;\n for(int i = 2; i<= n; i++){\n ans *= (9 - i + 2);\n ret += ans;\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.countNumbersWithUniqueDigits(3));\n}" }, { "code": null, "e": 2259, "s": 2257, "text": "3" }, { "code": null, "e": 2263, "s": 2259, "text": "739" } ]
Sorting Operators in LINQ
A sorting operation allows ordering the elements of a sequence on basis of a single or more attributes. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class Program { static void Main(string[] args) { int[] num = { -20, 12, 6, 10, 0, -3, 1 }; //create a query that obtain the values in sorted order var posNums = from n in num orderby n select n; Console.Write("Values in ascending order: "); // Execute the query and display the results. foreach (int i in posNums) Console.Write(i + " \n"); var posNumsDesc = from n in num orderby n descending select n; Console.Write("\nValues in descending order: "); // Execute the query and display the results. foreach (int i in posNumsDesc) Console.Write(i + " \n"); Console.ReadLine(); } } } Module Module1 Sub Main() Dim num As Integer() = {-20, 12, 6, 10, 0, -3, 1}; Dim posNums = From n In num Order By n Select n; Console.Write("Values in ascending order: "); For Each n In posNums Console.WriteLine(n) Next Dim posNumsDesc = From n In num Order By n Descending Select n; Console.Write("Values in descending order: "); For Each n In posNumsDesc Console.WriteLine(n) Next Console.ReadLine() End Sub End Module When the above code in C# or VB is compiled and executed, it produces the following result − Values in ascending order: -20 -3 0 1 6 10 12 Values in descending order: 12 10 6 1 0 -3 -20 In Thenby and ThenbyDescending operators, same syntax can be applied and sorting order will depend on more than one columns. Priority will be the column which is maintained first. 23 Lectures 1.5 hours Anadi Sharma 37 Lectures 13 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 1840, "s": 1736, "text": "A sorting operation allows ordering the elements of a sequence on basis of a single or more attributes." }, { "code": null, "e": 2838, "s": 1840, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Operators {\n class Program {\n static void Main(string[] args) {\n \n int[] num = { -20, 12, 6, 10, 0, -3, 1 };\n\t\t\t\n //create a query that obtain the values in sorted order\n var posNums = from n in num\n orderby n\n select n;\n\t\t\t\t\t\t\t \n Console.Write(\"Values in ascending order: \");\n \n // Execute the query and display the results.\n\t\t \n foreach (int i in posNums) \n Console.Write(i + \" \\n\");\n\n var posNumsDesc = from n in num\n orderby n descending\n select n;\n\t\t\t\t\t\t\t\t\t\t\n Console.Write(\"\\nValues in descending order: \");\n\n // Execute the query and display the results.\n\t\t \n foreach (int i in posNumsDesc) \n Console.Write(i + \" \\n\");\n\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3473, "s": 2838, "text": "Module Module1\n\n Sub Main()\n \n Dim num As Integer() = {-20, 12, 6, 10, 0, -3, 1};\n\n Dim posNums = From n In num\n Order By n\n Select n;\n\t\t\t\t\t\t \n Console.Write(\"Values in ascending order: \");\n\n For Each n In posNums\n Console.WriteLine(n)\n Next\n \n Dim posNumsDesc = From n In num\n Order By n Descending\n Select n;\n\t\t\t\t\t\t\t \n Console.Write(\"Values in descending order: \");\n\n For Each n In posNumsDesc\n Console.WriteLine(n)\n\t\t\n Next\n Console.ReadLine()\n\t\t\n End Sub\n \nEnd Module" }, { "code": null, "e": 3566, "s": 3473, "text": "When the above code in C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 3672, "s": 3566, "text": "Values in ascending order: -20 \n-3 \n0 \n1 \n6 \n10 \n12\nValues in descending order: 12 \n10 \n6 \n1 \n0 \n-3 \n-20\n" }, { "code": null, "e": 3852, "s": 3672, "text": "In Thenby and ThenbyDescending operators, same syntax can be applied and sorting order will depend on more than one columns. Priority will be the column which is maintained first." }, { "code": null, "e": 3887, "s": 3852, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3901, "s": 3887, "text": " Anadi Sharma" }, { "code": null, "e": 3935, "s": 3901, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 3953, "s": 3935, "text": " Trevoir Williams" }, { "code": null, "e": 3960, "s": 3953, "text": " Print" }, { "code": null, "e": 3971, "s": 3960, "text": " Add Notes" } ]
Real-time dashboard in Python. Streaming and Refreshing | by Sophia Yang | Towards Data Science
Data scientists use data visualization to communicate data and generate insights. It’s essential for data scientists to know how to create meaningful visualization dashboards, especially real-time dashboards. This article talks about two ways to get your real-time dashboard in Python: First, we use streaming data and create an auto-updated streaming dashboard. Second, we use a “Refresh” button to refresh the dashboard whenever we need the dashboard to be refreshed. For demonstration purposes, the plots and dashboards are very basic, but you will get the idea of how we do a real-time dashboard. The code for this article can be found here: realtime_dashboard.ipynb and realtime_dashboard.py. The content of these two files is completely the same, just in different formats. To show how we create this dashboard with a real-world API, we use weather data from the OpenWeather API as an example in this article. If you would like to try out the code mentioned in this article, you will need to get access to the OpenWeather weather API. You can sign up at the Open Weather website and then get the API keys. Before going into the code, let’s install the needed packages: conda install datashader holoviews hvplot notebook numpy pandas panel param requests streamz Here we import the packages used for this article: First, we make a function weather_data to get weather data for a list of cities using the OpenWeather API. The output is a pandas dataframe with each row representing each city. Second, we use streamzto create a streaming dataframe based on San Francisco’s weather data. The function streaming_weather_data is used as a callback function by the PeriodicDataFrame function to create a streamzstreaming dataframe df. streamzdocs documented how PeriodicDataFrame works: streamz provides a high-level convenience class for this purpose, called a PeriodicDataFrame. A PeriodicDataFrame uses Python’s asyncio event loop (used as part of Tornado in Jupyter and other interactive frameworks) to call a user-provided function at a regular interval, collecting the results and making them available for later processing. https://streamz.readthedocs.io/en/latest/dataframes.html#streaming-dataframes The streamzstreaming dataframe df looks like this, with values updated every 30s (since we set interval=’30'). Third, we make some very basic plots using hvPlot to plot the streamzdataframe, and then we use panel to organize the plots and put everything in a dashboard. If you would like to know more about how to usehvPlot to plot streamzdataframe, please see hvPlot docs. Here is what the dashboard looks like. Since the streaming dataframe updates every 30s, this dashboard will automatically update every 30s as well. Here we see that Temperature changed, while humidity and wind speed did not. Great, now you know how to make a streaming dataframe and a streaming dashboard. If you would like to learn more, here is a great video tutorial on the streaming dashboard by my friend Dr. Jim Bednar. Please check it out! Sometimes, we don’t really need a streaming dashboard. Instead, we might just like to refresh the dashboard whenever we see it. In this section, I am going to show you how to make a “Refresh” button in your dashboard and refresh the dashboard with new data whenever you click “Refresh”. First, let’s make a simple function weather_plot to plot weather data on a map given city names and return both the plot and the data. With the plotting function ready, we can start making the refreshable dashboard. I use the param.Action function to trigger an update whenever we click on the button Refresh. In addition, I use the param.ObjectSelector function to create a dropdown menu of the dataframe columns we are interested in plotting and param.ObjectSelector trigger an update whenever we select a different option in the dropdown menu. Then the @param.depends('action', 'select_column') decorator tells the get_plot function to rerun whenever we click the Refresh button or select another column. Here is what the refresh dashboard looks like: Finally, we can use panel to combine the two dashboards we created. Our final dashboard pane is a panel object, which can be served by running: panel serve realtime_dashboard.py or panel serve realtime_dashboard.ipynb For more information on panel deployment, please refer to the panel docs. Now you know how to make a real-time streaming dashboard and a refreshable dashboard in python using hvplot , paneland streamz. Hope you find this article helpful! https://anaconda.cloud/tutorials/4038ae58-286a-4fdc-b8bf-b4b257e2edf3 https://openweathermap.org/api https://panel.holoviz.org/gallery/param/action_button.html https://streamz.readthedocs.io/en/latest/dataframes.html https://hvplot.holoviz.org/user_guide/Streaming.html https://panel.holoviz.org/user_guide/Deploy_and_Export.html By Sophia Yang on February 7, 2021 Follow me on Medium, Twitter, Linkedin, and YouTube :)
[ { "code": null, "e": 457, "s": 171, "text": "Data scientists use data visualization to communicate data and generate insights. It’s essential for data scientists to know how to create meaningful visualization dashboards, especially real-time dashboards. This article talks about two ways to get your real-time dashboard in Python:" }, { "code": null, "e": 534, "s": 457, "text": "First, we use streaming data and create an auto-updated streaming dashboard." }, { "code": null, "e": 641, "s": 534, "text": "Second, we use a “Refresh” button to refresh the dashboard whenever we need the dashboard to be refreshed." }, { "code": null, "e": 772, "s": 641, "text": "For demonstration purposes, the plots and dashboards are very basic, but you will get the idea of how we do a real-time dashboard." }, { "code": null, "e": 951, "s": 772, "text": "The code for this article can be found here: realtime_dashboard.ipynb and realtime_dashboard.py. The content of these two files is completely the same, just in different formats." }, { "code": null, "e": 1087, "s": 951, "text": "To show how we create this dashboard with a real-world API, we use weather data from the OpenWeather API as an example in this article." }, { "code": null, "e": 1283, "s": 1087, "text": "If you would like to try out the code mentioned in this article, you will need to get access to the OpenWeather weather API. You can sign up at the Open Weather website and then get the API keys." }, { "code": null, "e": 1346, "s": 1283, "text": "Before going into the code, let’s install the needed packages:" }, { "code": null, "e": 1439, "s": 1346, "text": "conda install datashader holoviews hvplot notebook numpy pandas panel param requests streamz" }, { "code": null, "e": 1490, "s": 1439, "text": "Here we import the packages used for this article:" }, { "code": null, "e": 1668, "s": 1490, "text": "First, we make a function weather_data to get weather data for a list of cities using the OpenWeather API. The output is a pandas dataframe with each row representing each city." }, { "code": null, "e": 1957, "s": 1668, "text": "Second, we use streamzto create a streaming dataframe based on San Francisco’s weather data. The function streaming_weather_data is used as a callback function by the PeriodicDataFrame function to create a streamzstreaming dataframe df. streamzdocs documented how PeriodicDataFrame works:" }, { "code": null, "e": 2301, "s": 1957, "text": "streamz provides a high-level convenience class for this purpose, called a PeriodicDataFrame. A PeriodicDataFrame uses Python’s asyncio event loop (used as part of Tornado in Jupyter and other interactive frameworks) to call a user-provided function at a regular interval, collecting the results and making them available for later processing." }, { "code": null, "e": 2379, "s": 2301, "text": "https://streamz.readthedocs.io/en/latest/dataframes.html#streaming-dataframes" }, { "code": null, "e": 2490, "s": 2379, "text": "The streamzstreaming dataframe df looks like this, with values updated every 30s (since we set interval=’30')." }, { "code": null, "e": 2753, "s": 2490, "text": "Third, we make some very basic plots using hvPlot to plot the streamzdataframe, and then we use panel to organize the plots and put everything in a dashboard. If you would like to know more about how to usehvPlot to plot streamzdataframe, please see hvPlot docs." }, { "code": null, "e": 2978, "s": 2753, "text": "Here is what the dashboard looks like. Since the streaming dataframe updates every 30s, this dashboard will automatically update every 30s as well. Here we see that Temperature changed, while humidity and wind speed did not." }, { "code": null, "e": 3059, "s": 2978, "text": "Great, now you know how to make a streaming dataframe and a streaming dashboard." }, { "code": null, "e": 3200, "s": 3059, "text": "If you would like to learn more, here is a great video tutorial on the streaming dashboard by my friend Dr. Jim Bednar. Please check it out!" }, { "code": null, "e": 3487, "s": 3200, "text": "Sometimes, we don’t really need a streaming dashboard. Instead, we might just like to refresh the dashboard whenever we see it. In this section, I am going to show you how to make a “Refresh” button in your dashboard and refresh the dashboard with new data whenever you click “Refresh”." }, { "code": null, "e": 3622, "s": 3487, "text": "First, let’s make a simple function weather_plot to plot weather data on a map given city names and return both the plot and the data." }, { "code": null, "e": 4195, "s": 3622, "text": "With the plotting function ready, we can start making the refreshable dashboard. I use the param.Action function to trigger an update whenever we click on the button Refresh. In addition, I use the param.ObjectSelector function to create a dropdown menu of the dataframe columns we are interested in plotting and param.ObjectSelector trigger an update whenever we select a different option in the dropdown menu. Then the @param.depends('action', 'select_column') decorator tells the get_plot function to rerun whenever we click the Refresh button or select another column." }, { "code": null, "e": 4242, "s": 4195, "text": "Here is what the refresh dashboard looks like:" }, { "code": null, "e": 4310, "s": 4242, "text": "Finally, we can use panel to combine the two dashboards we created." }, { "code": null, "e": 4386, "s": 4310, "text": "Our final dashboard pane is a panel object, which can be served by running:" }, { "code": null, "e": 4420, "s": 4386, "text": "panel serve realtime_dashboard.py" }, { "code": null, "e": 4423, "s": 4420, "text": "or" }, { "code": null, "e": 4460, "s": 4423, "text": "panel serve realtime_dashboard.ipynb" }, { "code": null, "e": 4534, "s": 4460, "text": "For more information on panel deployment, please refer to the panel docs." }, { "code": null, "e": 4698, "s": 4534, "text": "Now you know how to make a real-time streaming dashboard and a refreshable dashboard in python using hvplot , paneland streamz. Hope you find this article helpful!" }, { "code": null, "e": 4768, "s": 4698, "text": "https://anaconda.cloud/tutorials/4038ae58-286a-4fdc-b8bf-b4b257e2edf3" }, { "code": null, "e": 4799, "s": 4768, "text": "https://openweathermap.org/api" }, { "code": null, "e": 4858, "s": 4799, "text": "https://panel.holoviz.org/gallery/param/action_button.html" }, { "code": null, "e": 4915, "s": 4858, "text": "https://streamz.readthedocs.io/en/latest/dataframes.html" }, { "code": null, "e": 4968, "s": 4915, "text": "https://hvplot.holoviz.org/user_guide/Streaming.html" }, { "code": null, "e": 5028, "s": 4968, "text": "https://panel.holoviz.org/user_guide/Deploy_and_Export.html" }, { "code": null, "e": 5063, "s": 5028, "text": "By Sophia Yang on February 7, 2021" } ]
Flip Bits | Practice | GeeksforGeeks
Given an array A[] consisting of 0’s and 1’s. A flip operation is one in which you turn 1 into 0 and a 0 into 1. You have to do at most one “Flip” operation of any subarray. Formally, select a range (l, r) in the array A[], such that (0 ≤ l ≤ r < n) holds and flip the elements in this range to get the maximum ones in the final array. You can possibly make zero operations to get the answer. Example 1: Input: N = 5 A[] = {1, 0, 0, 1, 0} Output: 4 Explanation: We can perform a flip operation in the range [1,2] After flip operation array is : [ 1 1 1 1 0 ] Count of one after fliping is : 4 [Note: the subarray marked in bold is the flipped subarray] Example 2: Input: N = 7 A[] = {1, 0, 0, 1, 0, 0, 1} Output: 6 Explanation: We can perform a flip operation in the range [1,5] After flip operation array is : [ 1 1 1 0 1 1 1] Count of one after fliping is : 6 [Note: the subarray marked in bold is the flipped subarray] Your Task: You don't need to read input or print anything. Your task is to complete the function maxOnes() which takes the array A[] and its size N as inputs and returns the maximum number of 1's you can have in the array after atmost one flip operation. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 104 0 ≤ A[i] ≤ 1 0 shivanshpandey1571 week ago int ans=INT_MAX,count=0,sum=0; for(int i=0;i<n;i++) { if(a[i]==0) a[i]=-1; else count++; } for(int i=0;i<n;i++) { if(sum+a[i]<0) { sum+=a[i]; ans=min(ans,sum); } else { sum=0; } } if(ans==INT_MAX) return count; return count+abs(ans); 0 sriharichalla1220021 month ago def maxOnes(self, a, n): # Your code goes here ones = 0 sum = 0 max_sum = 0 for i in range(n): if a[i] == 1: ones+=1 value = -1 if a[i] == 1 else 1 sum = sum+value max_sum = max(sum,max_sum) if sum < 0: sum = 0 return max_sum+ones +2 arun1331prasad1 month ago class Solution { public static int maxOnes(int a[], int n) { int totalones=0; int currsum=0; int maxsum=0; for( int i=0; i<n;i++){ if(a[i]==1) totalones++; int val= a[i]==1?-1:1; currsum+=val; if(currsum>maxsum){ maxsum=currsum; } if(currsum<0){ currsum=0; } } return totalones+maxsum; } } 0 ashutoshchoudhary9982 months ago class Solution { public static int maxOnes(int a[], int n) { // Your code goes here int current=0; int ones=0; int max=0; for(int i=0;i<n;i++){ if(a[i]==1){ ones++; } int val=0; val=(a[i]==1)?-1:1; current=Math.max(current+val,val); max=Math.max(max,current); } return max+ones; }} +3 ameenul88087 months ago int maxOnes(int a[], int n) { // Your code goes here //uisng kadane's int msf=0,meh=0; for(int i=0;i<n;i++){ meh += (a[i])?-1:1; if(meh>msf){ msf=meh; } if(meh<0){ meh=0; } } for(int i=0;i<n;i++){ if(a[i]) msf++; } return msf; } 0 b181397 months ago #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: int maxOnes(int a[], int n) { int zc=0 , oc=0; for(int i=0;i<n;i++) { if(a[i]==1) oc++; } if(oc==n or oc==n-1) return n; int flip=0; int curr=0; int i=0; while(a[i]==1) i++; for(i;i<n;i++) { if(a[i]==1) curr--; else if(a[i]==0) curr++; flip=max(flip, curr); } return flip+oc; } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; cin>>n; int a[n+5]; for(int i=0;i<n;i++) cin>>a[i]; Solution ob; cout<< ob.maxOnes(a, n) <<endl; } return 0; } // } Driver Code Ends // CAN ANYONE PLEASE TELL ME WHAT'S WRONG WITH MY APPROACH HERE 0 Abdullah Jamal11 months ago Abdullah Jamal int maxOnes(int bits[], int n) { int zeroesCount = 0, maxZeroes = 0; // count zeroes in the range where (num of zeroes > num of ones) // and find their max for(int i = 0; i < n; i++){ if(bits[ i ] == 0) zeroesCount ++; else zeroesCount --; if(zeroesCount < 0) zeroesCount = 0; maxZeroes = max(maxZeroes, zeroesCount); } // add ones in array to maxZeroes for(int i = 0; i < n; i++){ if(bits[ i ]) maxZeroes++; } return maxZeroes; } 0 Siddharth Singh1 year ago Siddharth Singh Simply, here we have to use Kadane's Algorithm (Maximum Sum Subarray): #include<bits stdc++.h="">using namespace std;int main() {int t;cin>>t;while(t--){ int n; cin>>n; vector<int>v(n); for(int &i : v) cin>>i; int noOfZeros=0; int noOfOnes=0; int maxZeroes = 0; for(int i=0; i<n; i++){="" if(v[i]="=0){" noofzeros++;="" }else{="" noofones++;="" noofzeros--;="" }="" maxzeroes="max(maxZeroes," noofzeros);="" noofzeros="max(0,noOfZeros);" }="" int="" res="noOfOnes" +="" maxzeroes;="" cout<<res<<"\n";="" }="" return="" 0;="" }="" <="" code=""> 0 Kiran kartheek2 years ago Kiran kartheek can some one verify if this working for all test cases. I am getting it wrong for input of 10,000#include<bits stdc++.h="">using namespace std;void solve(){ int n; cin>>n; vector<int> A(n); int allzerocount = 0; for(int i=0;i<n;i++){ cin="">>A[i]; if(A[i]==0){ allzerocount++; } } int left = 0; int count0 = 0,count1=0; int ans = INT_MIN; for(int i=0;i<n;i++){ if(a[i]="=0){" count0++;="" }="" if(a[i]="=1){" count1++;="" }="" while(count1-count0<0="" &&="" left<="i){" if(a[left]="=0){" count0--;="" }="" else{="" count1--;="" }="" left++;="" }="" ans="max(ans,allzerocount+count1-count0);" }="" cout<<ans<<endl;="" }="" int="" main(){="" int="" t;="" cin="">>t; while(t--){ solve(); } return 0;} 0 RAJU KUMAR2 years ago RAJU KUMAR TC: O(n) using kaden's algorithmhttps://ide.codingblocks.co... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 631, "s": 238, "text": "Given an array A[] consisting of 0’s and 1’s. A flip operation is one in which you turn 1 into 0 and a 0 into 1. You have to do at most one “Flip” operation of any subarray. Formally, select a range (l, r) in the array A[], such that (0 ≤ l ≤ r < n) holds and flip the elements in this range to get the maximum ones in the final array. You can possibly make zero operations to get the answer." }, { "code": null, "e": 644, "s": 633, "text": "Example 1:" }, { "code": null, "e": 894, "s": 644, "text": "Input:\nN = 5\nA[] = {1, 0, 0, 1, 0} \nOutput:\n4\nExplanation:\nWe can perform a flip operation in the range [1,2]\nAfter flip operation array is : [ 1 1 1 1 0 ]\nCount of one after fliping is : 4\n[Note: the subarray marked in bold is the flipped subarray]" }, { "code": null, "e": 907, "s": 896, "text": "Example 2:" }, { "code": null, "e": 1165, "s": 907, "text": "Input:\nN = 7\nA[] = {1, 0, 0, 1, 0, 0, 1}\nOutput:\n6\nExplanation:\nWe can perform a flip operation in the range [1,5]\nAfter flip operation array is : [ 1 1 1 0 1 1 1]\nCount of one after fliping is : 6\n[Note: the subarray marked in bold is the flipped subarray]" }, { "code": null, "e": 1424, "s": 1167, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function maxOnes() which takes the array A[] and its size N as inputs and returns the maximum number of 1's you can have in the array after atmost one flip operation." }, { "code": null, "e": 1488, "s": 1426, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1528, "s": 1490, "text": "Constraints:\n1 ≤ N ≤ 104\n0 ≤ A[i] ≤ 1" }, { "code": null, "e": 1530, "s": 1528, "text": "0" }, { "code": null, "e": 1558, "s": 1530, "text": "shivanshpandey1571 week ago" }, { "code": null, "e": 1989, "s": 1558, "text": " int ans=INT_MAX,count=0,sum=0; for(int i=0;i<n;i++) { if(a[i]==0) a[i]=-1; else count++; } for(int i=0;i<n;i++) { if(sum+a[i]<0) { sum+=a[i]; ans=min(ans,sum); } else { sum=0; } } if(ans==INT_MAX) return count; return count+abs(ans);" }, { "code": null, "e": 1991, "s": 1989, "text": "0" }, { "code": null, "e": 2022, "s": 1991, "text": "sriharichalla1220021 month ago" }, { "code": null, "e": 2375, "s": 2022, "text": "def maxOnes(self, a, n): # Your code goes here ones = 0 sum = 0 max_sum = 0 for i in range(n): if a[i] == 1: ones+=1 value = -1 if a[i] == 1 else 1 sum = sum+value max_sum = max(sum,max_sum) if sum < 0: sum = 0 return max_sum+ones" }, { "code": null, "e": 2378, "s": 2375, "text": "+2" }, { "code": null, "e": 2404, "s": 2378, "text": "arun1331prasad1 month ago" }, { "code": null, "e": 2840, "s": 2404, "text": "class Solution {\n public static int maxOnes(int a[], int n) {\n int totalones=0;\n int currsum=0;\n int maxsum=0;\n for( int i=0; i<n;i++){\n if(a[i]==1)\n totalones++;\n int val= a[i]==1?-1:1;\n currsum+=val;\n if(currsum>maxsum){\n maxsum=currsum;\n }\n if(currsum<0){\n currsum=0;\n }\n }\n return totalones+maxsum;\n }\n}\n" }, { "code": null, "e": 2842, "s": 2840, "text": "0" }, { "code": null, "e": 2875, "s": 2842, "text": "ashutoshchoudhary9982 months ago" }, { "code": null, "e": 2892, "s": 2875, "text": "class Solution {" }, { "code": null, "e": 3328, "s": 2892, "text": " public static int maxOnes(int a[], int n) { // Your code goes here int current=0; int ones=0; int max=0; for(int i=0;i<n;i++){ if(a[i]==1){ ones++; } int val=0; val=(a[i]==1)?-1:1; current=Math.max(current+val,val); max=Math.max(max,current); } return max+ones; }} " }, { "code": null, "e": 3331, "s": 3328, "text": "+3" }, { "code": null, "e": 3355, "s": 3331, "text": "ameenul88087 months ago" }, { "code": null, "e": 3796, "s": 3355, "text": "int maxOnes(int a[], int n)\n {\n // Your code goes here\n //uisng kadane's\n int msf=0,meh=0;\n for(int i=0;i<n;i++){\n meh += (a[i])?-1:1;\n \n if(meh>msf){\n msf=meh;\n }\n \n if(meh<0){\n meh=0;\n }\n }\n \n for(int i=0;i<n;i++){\n if(a[i]) msf++;\n }\n \n return msf;\n }" }, { "code": null, "e": 3798, "s": 3796, "text": "0" }, { "code": null, "e": 3817, "s": 3798, "text": "b181397 months ago" }, { "code": null, "e": 3841, "s": 3817, "text": "#include<bits/stdc++.h>" }, { "code": null, "e": 3862, "s": 3841, "text": "using namespace std;" }, { "code": null, "e": 3887, "s": 3864, "text": " // } Driver Code Ends" }, { "code": null, "e": 3907, "s": 3891, "text": "class Solution{" }, { "code": null, "e": 3919, "s": 3907, "text": " public:" }, { "code": null, "e": 3951, "s": 3919, "text": " int maxOnes(int a[], int n)" }, { "code": null, "e": 3957, "s": 3951, "text": " {" }, { "code": null, "e": 3982, "s": 3957, "text": " int zc=0 , oc=0;" }, { "code": null, "e": 4011, "s": 3982, "text": " for(int i=0;i<n;i++)" }, { "code": null, "e": 4021, "s": 4011, "text": " {" }, { "code": null, "e": 4051, "s": 4021, "text": " if(a[i]==1) oc++;" }, { "code": null, "e": 4061, "s": 4051, "text": " }" }, { "code": null, "e": 4100, "s": 4061, "text": " if(oc==n or oc==n-1) return n;" }, { "code": null, "e": 4120, "s": 4100, "text": " int flip=0;" }, { "code": null, "e": 4140, "s": 4120, "text": " int curr=0;" }, { "code": null, "e": 4157, "s": 4140, "text": " int i=0;" }, { "code": null, "e": 4185, "s": 4157, "text": " while(a[i]==1) i++;" }, { "code": null, "e": 4208, "s": 4185, "text": " for(i;i<n;i++)" }, { "code": null, "e": 4218, "s": 4208, "text": " {" }, { "code": null, "e": 4250, "s": 4218, "text": " if(a[i]==1) curr--;" }, { "code": null, "e": 4287, "s": 4250, "text": " else if(a[i]==0) curr++;" }, { "code": null, "e": 4321, "s": 4287, "text": " flip=max(flip, curr);" }, { "code": null, "e": 4331, "s": 4321, "text": " }" }, { "code": null, "e": 4355, "s": 4331, "text": " return flip+oc;" }, { "code": null, "e": 4361, "s": 4355, "text": " }" }, { "code": null, "e": 4364, "s": 4361, "text": "};" }, { "code": null, "e": 4393, "s": 4368, "text": "// { Driver Code Starts." }, { "code": null, "e": 4404, "s": 4393, "text": "int main()" }, { "code": null, "e": 4406, "s": 4404, "text": "{" }, { "code": null, "e": 4425, "s": 4406, "text": " int t; cin>>t;" }, { "code": null, "e": 4440, "s": 4425, "text": " while(t--)" }, { "code": null, "e": 4446, "s": 4440, "text": " {" }, { "code": null, "e": 4461, "s": 4446, "text": " int n;" }, { "code": null, "e": 4477, "s": 4461, "text": " cin>>n;" }, { "code": null, "e": 4497, "s": 4477, "text": " int a[n+5];" }, { "code": null, "e": 4526, "s": 4497, "text": " for(int i=0;i<n;i++)" }, { "code": null, "e": 4549, "s": 4526, "text": " cin>>a[i];" }, { "code": null, "e": 4570, "s": 4549, "text": " Solution ob;" }, { "code": null, "e": 4610, "s": 4570, "text": " cout<< ob.maxOnes(a, n) <<endl;" }, { "code": null, "e": 4616, "s": 4610, "text": " }" }, { "code": null, "e": 4630, "s": 4616, "text": " return 0;" }, { "code": null, "e": 4632, "s": 4630, "text": "}" }, { "code": null, "e": 4656, "s": 4632, "text": " // } Driver Code Ends" }, { "code": null, "e": 4724, "s": 4660, "text": "// CAN ANYONE PLEASE TELL ME WHAT'S WRONG WITH MY APPROACH HERE" }, { "code": null, "e": 4726, "s": 4724, "text": "0" }, { "code": null, "e": 4754, "s": 4726, "text": "Abdullah Jamal11 months ago" }, { "code": null, "e": 4769, "s": 4754, "text": "Abdullah Jamal" }, { "code": null, "e": 5391, "s": 4769, "text": " int maxOnes(int bits[], int n) { int zeroesCount = 0, maxZeroes = 0; // count zeroes in the range where (num of zeroes > num of ones) // and find their max for(int i = 0; i < n; i++){ if(bits[ i ] == 0) zeroesCount ++; else zeroesCount --; if(zeroesCount < 0) zeroesCount = 0; maxZeroes = max(maxZeroes, zeroesCount); } // add ones in array to maxZeroes for(int i = 0; i < n; i++){ if(bits[ i ]) maxZeroes++; } return maxZeroes; }" }, { "code": null, "e": 5393, "s": 5391, "text": "0" }, { "code": null, "e": 5419, "s": 5393, "text": "Siddharth Singh1 year ago" }, { "code": null, "e": 5435, "s": 5419, "text": "Siddharth Singh" }, { "code": null, "e": 5506, "s": 5435, "text": "Simply, here we have to use Kadane's Algorithm (Maximum Sum Subarray):" }, { "code": null, "e": 6004, "s": 5506, "text": "#include<bits stdc++.h=\"\">using namespace std;int main() {int t;cin>>t;while(t--){ int n; cin>>n; vector<int>v(n); for(int &i : v) cin>>i; int noOfZeros=0; int noOfOnes=0; int maxZeroes = 0; for(int i=0; i<n; i++){=\"\" if(v[i]=\"=0){\" noofzeros++;=\"\" }else{=\"\" noofones++;=\"\" noofzeros--;=\"\" }=\"\" maxzeroes=\"max(maxZeroes,\" noofzeros);=\"\" noofzeros=\"max(0,noOfZeros);\" }=\"\" int=\"\" res=\"noOfOnes\" +=\"\" maxzeroes;=\"\" cout<<res<<\"\\n\";=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 6006, "s": 6004, "text": "0" }, { "code": null, "e": 6032, "s": 6006, "text": "Kiran kartheek2 years ago" }, { "code": null, "e": 6047, "s": 6032, "text": "Kiran kartheek" }, { "code": null, "e": 6442, "s": 6047, "text": "can some one verify if this working for all test cases. I am getting it wrong for input of 10,000#include<bits stdc++.h=\"\">using namespace std;void solve(){ int n; cin>>n; vector<int> A(n); int allzerocount = 0; for(int i=0;i<n;i++){ cin=\"\">>A[i]; if(A[i]==0){ allzerocount++; } } int left = 0; int count0 = 0,count1=0; int ans = INT_MIN;" }, { "code": null, "e": 6821, "s": 6442, "text": " for(int i=0;i<n;i++){ if(a[i]=\"=0){\" count0++;=\"\" }=\"\" if(a[i]=\"=1){\" count1++;=\"\" }=\"\" while(count1-count0<0=\"\" &&=\"\" left<=\"i){\" if(a[left]=\"=0){\" count0--;=\"\" }=\"\" else{=\"\" count1--;=\"\" }=\"\" left++;=\"\" }=\"\" ans=\"max(ans,allzerocount+count1-count0);\" }=\"\" cout<<ans<<endl;=\"\" }=\"\" int=\"\" main(){=\"\" int=\"\" t;=\"\" cin=\"\">>t; while(t--){ solve(); } return 0;}" }, { "code": null, "e": 6823, "s": 6821, "text": "0" }, { "code": null, "e": 6845, "s": 6823, "text": "RAJU KUMAR2 years ago" }, { "code": null, "e": 6856, "s": 6845, "text": "RAJU KUMAR" }, { "code": null, "e": 6919, "s": 6856, "text": "TC: O(n) using kaden's algorithmhttps://ide.codingblocks.co..." }, { "code": null, "e": 7065, "s": 6919, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7101, "s": 7065, "text": " Login to access your submissions. " }, { "code": null, "e": 7111, "s": 7101, "text": "\nProblem\n" }, { "code": null, "e": 7121, "s": 7111, "text": "\nContest\n" }, { "code": null, "e": 7184, "s": 7121, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7332, "s": 7184, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7540, "s": 7332, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7646, "s": 7540, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Input/Output Operators Overloading in C++
C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object. Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object. Following example explains how extraction operator >> and insertion operator <<. #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance() { feet = 0; inches = 0; } Distance(int f, int i) { feet = f; inches = i; } friend ostream &operator<<( ostream &output, const Distance &D ) { output << "F : " << D.feet << " I : " << D.inches; return output; } friend istream &operator>>( istream &input, Distance &D ) { input >> D.feet >> D.inches; return input; } }; int main() { Distance D1(11, 10), D2(5, 11), D3; cout << "Enter the value of object : " << endl; cin >> D3; cout << "First Distance : " << D1 << endl; cout << "Second Distance :" << D2 << endl; cout << "Third Distance :" << D3 << endl; return 0; } When the above code is compiled and executed, it produces the following result − $./a.out Enter the value of object : 70 10 First Distance : F : 11 I : 10 Second Distance :F : 5 I : 11 Third Distance :F : 70 I : 10 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2596, "s": 2318, "text": "C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object." }, { "code": null, "e": 2733, "s": 2596, "text": "Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object." }, { "code": null, "e": 2814, "s": 2733, "text": "Following example explains how extraction operator >> and insertion operator <<." }, { "code": null, "e": 3768, "s": 2814, "text": "#include <iostream>\nusing namespace std;\n \nclass Distance {\n private:\n int feet; // 0 to infinite\n int inches; // 0 to 12\n \n public:\n // required constructors\n Distance() {\n feet = 0;\n inches = 0;\n }\n Distance(int f, int i) {\n feet = f;\n inches = i;\n }\n friend ostream &operator<<( ostream &output, const Distance &D ) { \n output << \"F : \" << D.feet << \" I : \" << D.inches;\n return output; \n }\n\n friend istream &operator>>( istream &input, Distance &D ) { \n input >> D.feet >> D.inches;\n return input; \n }\n};\n\nint main() {\n Distance D1(11, 10), D2(5, 11), D3;\n\n cout << \"Enter the value of object : \" << endl;\n cin >> D3;\n cout << \"First Distance : \" << D1 << endl;\n cout << \"Second Distance :\" << D2 << endl;\n cout << \"Third Distance :\" << D3 << endl;\n\n return 0;\n}" }, { "code": null, "e": 3849, "s": 3768, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3984, "s": 3849, "text": "$./a.out\nEnter the value of object :\n70\n10\nFirst Distance : F : 11 I : 10\nSecond Distance :F : 5 I : 11\nThird Distance :F : 70 I : 10\n" }, { "code": null, "e": 4021, "s": 3984, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4040, "s": 4021, "text": " Arnab Chakraborty" }, { "code": null, "e": 4072, "s": 4040, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4095, "s": 4072, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4131, "s": 4095, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4148, "s": 4131, "text": " Frahaan Hussain" }, { "code": null, "e": 4183, "s": 4148, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4200, "s": 4183, "text": " Frahaan Hussain" }, { "code": null, "e": 4235, "s": 4200, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4252, "s": 4235, "text": " Frahaan Hussain" }, { "code": null, "e": 4287, "s": 4252, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4304, "s": 4287, "text": " Frahaan Hussain" }, { "code": null, "e": 4311, "s": 4304, "text": " Print" }, { "code": null, "e": 4322, "s": 4311, "text": " Add Notes" } ]
Git - Push Operation
Jerry modified his last commit by using the amend operation and he is ready to push the changes. The Push operation stores data permanently to the Git repository. After a successful push operation, other developers can see Jerry’s changes. He executes the git log command to view the commit details. [jerry@CentOS project]$ git log The above command will produce the following result: commit d1e19d316224cddc437e3ed34ec3c931ad803958 Author: Jerry Mouse <[email protected]> Date: Wed Sep 11 08:05:26 2013 +0530 Changed return type of my_strlen to size_t Before push operation, he wants to review his changes, so he uses the git show command to review his changes. [jerry@CentOS project]$ git show d1e19d316224cddc437e3ed34ec3c931ad803958 The above command will produce the following result: commit d1e19d316224cddc437e3ed34ec3c931ad803958 Author: Jerry Mouse <[email protected]> Date: Wed Sep 11 08:05:26 2013 +0530 Changed return type of my_strlen to size_t diff --git a/string.c b/string.c new file mode 100644 index 0000000..7da2992 --- /dev/null +++ b/string.c @@ -0,0 +1,24 @@ +#include <stdio.h> + +size_t my_strlen(char *s) + { + char *p = s; + + while (*p) + ++p; + return (p -s ); + } + +int main(void) + { + int i; + char *s[] = { + "Git tutorials", + "Tutorials Point" + }; + + + for (i = 0; i < 2; ++i) printf("string lenght of %s = %lu\n", s[i], my_strlen(s[i])); + + return 0; + } Jerry is happy with his changes and he is ready to push his changes. [jerry@CentOS project]$ git push origin master The above command will produce the following result: Counting objects: 4, done. Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 517 bytes, done. Total 3 (delta 0), reused 0 (delta 0) To [email protected]:project.git 19ae206..d1e19d3 master −> master Jerry’s changes have been successfully pushed to the repository; now other developers can view his changes by performing clone or update operation. 251 Lectures 35.5 hours Gowthami Swarna 23 Lectures 2 hours Asif Hussain 15 Lectures 1.5 hours Abhilash Nelson 125 Lectures 9 hours John Shea 13 Lectures 2.5 hours Raghu Pandey 13 Lectures 3 hours Sebastian Sulinski Print Add Notes Bookmark this page
[ { "code": null, "e": 2285, "s": 2045, "text": "Jerry modified his last commit by using the amend operation and he is ready to push the changes. The Push operation stores data permanently to the Git repository. After a successful push operation, other developers can see Jerry’s changes." }, { "code": null, "e": 2345, "s": 2285, "text": "He executes the git log command to view the commit details." }, { "code": null, "e": 2378, "s": 2345, "text": "[jerry@CentOS project]$ git log\n" }, { "code": null, "e": 2431, "s": 2378, "text": "The above command will produce the following result:" }, { "code": null, "e": 2608, "s": 2431, "text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <[email protected]>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n" }, { "code": null, "e": 2718, "s": 2608, "text": "Before push operation, he wants to review his changes, so he uses the git show command to review his changes." }, { "code": null, "e": 2793, "s": 2718, "text": "[jerry@CentOS project]$ git show d1e19d316224cddc437e3ed34ec3c931ad803958\n" }, { "code": null, "e": 2846, "s": 2793, "text": "The above command will produce the following result:" }, { "code": null, "e": 3542, "s": 2846, "text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <[email protected]>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\ndiff --git a/string.c b/string.c\nnew file mode 100644\nindex 0000000..7da2992\n--- /dev/null\n+++ b/string.c\n@@ -0,0 +1,24 @@\n+#include <stdio.h>\n+\n+size_t my_strlen(char *s)\n+\n{\n +\n char *p = s;\n +\n +\n while (*p)\n + ++p;\n + return (p -s );\n +\n}\n+\n+int main(void)\n+\n{\n + int i;\n + char *s[] = \n {\n + \"Git tutorials\",\n + \"Tutorials Point\"\n +\n };\n +\n +\n +\n for (i = 0; i < 2; ++i)\n printf(\"string lenght of %s = %lu\\n\", s[i], my_strlen(s[i]));\n +\n +\n return 0;\n +\n}\n" }, { "code": null, "e": 3611, "s": 3542, "text": "Jerry is happy with his changes and he is ready to push his changes." }, { "code": null, "e": 3659, "s": 3611, "text": "[jerry@CentOS project]$ git push origin master\n" }, { "code": null, "e": 3712, "s": 3659, "text": "The above command will produce the following result:" }, { "code": null, "e": 3935, "s": 3712, "text": "Counting objects: 4, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 517 bytes, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo [email protected]:project.git\n19ae206..d1e19d3 master −> master\n" }, { "code": null, "e": 4083, "s": 3935, "text": "Jerry’s changes have been successfully pushed to the repository; now other developers can view his changes by performing clone or update operation." }, { "code": null, "e": 4120, "s": 4083, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 4137, "s": 4120, "text": " Gowthami Swarna" }, { "code": null, "e": 4170, "s": 4137, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 4184, "s": 4170, "text": " Asif Hussain" }, { "code": null, "e": 4219, "s": 4184, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4236, "s": 4219, "text": " Abhilash Nelson" }, { "code": null, "e": 4270, "s": 4236, "text": "\n 125 Lectures \n 9 hours \n" }, { "code": null, "e": 4281, "s": 4270, "text": " John Shea" }, { "code": null, "e": 4316, "s": 4281, "text": "\n 13 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4330, "s": 4316, "text": " Raghu Pandey" }, { "code": null, "e": 4363, "s": 4330, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 4383, "s": 4363, "text": " Sebastian Sulinski" }, { "code": null, "e": 4390, "s": 4383, "text": " Print" }, { "code": null, "e": 4401, "s": 4390, "text": " Add Notes" } ]
Deep Reinforcement Learning for Automated Stock Trading | by Bruce Yang | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. This blog is based on our paper: Deep Reinforcement Learning for Automated Stock Trading: An Ensemble Strategy, presented at ICAIF 2020: ACM International Conference on AI in Finance. Our codes are available on Github. github.com Our paper is available on SSRN. papers.ssrn.com If you want to cite our paper, the reference format is as follows: Hongyang Yang, Xiao-Yang Liu, Shan Zhong, and Anwar Walid. 2020. Deep Reinforcement Learning for Automated Stock Trading: An Ensemble Strategy. In ICAIF ’20: ACM International Conference on AI in Finance, Oct. 15–16, 2020, Manhattan, NY. ACM, New York, NY, USA. A most recent DRL library for Automated Trading-FinRL can be found here: github.com FinRL for Quantitative Finance: Tutorial for Single Stock Trading FinRL for Quantitative Finance: Tutorial for Multiple Stock Trading FinRL for Quantitative Finance: Tutorial for Portfolio Allocation ElegantRL supports state-of-the-art DRL algorithms and provides user-friendly tutorials in Jupyter notebooks. The core codes <1,000 lines, using PyTorch, OpenAI Gym, and NumPy. towardsdatascience.com One can hardly overestimate the crucial role stock trading strategies play in investment. Profitable automated stock trading strategy is vital to investment companies and hedge funds. It is applied to optimize capital allocation and maximize investment performance, such as expected return. Return maximization can be based on the estimates of potential return and risk. However, it is challenging to design a profitable strategy in a complex and dynamic stock market. Every player wants a winning strategy. Needless to say, a profitable strategy in such a complex and dynamic stock market is not easy to design. Yet, we are to reveal a deep reinforcement learning scheme that automatically learns a stock trading strategy by maximizing investment return. Our Solution: Ensemble Deep Reinforcement Learning Trading StrategyThis strategy includes three actor-critic based algorithms: Proximal Policy Optimization (PPO), Advantage Actor Critic (A2C), and Deep Deterministic Policy Gradient (DDPG).It combines the best features of the three algorithms, thereby robustly adjusting to different market conditions. The performance of the trading agent with different reinforcement learning algorithms is evaluated using Sharpe ratio and compared with both the Dow Jones Industrial Average index and the traditional min-variance portfolio allocation strategy. Existing works are not satisfactory. Deep Reinforcement Learning approach has many advantages. MPT performs not so well in out-of-sample data.MPT is very sensitive to outliers.MPT is calculated only based on stock returns, if we want to take other relevant factors into account, for example some of the technical indicators like Moving Average Convergence Divergence (MACD), and Relative Strength Index (RSI), MPT may not be able to combine these information together well. MPT performs not so well in out-of-sample data. MPT is very sensitive to outliers. MPT is calculated only based on stock returns, if we want to take other relevant factors into account, for example some of the technical indicators like Moving Average Convergence Divergence (MACD), and Relative Strength Index (RSI), MPT may not be able to combine these information together well. DRL doesn’t need large labeled training datasets. This is a significant advantage since the amount of data grows exponentially today, it becomes very time-and-labor-consuming to label a large dataset.DRL uses a reward function to optimize future rewards, in contrast to an ML regression/classification model that predicts the probability of future outcomes. DRL doesn’t need large labeled training datasets. This is a significant advantage since the amount of data grows exponentially today, it becomes very time-and-labor-consuming to label a large dataset. DRL uses a reward function to optimize future rewards, in contrast to an ML regression/classification model that predicts the probability of future outcomes. The goal of stock trading is to maximize returns, while avoiding risks. DRL solves this optimization problem by maximizing the expected total reward from future actions over a time period.Stock trading is a continuous process of testing new ideas, getting feedback from the market, and trying to optimize the trading strategies over time. We can model stock trading process as Markov decision process which is the very foundation of Reinforcement Learning. The goal of stock trading is to maximize returns, while avoiding risks. DRL solves this optimization problem by maximizing the expected total reward from future actions over a time period. Stock trading is a continuous process of testing new ideas, getting feedback from the market, and trying to optimize the trading strategies over time. We can model stock trading process as Markov decision process which is the very foundation of Reinforcement Learning. Deep reinforcement learning algorithms can outperform human players in many challenging games. For example, on March 2016, DeepMind’s AlphaGo program, a deep reinforcement learning algorithm, beat the world champion Lee Sedol at the game of Go.Return maximization as trading goal: by defining the reward function as the change of the portfolio value, Deep Reinforcement Learning maximizes the portfolio value over time.The stock market provides sequential feedback. DRL can sequentially increase the model performance during the training process.The exploration-exploitation technique balances trying out different new things and taking advantage of what’s figured out. This is difference from other learning algorithms. Also, there is no requirement for a skilled human to provide training examples or labeled samples. Furthermore, during the exploration process, the agent is encouraged to explore the uncharted by human experts.Experience replay: is able to overcome the correlated samples issue, since learning from a batch of consecutive samples may experience high variances, hence is inefficient. Experience replay efficiently addresses this issue by randomly sampling mini-batches of transitions from a pre-saved replay memory.Multi-dimensional data: by using a continuous action space, DRL can handle large dimensional data.Computational power: Q-learning is a very important RL algorithm, however, it fails to handle large space. DRL, empowered by neural networks as efficient function approximator, is powerful to handle extremely large state space and action space. Deep reinforcement learning algorithms can outperform human players in many challenging games. For example, on March 2016, DeepMind’s AlphaGo program, a deep reinforcement learning algorithm, beat the world champion Lee Sedol at the game of Go. Return maximization as trading goal: by defining the reward function as the change of the portfolio value, Deep Reinforcement Learning maximizes the portfolio value over time. The stock market provides sequential feedback. DRL can sequentially increase the model performance during the training process. The exploration-exploitation technique balances trying out different new things and taking advantage of what’s figured out. This is difference from other learning algorithms. Also, there is no requirement for a skilled human to provide training examples or labeled samples. Furthermore, during the exploration process, the agent is encouraged to explore the uncharted by human experts. Experience replay: is able to overcome the correlated samples issue, since learning from a batch of consecutive samples may experience high variances, hence is inefficient. Experience replay efficiently addresses this issue by randomly sampling mini-batches of transitions from a pre-saved replay memory. Multi-dimensional data: by using a continuous action space, DRL can handle large dimensional data. Computational power: Q-learning is a very important RL algorithm, however, it fails to handle large space. DRL, empowered by neural networks as efficient function approximator, is powerful to handle extremely large state space and action space. Reinforcement Learning is one of three approaches of machine learning techniques, and it trains an agent to interact with the environment by sequentially receiving states and rewards from the environment and taking actions to reach better rewards. Deep Reinforcement Learning approximates the Q value with a neural network. Using a neural network as a function approximator would allow reinforcement learning to be applied to large data. Bellman Equation is the guiding principle to design reinforcement learning algorithms. Markov Decision Process (MDP) is used to model the environment. Recent applications of deep reinforcement learning in financial markets consider discrete or continuous state and action spaces, and employ one of these learning approaches: critic-only approach, actor-only approach, or and actor-critic approach. 1. Critic-only approach: the critic-only learning approach, which is the most common, solves a discrete action space problem using, for example, Q-learning, Deep Q-learning (DQN) and its improvements, and trains an agent on a single stock or asset. The idea of the critic-only approach is to use a Q-value function to learn the optimal action-selection policy that maximizes the expected future reward given the current state. Instead of calculating a state-action value table, DQN minimizes the mean squared error between the target Q-values, and uses a neural network to perform function approximation. The major limitation of the critic-only approach is that it only works with discrete and finite state and action spaces, which is not practical for a large portfolio of stocks, since the prices are of course continuous. Q-learning: is a value-based Reinforcement Learning algorithm that is used to find the optimal action-selection policy using a Q function. DQN: In deep Q-learning, we use a neural network to approximate the Q-value function. The state is given as the input and the Q-value of allowed actions is the predicted output. 2. Actor-only approach: The idea here is that the agent directly learns the optimal policy itself. Instead of having a neural network to learn the Q-value, the neural network learns the policy. The policy is a probability distribution that is essentially a strategy for a given state, namely the likelihood to take an allowed action. The actor-only approach can handle the continuous action space environments. Policy Gradient: aims to maximize the expected total rewards by directly learns the optimal policy itself. 3. Actor-Critic approach: The actor-critic approach has been recently applied in finance. The idea is to simultaneously update the actor network that represents the policy, and the critic network that represents the value function. The critic estimates the value function, while the actor updates the policy probability distribution guided by the critic with policy gradients. Over time, the actor learns to take better actions and the critic gets better at evaluating those actions. The actor-critic approach has proven to be able to learn and adapt to large and complex environments, and has been used to play popular video games, such as Doom. Thus, the actor-critic approach fits well in trading with a large stock portfolio. A2C: A2C is a typical actor-critic algorithm. A2C uses copies of the same agent working in parallel to update gradients with different data samples. Each agent works independently to interact with the same environment. PPO: PPO is introduced to control the policy gradient update and ensure that the new policy will not be too different from the previous one. DDPG: DDPG combines the frameworks of both Q-learning and policy gradient, and uses neural networks as function approximators. We track and select the Dow Jones 30 stocks (at 2016/01/01) and use historical daily data from 01/01/2009 to 05/08/2020 to train the agent and test the performance. The dataset is downloaded from Compustat database accessed through Wharton Research Data Services (WRDS). The whole dataset is split in the following figure. Data from 01/01/2009 to 12/31/2014 is used for training, and the data from 10/01/2015 to 12/31/2015 is used for validation and tuning of parameters. Finally, we test our agent’s performance on trading data, which is the unseen out-of-sample data from 01/01/2016 to 05/08/2020. To better exploit the trading data, we continue training our agent while in the trading stage, since this will help the agent to better adapt to the market dynamics. • State s = [p, h, b]: a vector that includes stock prices p ∈ R+^D, the stock shares h ∈ Z+^D, and the remaining balance b ∈ R+, where D denotes the number of stocks and Z+ denotes non-negative integers. • Action a: a vector of actions over D stocks. The allowed actions on each stock include selling, buying, or holding, which result in decreasing, increasing, and no change of the stock shares h, respectively. • Reward r(s,a,s′):the direct reward of taking action a at state s and arriving at the new state s′. • Policy π (s): the trading strategy at state s, which is the probability distribution of actions at state s. • Q-value Qπ (s, a): the expected reward of taking action a at state s following policy π . The state transition of our stock trading process is shown in the following figure. At each state, one of three possible actions is taken on stock d (d = 1, ..., D) in the portfolio. Selling k[d] ∈ [1,h[d]] shares results in ht+1[d] = ht [d] − k[d],wherek[d] ∈Z+ andd =1,...,D. Holding, ht+1[d]=ht[d]. Buying k[d] shares results in ht+1[d] = ht [d] + k[d]. At time t an action is taken and the stock prices update at t+1, accordingly the portfolio values may change from “portfolio value 0” to “portfolio value 1”, “portfolio value 2”, or “portfolio value 3”, respectively, as illustrated in Figure 2. Note that the portfolio value is pT h + b. Market liquidity: The orders can be rapidly executed at the close price. We assume that stock market will not be affected by our reinforcement trading agent. Nonnegative balance: the allowed actions should not result in a negative balance. Transaction cost: transaction costs are incurred for each trade. There are many types of transaction costs such as exchange fees, execution fees, and SEC fees. Different brokers have different commission fees. Despite these variations in fees, we assume that our transaction costs to be 1/1000 of the value of each trade (either buy or sell). Risk-aversion for market crash: there are sudden events that may cause stock market crash, such as wars, collapse of stock market bubbles, sovereign debt default, and financial crisis. To control the risk in a worst-case scenario like 2008 global financial crisis, we employ the financial turbulence index that measures extreme asset price movements. We define our reward function as the change of the portfolio value when action a is taken at state s and arriving at new state s + 1. The goal is to design a trading strategy that maximizes the change of the portfolio value r(st,at,st+1) in the dynamic environment, and we employ the deep reinforcement learning method to solve this problem. State Space: We use a 181-dimensional vector (30 stocks * 6 + 1) consists of seven parts of information to represent the state space of multiple stocks trading environment Balance: available amount of money left in the account at current time stepPrice: current adjusted close price of each stock.Shares: shares owned of each stock.MACD: Moving Average Convergence Divergence (MACD) is calculated using close price.RSI: Relative Strength Index (RSI) is calculated using close price.CCI: Commodity Channel Index (CCI) is calculated using high, low and close price.ADX: Average Directional Index (ADX) is calculated using high, low and close price. Balance: available amount of money left in the account at current time step Price: current adjusted close price of each stock. Shares: shares owned of each stock. MACD: Moving Average Convergence Divergence (MACD) is calculated using close price. RSI: Relative Strength Index (RSI) is calculated using close price. CCI: Commodity Channel Index (CCI) is calculated using high, low and close price. ADX: Average Directional Index (ADX) is calculated using high, low and close price. Action Space: For a single stock, the action space is defined as {-k,...,-1, 0, 1, ..., k}, where k and -k presents the number of shares we can buy and sell, and k ≤h_max while h_max is a predefined parameter that sets as the maximum amount of shares for each buying action.For multiple stocks, therefore the size of the entire action space is (2k+1)^30.The action space is then normalized to [-1, 1], since the RL algorithms A2C and PPO define the policy directly on a Gaussian distribution, which needs to be normalized and symmetric. For a single stock, the action space is defined as {-k,...,-1, 0, 1, ..., k}, where k and -k presents the number of shares we can buy and sell, and k ≤h_max while h_max is a predefined parameter that sets as the maximum amount of shares for each buying action. For multiple stocks, therefore the size of the entire action space is (2k+1)^30. The action space is then normalized to [-1, 1], since the RL algorithms A2C and PPO define the policy directly on a Gaussian distribution, which needs to be normalized and symmetric. class StockEnvTrain(gym.Env):“””A stock trading environment for OpenAI gym””” metadata = {‘render.modes’: [‘human’]}def __init__(self, df, day = 0): self.day = day self.df = df # Action Space # action_space normalization and shape is STOCK_DIM self.action_space = spaces.Box(low = -1, high = 1,shape = (STOCK_DIM,)) # State Space # Shape = 181: [Current Balance]+[prices 1–30]+[owned shares 1–30] # +[macd 1–30]+ [rsi 1–30] + [cci 1–30] + [adx 1–30] self.observation_space = spaces.Box(low=0, high=np.inf, shape = (181,)) # load data from a pandas dataframe self.data = self.df.loc[self.day,:] self.terminal = False # initalize state self.state = [INITIAL_ACCOUNT_BALANCE] + \ self.data.adjcp.values.tolist() + \ [0]*STOCK_DIM + \ self.data.macd.values.tolist() + \ self.data.rsi.values.tolist() + \ self.data.cci.values.tolist() + \ self.data.adx.values.tolist() # initialize reward self.reward = 0 self.cost = 0 # memorize all the total balance change self.asset_memory = [INITIAL_ACCOUNT_BALANCE] self.rewards_memory = [] self.trades = 0 #self.reset() self._seed() A2C is a typical actor-critic algorithm which we use as a component in the ensemble method. A2C is introduced to improve the policy gradient updates. A2C utilizes an advantage function to reduce the variance of the policy gradient. Instead of only estimates the value function, the critic network estimates the advantage function. Thus, the evaluation of an action not only depends on how good the action is, but also considers how much better it can be. So that it reduces the high variance of the policy networks and makes the model more robust. A2C uses copies of the same agent working in parallel to update gradients with different data samples. Each agent works independently to interact with the same environment. After all of the parallel agents finish calculating their gradients, A2C uses a coordinator to pass the average gradients over all the agents to a global network. So that the global network can update the actor and the critic network. The presence of a global network increases the diversity of training data. The synchronized gradient update is more cost-effective, faster and works better with large batch sizes. A2C is a great model for stock trading because of its stability. DDPG is an actor-critic based algorithm which we use as a component in the ensemble strategy to maximize the investment return. DDPG combines the frameworks of both Q-learning and policy gradient, and uses neural networks as function approximators. In contrast with DQN that learns indirectly through Q-values tables and suffers the curse of dimensionality problem, DDPG learns directly from the observations through policy gradient. It is proposed to deterministically map states to actions to better fit the continuous action space environment. We explore and use PPO as a component in the ensemble method. PPO is introduced to control the policy gradient update and ensure that the new policy will not be too different from the older one. PPO tries to simplify the objective of Trust Region Policy Optimization (TRPO) by introducing a clipping term to the objective function. The objective function of PPO takes the minimum of the clipped and normal objective. PPO discourages large policy change move outside of the clipped interval. Therefore, PPO improves the stability of the policy networks training by restricting the policy update at each training step. We select PPO for stock trading because it is stable, fast, and simpler to implement and tune. Our purpose is to create a highly robust trading strategy. So we use an ensemble method to automatically select the best performing agent among PPO, A2C, and DDPG to trade based on the Sharpe ratio. The ensemble process is described as follows: Step 1. We use a growing window of n months to retrain our three agents concurrently. In this paper, we retrain our three agents at every three months. Step 2. We validate all three agents by using a 3-month validation rolling window followed by training to pick the best performing agent which has the highest Sharpe ratio. We also adjust risk-aversion by using turbulence index in our validation stage. Step 3. After validation, we only use the best model with the highest Sharpe ratio to predict and trade for the next quarter. from stable_baselines import SACfrom stable_baselines import PPO2from stable_baselines import A2Cfrom stable_baselines import DDPGfrom stable_baselines import TD3from stable_baselines.ddpg.policies import DDPGPolicyfrom stable_baselines.common.policies import MlpPolicyfrom stable_baselines.common.vec_env import DummyVecEnvdef train_A2C(env_train, model_name, timesteps=10000): “””A2C model””” start = time.time() model = A2C(‘MlpPolicy’, env_train, verbose=0) model.learn(total_timesteps=timesteps) end = time.time() model.save(f”{config.TRAINED_MODEL_DIR}/{model_name}”) print(‘Training time (A2C): ‘, (end-start)/60,’ minutes’) return modeldef train_DDPG(env_train, model_name, timesteps=10000): “””DDPG model””” start = time.time() model = DDPG(‘MlpPolicy’, env_train) model.learn(total_timesteps=timesteps) end = time.time() model.save(f”{config.TRAINED_MODEL_DIR}/{model_name}”) print(‘Training time (DDPG): ‘, (end-start)/60,’ minutes’) return modeldef train_PPO(env_train, model_name, timesteps=50000): “””PPO model””” start = time.time() model = PPO2(‘MlpPolicy’, env_train) model.learn(total_timesteps=timesteps) end = time.time() model.save(f”{config.TRAINED_MODEL_DIR}/{model_name}”) print(‘Training time (PPO): ‘, (end-start)/60,’ minutes’) return modeldef DRL_prediction(model, test_data, test_env, test_obs): “””make a prediction””” start = time.time() for i in range(len(test_data.index.unique())): action, _states = model.predict(test_obs) test_obs, rewards, dones, info = test_env.step(action) # env_test.render() end = time.time() We use Quantopian’s pyfolio to do the backtesting. The charts look pretty good, and it takes literally one line of code to implement it. You just need to convert everything into daily returns. import pyfoliowith pyfolio.plotting.plotting_context(font_scale=1.1): pyfolio.create_full_tear_sheet(returns = ensemble_strat, benchmark_rets=dow_strat, set_context=False) References: A2C:Volodymyr Mnih, Adrià Badia, Mehdi Mirza, Alex Graves, Timothy Lillicrap, Tim Harley, David Silver, and Koray Kavukcuoglu. 2016. Asynchronous methods for deep reinforcement learning. The 33rd International Conference on Machine Learning (02 2016). https://arxiv.org/abs/1602.01783 DDPG:Timothy Lillicrap, Jonathan Hunt, Alexander Pritzel, Nicolas Heess, Tom Erez, Yuval Tassa, David Silver, and Daan Wierstra. 2015. Continuous control with deep reinforcement learning. International Conference on Learning Representations (ICLR) 2016 (09 2015). https://arxiv.org/abs/1509.02971 PPO:John Schulman, Sergey Levine, Philipp Moritz, Michael Jordan, and Pieter Abbeel. 2015. Trust region policy optimization. In The 31st International Conference on Machine Learning. https://arxiv.org/abs/1502.05477 John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. 2017. Proximal policy optimization algorithms. arXiv:1707.06347 (07 2017). https://arxiv.org/abs/1707.06347
[ { "code": null, "e": 472, "s": 172, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 656, "s": 472, "text": "This blog is based on our paper: Deep Reinforcement Learning for Automated Stock Trading: An Ensemble Strategy, presented at ICAIF 2020: ACM International Conference on AI in Finance." }, { "code": null, "e": 691, "s": 656, "text": "Our codes are available on Github." }, { "code": null, "e": 702, "s": 691, "text": "github.com" }, { "code": null, "e": 734, "s": 702, "text": "Our paper is available on SSRN." }, { "code": null, "e": 750, "s": 734, "text": "papers.ssrn.com" }, { "code": null, "e": 817, "s": 750, "text": "If you want to cite our paper, the reference format is as follows:" }, { "code": null, "e": 1079, "s": 817, "text": "Hongyang Yang, Xiao-Yang Liu, Shan Zhong, and Anwar Walid. 2020. Deep Reinforcement Learning for Automated Stock Trading: An Ensemble Strategy. In ICAIF ’20: ACM International Conference on AI in Finance, Oct. 15–16, 2020, Manhattan, NY. ACM, New York, NY, USA." }, { "code": null, "e": 1152, "s": 1079, "text": "A most recent DRL library for Automated Trading-FinRL can be found here:" }, { "code": null, "e": 1163, "s": 1152, "text": "github.com" }, { "code": null, "e": 1229, "s": 1163, "text": "FinRL for Quantitative Finance: Tutorial for Single Stock Trading" }, { "code": null, "e": 1297, "s": 1229, "text": "FinRL for Quantitative Finance: Tutorial for Multiple Stock Trading" }, { "code": null, "e": 1363, "s": 1297, "text": "FinRL for Quantitative Finance: Tutorial for Portfolio Allocation" }, { "code": null, "e": 1540, "s": 1363, "text": "ElegantRL supports state-of-the-art DRL algorithms and provides user-friendly tutorials in Jupyter notebooks. The core codes <1,000 lines, using PyTorch, OpenAI Gym, and NumPy." }, { "code": null, "e": 1563, "s": 1540, "text": "towardsdatascience.com" }, { "code": null, "e": 1653, "s": 1563, "text": "One can hardly overestimate the crucial role stock trading strategies play in investment." }, { "code": null, "e": 2032, "s": 1653, "text": "Profitable automated stock trading strategy is vital to investment companies and hedge funds. It is applied to optimize capital allocation and maximize investment performance, such as expected return. Return maximization can be based on the estimates of potential return and risk. However, it is challenging to design a profitable strategy in a complex and dynamic stock market." }, { "code": null, "e": 2176, "s": 2032, "text": "Every player wants a winning strategy. Needless to say, a profitable strategy in such a complex and dynamic stock market is not easy to design." }, { "code": null, "e": 2319, "s": 2176, "text": "Yet, we are to reveal a deep reinforcement learning scheme that automatically learns a stock trading strategy by maximizing investment return." }, { "code": null, "e": 2672, "s": 2319, "text": "Our Solution: Ensemble Deep Reinforcement Learning Trading StrategyThis strategy includes three actor-critic based algorithms: Proximal Policy Optimization (PPO), Advantage Actor Critic (A2C), and Deep Deterministic Policy Gradient (DDPG).It combines the best features of the three algorithms, thereby robustly adjusting to different market conditions." }, { "code": null, "e": 2916, "s": 2672, "text": "The performance of the trading agent with different reinforcement learning algorithms is evaluated using Sharpe ratio and compared with both the Dow Jones Industrial Average index and the traditional min-variance portfolio allocation strategy." }, { "code": null, "e": 3011, "s": 2916, "text": "Existing works are not satisfactory. Deep Reinforcement Learning approach has many advantages." }, { "code": null, "e": 3390, "s": 3011, "text": "MPT performs not so well in out-of-sample data.MPT is very sensitive to outliers.MPT is calculated only based on stock returns, if we want to take other relevant factors into account, for example some of the technical indicators like Moving Average Convergence Divergence (MACD), and Relative Strength Index (RSI), MPT may not be able to combine these information together well." }, { "code": null, "e": 3438, "s": 3390, "text": "MPT performs not so well in out-of-sample data." }, { "code": null, "e": 3473, "s": 3438, "text": "MPT is very sensitive to outliers." }, { "code": null, "e": 3771, "s": 3473, "text": "MPT is calculated only based on stock returns, if we want to take other relevant factors into account, for example some of the technical indicators like Moving Average Convergence Divergence (MACD), and Relative Strength Index (RSI), MPT may not be able to combine these information together well." }, { "code": null, "e": 4129, "s": 3771, "text": "DRL doesn’t need large labeled training datasets. This is a significant advantage since the amount of data grows exponentially today, it becomes very time-and-labor-consuming to label a large dataset.DRL uses a reward function to optimize future rewards, in contrast to an ML regression/classification model that predicts the probability of future outcomes." }, { "code": null, "e": 4330, "s": 4129, "text": "DRL doesn’t need large labeled training datasets. This is a significant advantage since the amount of data grows exponentially today, it becomes very time-and-labor-consuming to label a large dataset." }, { "code": null, "e": 4488, "s": 4330, "text": "DRL uses a reward function to optimize future rewards, in contrast to an ML regression/classification model that predicts the probability of future outcomes." }, { "code": null, "e": 4945, "s": 4488, "text": "The goal of stock trading is to maximize returns, while avoiding risks. DRL solves this optimization problem by maximizing the expected total reward from future actions over a time period.Stock trading is a continuous process of testing new ideas, getting feedback from the market, and trying to optimize the trading strategies over time. We can model stock trading process as Markov decision process which is the very foundation of Reinforcement Learning." }, { "code": null, "e": 5134, "s": 4945, "text": "The goal of stock trading is to maximize returns, while avoiding risks. DRL solves this optimization problem by maximizing the expected total reward from future actions over a time period." }, { "code": null, "e": 5403, "s": 5134, "text": "Stock trading is a continuous process of testing new ideas, getting feedback from the market, and trying to optimize the trading strategies over time. We can model stock trading process as Markov decision process which is the very foundation of Reinforcement Learning." }, { "code": null, "e": 6981, "s": 5403, "text": "Deep reinforcement learning algorithms can outperform human players in many challenging games. For example, on March 2016, DeepMind’s AlphaGo program, a deep reinforcement learning algorithm, beat the world champion Lee Sedol at the game of Go.Return maximization as trading goal: by defining the reward function as the change of the portfolio value, Deep Reinforcement Learning maximizes the portfolio value over time.The stock market provides sequential feedback. DRL can sequentially increase the model performance during the training process.The exploration-exploitation technique balances trying out different new things and taking advantage of what’s figured out. This is difference from other learning algorithms. Also, there is no requirement for a skilled human to provide training examples or labeled samples. Furthermore, during the exploration process, the agent is encouraged to explore the uncharted by human experts.Experience replay: is able to overcome the correlated samples issue, since learning from a batch of consecutive samples may experience high variances, hence is inefficient. Experience replay efficiently addresses this issue by randomly sampling mini-batches of transitions from a pre-saved replay memory.Multi-dimensional data: by using a continuous action space, DRL can handle large dimensional data.Computational power: Q-learning is a very important RL algorithm, however, it fails to handle large space. DRL, empowered by neural networks as efficient function approximator, is powerful to handle extremely large state space and action space." }, { "code": null, "e": 7226, "s": 6981, "text": "Deep reinforcement learning algorithms can outperform human players in many challenging games. For example, on March 2016, DeepMind’s AlphaGo program, a deep reinforcement learning algorithm, beat the world champion Lee Sedol at the game of Go." }, { "code": null, "e": 7402, "s": 7226, "text": "Return maximization as trading goal: by defining the reward function as the change of the portfolio value, Deep Reinforcement Learning maximizes the portfolio value over time." }, { "code": null, "e": 7530, "s": 7402, "text": "The stock market provides sequential feedback. DRL can sequentially increase the model performance during the training process." }, { "code": null, "e": 7916, "s": 7530, "text": "The exploration-exploitation technique balances trying out different new things and taking advantage of what’s figured out. This is difference from other learning algorithms. Also, there is no requirement for a skilled human to provide training examples or labeled samples. Furthermore, during the exploration process, the agent is encouraged to explore the uncharted by human experts." }, { "code": null, "e": 8221, "s": 7916, "text": "Experience replay: is able to overcome the correlated samples issue, since learning from a batch of consecutive samples may experience high variances, hence is inefficient. Experience replay efficiently addresses this issue by randomly sampling mini-batches of transitions from a pre-saved replay memory." }, { "code": null, "e": 8320, "s": 8221, "text": "Multi-dimensional data: by using a continuous action space, DRL can handle large dimensional data." }, { "code": null, "e": 8565, "s": 8320, "text": "Computational power: Q-learning is a very important RL algorithm, however, it fails to handle large space. DRL, empowered by neural networks as efficient function approximator, is powerful to handle extremely large state space and action space." }, { "code": null, "e": 8813, "s": 8565, "text": "Reinforcement Learning is one of three approaches of machine learning techniques, and it trains an agent to interact with the environment by sequentially receiving states and rewards from the environment and taking actions to reach better rewards." }, { "code": null, "e": 9003, "s": 8813, "text": "Deep Reinforcement Learning approximates the Q value with a neural network. Using a neural network as a function approximator would allow reinforcement learning to be applied to large data." }, { "code": null, "e": 9090, "s": 9003, "text": "Bellman Equation is the guiding principle to design reinforcement learning algorithms." }, { "code": null, "e": 9154, "s": 9090, "text": "Markov Decision Process (MDP) is used to model the environment." }, { "code": null, "e": 9401, "s": 9154, "text": "Recent applications of deep reinforcement learning in financial markets consider discrete or continuous state and action spaces, and employ one of these learning approaches: critic-only approach, actor-only approach, or and actor-critic approach." }, { "code": null, "e": 10226, "s": 9401, "text": "1. Critic-only approach: the critic-only learning approach, which is the most common, solves a discrete action space problem using, for example, Q-learning, Deep Q-learning (DQN) and its improvements, and trains an agent on a single stock or asset. The idea of the critic-only approach is to use a Q-value function to learn the optimal action-selection policy that maximizes the expected future reward given the current state. Instead of calculating a state-action value table, DQN minimizes the mean squared error between the target Q-values, and uses a neural network to perform function approximation. The major limitation of the critic-only approach is that it only works with discrete and finite state and action spaces, which is not practical for a large portfolio of stocks, since the prices are of course continuous." }, { "code": null, "e": 10365, "s": 10226, "text": "Q-learning: is a value-based Reinforcement Learning algorithm that is used to find the optimal action-selection policy using a Q function." }, { "code": null, "e": 10543, "s": 10365, "text": "DQN: In deep Q-learning, we use a neural network to approximate the Q-value function. The state is given as the input and the Q-value of allowed actions is the predicted output." }, { "code": null, "e": 10954, "s": 10543, "text": "2. Actor-only approach: The idea here is that the agent directly learns the optimal policy itself. Instead of having a neural network to learn the Q-value, the neural network learns the policy. The policy is a probability distribution that is essentially a strategy for a given state, namely the likelihood to take an allowed action. The actor-only approach can handle the continuous action space environments." }, { "code": null, "e": 11061, "s": 10954, "text": "Policy Gradient: aims to maximize the expected total rewards by directly learns the optimal policy itself." }, { "code": null, "e": 11791, "s": 11061, "text": "3. Actor-Critic approach: The actor-critic approach has been recently applied in finance. The idea is to simultaneously update the actor network that represents the policy, and the critic network that represents the value function. The critic estimates the value function, while the actor updates the policy probability distribution guided by the critic with policy gradients. Over time, the actor learns to take better actions and the critic gets better at evaluating those actions. The actor-critic approach has proven to be able to learn and adapt to large and complex environments, and has been used to play popular video games, such as Doom. Thus, the actor-critic approach fits well in trading with a large stock portfolio." }, { "code": null, "e": 12010, "s": 11791, "text": "A2C: A2C is a typical actor-critic algorithm. A2C uses copies of the same agent working in parallel to update gradients with different data samples. Each agent works independently to interact with the same environment." }, { "code": null, "e": 12151, "s": 12010, "text": "PPO: PPO is introduced to control the policy gradient update and ensure that the new policy will not be too different from the previous one." }, { "code": null, "e": 12278, "s": 12151, "text": "DDPG: DDPG combines the frameworks of both Q-learning and policy gradient, and uses neural networks as function approximators." }, { "code": null, "e": 12549, "s": 12278, "text": "We track and select the Dow Jones 30 stocks (at 2016/01/01) and use historical daily data from 01/01/2009 to 05/08/2020 to train the agent and test the performance. The dataset is downloaded from Compustat database accessed through Wharton Research Data Services (WRDS)." }, { "code": null, "e": 13044, "s": 12549, "text": "The whole dataset is split in the following figure. Data from 01/01/2009 to 12/31/2014 is used for training, and the data from 10/01/2015 to 12/31/2015 is used for validation and tuning of parameters. Finally, we test our agent’s performance on trading data, which is the unseen out-of-sample data from 01/01/2016 to 05/08/2020. To better exploit the trading data, we continue training our agent while in the trading stage, since this will help the agent to better adapt to the market dynamics." }, { "code": null, "e": 13249, "s": 13044, "text": "• State s = [p, h, b]: a vector that includes stock prices p ∈ R+^D, the stock shares h ∈ Z+^D, and the remaining balance b ∈ R+, where D denotes the number of stocks and Z+ denotes non-negative integers." }, { "code": null, "e": 13458, "s": 13249, "text": "• Action a: a vector of actions over D stocks. The allowed actions on each stock include selling, buying, or holding, which result in decreasing, increasing, and no change of the stock shares h, respectively." }, { "code": null, "e": 13559, "s": 13458, "text": "• Reward r(s,a,s′):the direct reward of taking action a at state s and arriving at the new state s′." }, { "code": null, "e": 13669, "s": 13559, "text": "• Policy π (s): the trading strategy at state s, which is the probability distribution of actions at state s." }, { "code": null, "e": 13761, "s": 13669, "text": "• Q-value Qπ (s, a): the expected reward of taking action a at state s following policy π ." }, { "code": null, "e": 13944, "s": 13761, "text": "The state transition of our stock trading process is shown in the following figure. At each state, one of three possible actions is taken on stock d (d = 1, ..., D) in the portfolio." }, { "code": null, "e": 14039, "s": 13944, "text": "Selling k[d] ∈ [1,h[d]] shares results in ht+1[d] = ht [d] − k[d],wherek[d] ∈Z+ andd =1,...,D." }, { "code": null, "e": 14063, "s": 14039, "text": "Holding, ht+1[d]=ht[d]." }, { "code": null, "e": 14118, "s": 14063, "text": "Buying k[d] shares results in ht+1[d] = ht [d] + k[d]." }, { "code": null, "e": 14406, "s": 14118, "text": "At time t an action is taken and the stock prices update at t+1, accordingly the portfolio values may change from “portfolio value 0” to “portfolio value 1”, “portfolio value 2”, or “portfolio value 3”, respectively, as illustrated in Figure 2. Note that the portfolio value is pT h + b." }, { "code": null, "e": 14564, "s": 14406, "text": "Market liquidity: The orders can be rapidly executed at the close price. We assume that stock market will not be affected by our reinforcement trading agent." }, { "code": null, "e": 14646, "s": 14564, "text": "Nonnegative balance: the allowed actions should not result in a negative balance." }, { "code": null, "e": 14989, "s": 14646, "text": "Transaction cost: transaction costs are incurred for each trade. There are many types of transaction costs such as exchange fees, execution fees, and SEC fees. Different brokers have different commission fees. Despite these variations in fees, we assume that our transaction costs to be 1/1000 of the value of each trade (either buy or sell)." }, { "code": null, "e": 15340, "s": 14989, "text": "Risk-aversion for market crash: there are sudden events that may cause stock market crash, such as wars, collapse of stock market bubbles, sovereign debt default, and financial crisis. To control the risk in a worst-case scenario like 2008 global financial crisis, we employ the financial turbulence index that measures extreme asset price movements." }, { "code": null, "e": 15474, "s": 15340, "text": "We define our reward function as the change of the portfolio value when action a is taken at state s and arriving at new state s + 1." }, { "code": null, "e": 15682, "s": 15474, "text": "The goal is to design a trading strategy that maximizes the change of the portfolio value r(st,at,st+1) in the dynamic environment, and we employ the deep reinforcement learning method to solve this problem." }, { "code": null, "e": 15854, "s": 15682, "text": "State Space: We use a 181-dimensional vector (30 stocks * 6 + 1) consists of seven parts of information to represent the state space of multiple stocks trading environment" }, { "code": null, "e": 16329, "s": 15854, "text": "Balance: available amount of money left in the account at current time stepPrice: current adjusted close price of each stock.Shares: shares owned of each stock.MACD: Moving Average Convergence Divergence (MACD) is calculated using close price.RSI: Relative Strength Index (RSI) is calculated using close price.CCI: Commodity Channel Index (CCI) is calculated using high, low and close price.ADX: Average Directional Index (ADX) is calculated using high, low and close price." }, { "code": null, "e": 16405, "s": 16329, "text": "Balance: available amount of money left in the account at current time step" }, { "code": null, "e": 16456, "s": 16405, "text": "Price: current adjusted close price of each stock." }, { "code": null, "e": 16492, "s": 16456, "text": "Shares: shares owned of each stock." }, { "code": null, "e": 16576, "s": 16492, "text": "MACD: Moving Average Convergence Divergence (MACD) is calculated using close price." }, { "code": null, "e": 16644, "s": 16576, "text": "RSI: Relative Strength Index (RSI) is calculated using close price." }, { "code": null, "e": 16726, "s": 16644, "text": "CCI: Commodity Channel Index (CCI) is calculated using high, low and close price." }, { "code": null, "e": 16810, "s": 16726, "text": "ADX: Average Directional Index (ADX) is calculated using high, low and close price." }, { "code": null, "e": 16824, "s": 16810, "text": "Action Space:" }, { "code": null, "e": 17347, "s": 16824, "text": "For a single stock, the action space is defined as {-k,...,-1, 0, 1, ..., k}, where k and -k presents the number of shares we can buy and sell, and k ≤h_max while h_max is a predefined parameter that sets as the maximum amount of shares for each buying action.For multiple stocks, therefore the size of the entire action space is (2k+1)^30.The action space is then normalized to [-1, 1], since the RL algorithms A2C and PPO define the policy directly on a Gaussian distribution, which needs to be normalized and symmetric." }, { "code": null, "e": 17608, "s": 17347, "text": "For a single stock, the action space is defined as {-k,...,-1, 0, 1, ..., k}, where k and -k presents the number of shares we can buy and sell, and k ≤h_max while h_max is a predefined parameter that sets as the maximum amount of shares for each buying action." }, { "code": null, "e": 17689, "s": 17608, "text": "For multiple stocks, therefore the size of the entire action space is (2k+1)^30." }, { "code": null, "e": 17872, "s": 17689, "text": "The action space is then normalized to [-1, 1], since the RL algorithms A2C and PPO define the policy directly on a Gaussian distribution, which needs to be normalized and symmetric." }, { "code": null, "e": 18944, "s": 17872, "text": "class StockEnvTrain(gym.Env):“””A stock trading environment for OpenAI gym””” metadata = {‘render.modes’: [‘human’]}def __init__(self, df, day = 0): self.day = day self.df = df # Action Space # action_space normalization and shape is STOCK_DIM self.action_space = spaces.Box(low = -1, high = 1,shape = (STOCK_DIM,)) # State Space # Shape = 181: [Current Balance]+[prices 1–30]+[owned shares 1–30] # +[macd 1–30]+ [rsi 1–30] + [cci 1–30] + [adx 1–30] self.observation_space = spaces.Box(low=0, high=np.inf, shape = (181,)) # load data from a pandas dataframe self.data = self.df.loc[self.day,:] self.terminal = False # initalize state self.state = [INITIAL_ACCOUNT_BALANCE] + \\ self.data.adjcp.values.tolist() + \\ [0]*STOCK_DIM + \\ self.data.macd.values.tolist() + \\ self.data.rsi.values.tolist() + \\ self.data.cci.values.tolist() + \\ self.data.adx.values.tolist() # initialize reward self.reward = 0 self.cost = 0 # memorize all the total balance change self.asset_memory = [INITIAL_ACCOUNT_BALANCE] self.rewards_memory = [] self.trades = 0 #self.reset() self._seed()" }, { "code": null, "e": 19492, "s": 18944, "text": "A2C is a typical actor-critic algorithm which we use as a component in the ensemble method. A2C is introduced to improve the policy gradient updates. A2C utilizes an advantage function to reduce the variance of the policy gradient. Instead of only estimates the value function, the critic network estimates the advantage function. Thus, the evaluation of an action not only depends on how good the action is, but also considers how much better it can be. So that it reduces the high variance of the policy networks and makes the model more robust." }, { "code": null, "e": 20145, "s": 19492, "text": "A2C uses copies of the same agent working in parallel to update gradients with different data samples. Each agent works independently to interact with the same environment. After all of the parallel agents finish calculating their gradients, A2C uses a coordinator to pass the average gradients over all the agents to a global network. So that the global network can update the actor and the critic network. The presence of a global network increases the diversity of training data. The synchronized gradient update is more cost-effective, faster and works better with large batch sizes. A2C is a great model for stock trading because of its stability." }, { "code": null, "e": 20692, "s": 20145, "text": "DDPG is an actor-critic based algorithm which we use as a component in the ensemble strategy to maximize the investment return. DDPG combines the frameworks of both Q-learning and policy gradient, and uses neural networks as function approximators. In contrast with DQN that learns indirectly through Q-values tables and suffers the curse of dimensionality problem, DDPG learns directly from the observations through policy gradient. It is proposed to deterministically map states to actions to better fit the continuous action space environment." }, { "code": null, "e": 21024, "s": 20692, "text": "We explore and use PPO as a component in the ensemble method. PPO is introduced to control the policy gradient update and ensure that the new policy will not be too different from the older one. PPO tries to simplify the objective of Trust Region Policy Optimization (TRPO) by introducing a clipping term to the objective function." }, { "code": null, "e": 21404, "s": 21024, "text": "The objective function of PPO takes the minimum of the clipped and normal objective. PPO discourages large policy change move outside of the clipped interval. Therefore, PPO improves the stability of the policy networks training by restricting the policy update at each training step. We select PPO for stock trading because it is stable, fast, and simpler to implement and tune." }, { "code": null, "e": 21649, "s": 21404, "text": "Our purpose is to create a highly robust trading strategy. So we use an ensemble method to automatically select the best performing agent among PPO, A2C, and DDPG to trade based on the Sharpe ratio. The ensemble process is described as follows:" }, { "code": null, "e": 21801, "s": 21649, "text": "Step 1. We use a growing window of n months to retrain our three agents concurrently. In this paper, we retrain our three agents at every three months." }, { "code": null, "e": 22054, "s": 21801, "text": "Step 2. We validate all three agents by using a 3-month validation rolling window followed by training to pick the best performing agent which has the highest Sharpe ratio. We also adjust risk-aversion by using turbulence index in our validation stage." }, { "code": null, "e": 22180, "s": 22054, "text": "Step 3. After validation, we only use the best model with the highest Sharpe ratio to predict and trade for the next quarter." }, { "code": null, "e": 23737, "s": 22180, "text": "from stable_baselines import SACfrom stable_baselines import PPO2from stable_baselines import A2Cfrom stable_baselines import DDPGfrom stable_baselines import TD3from stable_baselines.ddpg.policies import DDPGPolicyfrom stable_baselines.common.policies import MlpPolicyfrom stable_baselines.common.vec_env import DummyVecEnvdef train_A2C(env_train, model_name, timesteps=10000): “””A2C model””” start = time.time() model = A2C(‘MlpPolicy’, env_train, verbose=0) model.learn(total_timesteps=timesteps) end = time.time() model.save(f”{config.TRAINED_MODEL_DIR}/{model_name}”) print(‘Training time (A2C): ‘, (end-start)/60,’ minutes’) return modeldef train_DDPG(env_train, model_name, timesteps=10000): “””DDPG model””” start = time.time() model = DDPG(‘MlpPolicy’, env_train) model.learn(total_timesteps=timesteps) end = time.time() model.save(f”{config.TRAINED_MODEL_DIR}/{model_name}”) print(‘Training time (DDPG): ‘, (end-start)/60,’ minutes’) return modeldef train_PPO(env_train, model_name, timesteps=50000): “””PPO model””” start = time.time() model = PPO2(‘MlpPolicy’, env_train) model.learn(total_timesteps=timesteps) end = time.time() model.save(f”{config.TRAINED_MODEL_DIR}/{model_name}”) print(‘Training time (PPO): ‘, (end-start)/60,’ minutes’) return modeldef DRL_prediction(model, test_data, test_env, test_obs): “””make a prediction””” start = time.time() for i in range(len(test_data.index.unique())): action, _states = model.predict(test_obs) test_obs, rewards, dones, info = test_env.step(action) # env_test.render() end = time.time()" }, { "code": null, "e": 23930, "s": 23737, "text": "We use Quantopian’s pyfolio to do the backtesting. The charts look pretty good, and it takes literally one line of code to implement it. You just need to convert everything into daily returns." }, { "code": null, "e": 24102, "s": 23930, "text": "import pyfoliowith pyfolio.plotting.plotting_context(font_scale=1.1): pyfolio.create_full_tear_sheet(returns = ensemble_strat, benchmark_rets=dow_strat, set_context=False)" }, { "code": null, "e": 24114, "s": 24102, "text": "References:" }, { "code": null, "e": 24400, "s": 24114, "text": "A2C:Volodymyr Mnih, Adrià Badia, Mehdi Mirza, Alex Graves, Timothy Lillicrap, Tim Harley, David Silver, and Koray Kavukcuoglu. 2016. Asynchronous methods for deep reinforcement learning. The 33rd International Conference on Machine Learning (02 2016). https://arxiv.org/abs/1602.01783" }, { "code": null, "e": 24697, "s": 24400, "text": "DDPG:Timothy Lillicrap, Jonathan Hunt, Alexander Pritzel, Nicolas Heess, Tom Erez, Yuval Tassa, David Silver, and Daan Wierstra. 2015. Continuous control with deep reinforcement learning. International Conference on Learning Representations (ICLR) 2016 (09 2015). https://arxiv.org/abs/1509.02971" }, { "code": null, "e": 24913, "s": 24697, "text": "PPO:John Schulman, Sergey Levine, Philipp Moritz, Michael Jordan, and Pieter Abbeel. 2015. Trust region policy optimization. In The 31st International Conference on Machine Learning. https://arxiv.org/abs/1502.05477" } ]
Linear search in Java.
Following is the required program. Live Demo public class Tester { public static int linearSearch(int[] arr, int element) { for (int i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } public static void main(String a[]) { int[] array = { 10, 20, 30, 50, 70, 90 }; int element = 50; int index = linearSearch(array, element); if (index != -1) { System.out.println(element + " present at index: " +index); } else { System.out.println(element + " is not present."); } } } 50 present at index: 3
[ { "code": null, "e": 1097, "s": 1062, "text": "Following is the required program." }, { "code": null, "e": 1107, "s": 1097, "text": "Live Demo" }, { "code": null, "e": 1675, "s": 1107, "text": "public class Tester {\n public static int linearSearch(int[] arr, int element) {\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] == element) {\n return i;\n }\n }\n return -1;\n }\n public static void main(String a[]) {\n int[] array = { 10, 20, 30, 50, 70, 90 };\n int element = 50;\n int index = linearSearch(array, element);\n if (index != -1) {\n System.out.println(element + \" present at index: \" +index);\n } else {\n System.out.println(element + \" is not present.\");\n }\n }\n}" }, { "code": null, "e": 1698, "s": 1675, "text": "50 present at index: 3" } ]
How can we parse a nested JSON object in Java?
The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. A JSONArray can parse text from a String to produce a vector-like object. We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index).getString() method and it returns a string value at the specified position. String getString(int index) import java.util.*; import org.json.*; public class NestedJSONObjectTest { public static void main(String args[]) { String jsonDataString = "{userInfo : [{username:abc123}, {username:xyz123},{username:pqr123}, {username:mno123},{username:jkl123}]}"; JSONObject jsonObject = new JSONObject(jsonDataString); List<String> list = new ArrayList<String>(); JSONArray jsonArray = jsonObject.getJSONArray("userInfo"); for(int i = 0 ; i < jsonArray.length(); i++) { list.add(jsonArray.getJSONObject(i).getString("username")); System.out.println(jsonArray.getJSONObject(i).getString("username")); // display usernames } } } abc123 xyz123 pqr123 mno123 jkl123
[ { "code": null, "e": 1506, "s": 1062, "text": "The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. A JSONArray can parse text from a String to produce a vector-like object. We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index).getString() method and it returns a string value at the specified position." }, { "code": null, "e": 1534, "s": 1506, "text": "String getString(int index)" }, { "code": null, "e": 2210, "s": 1534, "text": "import java.util.*;\nimport org.json.*;\npublic class NestedJSONObjectTest {\n public static void main(String args[]) {\n String jsonDataString = \"{userInfo : [{username:abc123}, {username:xyz123},{username:pqr123}, {username:mno123},{username:jkl123}]}\";\n JSONObject jsonObject = new JSONObject(jsonDataString);\n List<String> list = new ArrayList<String>();\n JSONArray jsonArray = jsonObject.getJSONArray(\"userInfo\");\n for(int i = 0 ; i < jsonArray.length(); i++) {\n list.add(jsonArray.getJSONObject(i).getString(\"username\"));\n System.out.println(jsonArray.getJSONObject(i).getString(\"username\")); // display usernames\n }\n }\n}" }, { "code": null, "e": 2245, "s": 2210, "text": "abc123\nxyz123\npqr123\nmno123\njkl123" } ]
Python | os.path.dirname() method
26 Aug, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation. os.path.dirname() method in Python is used to get the directory name from the specified path. Syntax: os.path.dirname(path) Parameter:path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path. Code: Use of os.path.dirname() method # Python program to explain os.path.dirname() method # importing os.path module import os.path # Pathpath = '/home/User/Documents' # Get the directory name # from the specified pathdirname = os.path.dirname(path) # Print the directory name print(dirname) # Pathpath = '/home/User/Documents/file.txt' # Get the directory name # from the specified pathdirname = os.path.dirname(path) # Print the directory name print(dirname) # Pathpath = 'file.txt' # Get the directory name # from the specified pathdirname = os.path.dirname(path) # Print the directory name print(dirname) # In the above specified path # does not contains any# directory so, # It will print Nothing /home/User /home/User/Documents Reference: https://docs.python.org/3/library/os.path.html Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2019" }, { "code": null, "e": 339, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation." }, { "code": null, "e": 433, "s": 339, "text": "os.path.dirname() method in Python is used to get the directory name from the specified path." }, { "code": null, "e": 463, "s": 433, "text": "Syntax: os.path.dirname(path)" }, { "code": null, "e": 531, "s": 463, "text": "Parameter:path: A path-like object representing a file system path." }, { "code": null, "e": 640, "s": 531, "text": "Return Type: This method returns a string value which represents the directory name from the specified path." }, { "code": null, "e": 678, "s": 640, "text": "Code: Use of os.path.dirname() method" }, { "code": "# Python program to explain os.path.dirname() method # importing os.path module import os.path # Pathpath = '/home/User/Documents' # Get the directory name # from the specified pathdirname = os.path.dirname(path) # Print the directory name print(dirname) # Pathpath = '/home/User/Documents/file.txt' # Get the directory name # from the specified pathdirname = os.path.dirname(path) # Print the directory name print(dirname) # Pathpath = 'file.txt' # Get the directory name # from the specified pathdirname = os.path.dirname(path) # Print the directory name print(dirname) # In the above specified path # does not contains any# directory so, # It will print Nothing ", "e": 1369, "s": 678, "text": null }, { "code": null, "e": 1403, "s": 1369, "text": "/home/User\n/home/User/Documents\n\n" }, { "code": null, "e": 1461, "s": 1403, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 1483, "s": 1461, "text": "Python OS-path-module" }, { "code": null, "e": 1500, "s": 1483, "text": "python-os-module" }, { "code": null, "e": 1507, "s": 1500, "text": "Python" }, { "code": null, "e": 1605, "s": 1507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1623, "s": 1605, "text": "Python Dictionary" }, { "code": null, "e": 1665, "s": 1623, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1687, "s": 1665, "text": "Enumerate() in Python" }, { "code": null, "e": 1722, "s": 1687, "text": "Read a file line by line in Python" }, { "code": null, "e": 1748, "s": 1722, "text": "Python String | replace()" }, { "code": null, "e": 1780, "s": 1748, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1809, "s": 1780, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1836, "s": 1809, "text": "Python Classes and Objects" }, { "code": null, "e": 1866, "s": 1836, "text": "Iterate over a list in Python" } ]
Creating a dataframe from Pandas series
05 Feb, 2019 Series is a type of list in pandas which can take integer values, string values, double values and more. But in Pandas Series we return an object in the form of list, having index starting from 0 to n, Where n is the length of values in series. Later in this article, we will discuss dataframes in pandas, but we first need to understand the main difference between Series and Dataframe. Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data. Code #1: Creating a simple Series import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti'] auth_series = pd.Series(author)print(auth_series) Output: 0 Jitender 1 Purnima 2 Arpit 3 Jyoti dtype: object Let’s check type of Series: import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti'] auth_series = pd.Series(author)print(type(auth_series)) Output: <class 'pandas.core.series.Series'> Code #2: Creating Dataframe from Series import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame) print(result) Output: Author Article 0 Jitender 210 1 Purnima 211 2 Arpit 114 3 Jyoti 178 Explanation:We are combining two series Author and Article published. Create a dictionary so that we can combine the metadata for series. Metadata is the data of data that can define the series of values. Pass this dictionary to pandas DataFrame and finally you can see the result as combination of two series i.e for author and number of articles. Code #3: How to add series externally in dataframe import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame)age = [21, 21, 24, 23] result['Age'] = pd.Series(age) print(result) Output: Author Article Age 0 Jitender 210 21 1 Purnima 211 21 2 Arpit 114 24 3 Jyoti 178 23 Explanation:We have added one more series externally named as age of the authors, then directly added this series in the pandas dataframe. Remember one thing if any value is missing then by default it will be converted into NaN value i.e null by default. Code #4: Missing value in dataframe import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame)age = [21, 21, 23] result['Age'] = pd.Series(age) print(result) Output: Author Article Age 0 Jitender 210 21.0 1 Purnima 211 21.0 2 Arpit 114 23.0 3 Jyoti 178 NaN Code #5: Data Plot on graph Using plot.bar() we have created a bar graph. import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame)age = [21, 21, 24, 23] result['Age'] = pd.Series(age) result.plot.bar()plt.show() Output: pandas-dataframe-program pandas-series-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Create a Pandas DataFrame from Lists
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Feb, 2019" }, { "code": null, "e": 299, "s": 54, "text": "Series is a type of list in pandas which can take integer values, string values, double values and more. But in Pandas Series we return an object in the form of list, having index starting from 0 to n, Where n is the length of values in series." }, { "code": null, "e": 639, "s": 299, "text": "Later in this article, we will discuss dataframes in pandas, but we first need to understand the main difference between Series and Dataframe. Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data." }, { "code": null, "e": 673, "s": 639, "text": "Code #1: Creating a simple Series" }, { "code": "import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti'] auth_series = pd.Series(author)print(auth_series)", "e": 827, "s": 673, "text": null }, { "code": null, "e": 835, "s": 827, "text": "Output:" }, { "code": null, "e": 906, "s": 835, "text": "0 Jitender\n1 Purnima\n2 Arpit\n3 Jyoti\ndtype: object\n" }, { "code": null, "e": 934, "s": 906, "text": "Let’s check type of Series:" }, { "code": "import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti'] auth_series = pd.Series(author)print(type(auth_series))", "e": 1094, "s": 934, "text": null }, { "code": null, "e": 1102, "s": 1094, "text": "Output:" }, { "code": null, "e": 1139, "s": 1102, "text": "<class 'pandas.core.series.Series'>\n" }, { "code": null, "e": 1180, "s": 1139, "text": " Code #2: Creating Dataframe from Series" }, { "code": "import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame) print(result)", "e": 1488, "s": 1180, "text": null }, { "code": null, "e": 1496, "s": 1488, "text": "Output:" }, { "code": null, "e": 1602, "s": 1496, "text": " Author Article\n0 Jitender 210\n1 Purnima 211\n2 Arpit 114\n3 Jyoti 178\n" }, { "code": null, "e": 2002, "s": 1602, "text": "Explanation:We are combining two series Author and Article published. Create a dictionary so that we can combine the metadata for series. Metadata is the data of data that can define the series of values. Pass this dictionary to pandas DataFrame and finally you can see the result as combination of two series i.e for author and number of articles. Code #3: How to add series externally in dataframe" }, { "code": "import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame)age = [21, 21, 24, 23] result['Age'] = pd.Series(age) print(result)", "e": 2364, "s": 2002, "text": null }, { "code": null, "e": 2372, "s": 2364, "text": "Output:" }, { "code": null, "e": 2503, "s": 2372, "text": " Author Article Age\n0 Jitender 210 21\n1 Purnima 211 21\n2 Arpit 114 24\n3 Jyoti 178 23\n" }, { "code": null, "e": 2794, "s": 2503, "text": "Explanation:We have added one more series externally named as age of the authors, then directly added this series in the pandas dataframe. Remember one thing if any value is missing then by default it will be converted into NaN value i.e null by default. Code #4: Missing value in dataframe" }, { "code": "import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame)age = [21, 21, 23] result['Age'] = pd.Series(age) print(result)", "e": 3152, "s": 2794, "text": null }, { "code": null, "e": 3160, "s": 3152, "text": "Output:" }, { "code": null, "e": 3296, "s": 3160, "text": " Author Article Age\n0 Jitender 210 21.0\n1 Purnima 211 21.0\n2 Arpit 114 23.0\n3 Jyoti 178 NaN\n" }, { "code": null, "e": 3325, "s": 3296, "text": " Code #5: Data Plot on graph" }, { "code": null, "e": 3371, "s": 3325, "text": "Using plot.bar() we have created a bar graph." }, { "code": "import pandas as pdimport matplotlib.pyplot as plt author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']article = [210, 211, 114, 178] auth_series = pd.Series(author)article_series = pd.Series(article) frame = { 'Author': auth_series, 'Article': article_series } result = pd.DataFrame(frame)age = [21, 21, 24, 23] result['Age'] = pd.Series(age) result.plot.bar()plt.show()", "e": 3747, "s": 3371, "text": null }, { "code": null, "e": 3755, "s": 3747, "text": "Output:" }, { "code": null, "e": 3780, "s": 3755, "text": "pandas-dataframe-program" }, { "code": null, "e": 3802, "s": 3780, "text": "pandas-series-program" }, { "code": null, "e": 3809, "s": 3802, "text": "Picked" }, { "code": null, "e": 3833, "s": 3809, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3847, "s": 3833, "text": "Python-pandas" }, { "code": null, "e": 3854, "s": 3847, "text": "Python" }, { "code": null, "e": 3952, "s": 3854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3970, "s": 3952, "text": "Python Dictionary" }, { "code": null, "e": 3992, "s": 3970, "text": "Enumerate() in Python" }, { "code": null, "e": 4024, "s": 3992, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4053, "s": 4024, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4080, "s": 4053, "text": "Python Classes and Objects" }, { "code": null, "e": 4116, "s": 4080, "text": "Convert integer to string in Python" }, { "code": null, "e": 4137, "s": 4116, "text": "Python OOPs Concepts" }, { "code": null, "e": 4168, "s": 4137, "text": "Python | os.path.join() method" }, { "code": null, "e": 4224, "s": 4168, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Calculate standard deviation of a Matrix in Python
26 Nov, 2020 In this article we will learn how to calculate standard deviation of a Matrix using Python. Standard deviation is used to measure the spread of values within the dataset. It indicates variations or dispersion of values in the dataset and also helps to determine the confidence in a model’s statistical conclusions. It is represented by the sigma (σ) and calculates by taking the square root of the variance. If the standard deviation is low it means most of the values are closer to the mean and if high, that means closer to the mean. In this article, we will learn what are the different ways to calculate SD in Python. We can calculate the Standard Deviation using the following method : std() method in NumPy packagestdev() method in Statistics package std() method in NumPy package stdev() method in Statistics package Method 1:std() method in NumPy package. Python3 # import required packagesimport numpy as np # Create matrixmatrix = np.array([[33, 55, 66, 74], [23, 45, 65, 27], [87, 96, 34, 54]]) print("Your matrix:\n", matrix) # use std() methodsd = np.std(matrix)print("Standard Deviation :\n", sd) Output : Your matrix: [[33 55 66 74] [23 45 65 27] [87 96 34 54]] Standard Deviation : 22.584870796373593 Method 2: stdev() method in Statistics package. Python3 import statistics statistics.stdev([11, 43, 56, 77, 87, 45, 67, 33]) Output : 24.67466890789592 Python-Matrix Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 120, "s": 28, "text": "In this article we will learn how to calculate standard deviation of a Matrix using Python." }, { "code": null, "e": 650, "s": 120, "text": "Standard deviation is used to measure the spread of values within the dataset. It indicates variations or dispersion of values in the dataset and also helps to determine the confidence in a model’s statistical conclusions. It is represented by the sigma (σ) and calculates by taking the square root of the variance. If the standard deviation is low it means most of the values are closer to the mean and if high, that means closer to the mean. In this article, we will learn what are the different ways to calculate SD in Python." }, { "code": null, "e": 720, "s": 650, "text": "We can calculate the Standard Deviation using the following method : " }, { "code": null, "e": 786, "s": 720, "text": "std() method in NumPy packagestdev() method in Statistics package" }, { "code": null, "e": 816, "s": 786, "text": "std() method in NumPy package" }, { "code": null, "e": 853, "s": 816, "text": "stdev() method in Statistics package" }, { "code": null, "e": 893, "s": 853, "text": "Method 1:std() method in NumPy package." }, { "code": null, "e": 901, "s": 893, "text": "Python3" }, { "code": "# import required packagesimport numpy as np # Create matrixmatrix = np.array([[33, 55, 66, 74], [23, 45, 65, 27], [87, 96, 34, 54]]) print(\"Your matrix:\\n\", matrix) # use std() methodsd = np.std(matrix)print(\"Standard Deviation :\\n\", sd)", "e": 1160, "s": 901, "text": null }, { "code": null, "e": 1169, "s": 1160, "text": "Output :" }, { "code": null, "e": 1267, "s": 1169, "text": "Your matrix:\n[[33 55 66 74]\n[23 45 65 27]\n[87 96 34 54]]\nStandard Deviation :\n22.584870796373593\n" }, { "code": null, "e": 1315, "s": 1267, "text": "Method 2: stdev() method in Statistics package." }, { "code": null, "e": 1323, "s": 1315, "text": "Python3" }, { "code": "import statistics statistics.stdev([11, 43, 56, 77, 87, 45, 67, 33])", "e": 1395, "s": 1323, "text": null }, { "code": null, "e": 1404, "s": 1395, "text": "Output :" }, { "code": null, "e": 1423, "s": 1404, "text": "24.67466890789592\n" }, { "code": null, "e": 1437, "s": 1423, "text": "Python-Matrix" }, { "code": null, "e": 1461, "s": 1437, "text": "Technical Scripter 2020" }, { "code": null, "e": 1468, "s": 1461, "text": "Python" }, { "code": null, "e": 1487, "s": 1468, "text": "Technical Scripter" }, { "code": null, "e": 1585, "s": 1487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1617, "s": 1585, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1644, "s": 1617, "text": "Python Classes and Objects" }, { "code": null, "e": 1675, "s": 1644, "text": "Python | os.path.join() method" }, { "code": null, "e": 1696, "s": 1675, "text": "Python OOPs Concepts" }, { "code": null, "e": 1752, "s": 1696, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1775, "s": 1752, "text": "Introduction To PYTHON" }, { "code": null, "e": 1817, "s": 1775, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1859, "s": 1817, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1898, "s": 1859, "text": "Python | datetime.timedelta() function" } ]
Left rotation of an array using vectors in C++
01 Jun, 2022 Given an array arr[] of integers and another integer D, the task is to perform D left rotations on the array and print the modified array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 2 Output: 3 4 5 6 1 2 Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 12 Output: 1 2 3 4 5 6 Approach: Using vectors in C++, a rotation can be performed by removing the first element from the vector and then inserting it in the end of the same vector. Similarly, all the required rotations can be performed and then print the contents of the modified vector to get the required rotated array. Below is the implementation of the above approach: CPP // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to left rotate the array by d elements// here we are passing vector by reference to avoid copying// that just make our program slowvoid rotate(vector<int>& vec, int d){ // Base case if (d == 0) return; // Push first d elements from the beginning // to the end and remove those elements // from the beginning for (int i = 0; i < d; i++) { // adding first element at // the end of vector vec.push_back(vec[0]); // removing first element vec.erase(vec.begin()); } // Print the rotated array for (int i = 0; i < vec.size(); i++) { cout << vec[i] << " "; }} // Driver codeint main(){ vector<int> vec = { 1, 2, 3, 4, 5, 6 }; int n = vec.size(); int d = 2; // Function call rotate(vec, d % n); return 0;} 3 4 5 6 1 2 Time Complexity: O(n)Auxiliary Space: O(1) prerna_mehraa sachinvinod1904 rotation Arrays C++ Programs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2022" }, { "code": null, "e": 167, "s": 28, "text": "Given an array arr[] of integers and another integer D, the task is to perform D left rotations on the array and print the modified array." }, { "code": null, "e": 178, "s": 167, "text": "Examples: " }, { "code": null, "e": 302, "s": 178, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 2\nOutput: 3 4 5 6 1 2\n\nInput: arr[] = {1, 2, 3, 4, 5, 6}, D = 12\nOutput: 1 2 3 4 5 6" }, { "code": null, "e": 602, "s": 302, "text": "Approach: Using vectors in C++, a rotation can be performed by removing the first element from the vector and then inserting it in the end of the same vector. Similarly, all the required rotations can be performed and then print the contents of the modified vector to get the required rotated array." }, { "code": null, "e": 653, "s": 602, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 657, "s": 653, "text": "CPP" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to left rotate the array by d elements// here we are passing vector by reference to avoid copying// that just make our program slowvoid rotate(vector<int>& vec, int d){ // Base case if (d == 0) return; // Push first d elements from the beginning // to the end and remove those elements // from the beginning for (int i = 0; i < d; i++) { // adding first element at // the end of vector vec.push_back(vec[0]); // removing first element vec.erase(vec.begin()); } // Print the rotated array for (int i = 0; i < vec.size(); i++) { cout << vec[i] << \" \"; }} // Driver codeint main(){ vector<int> vec = { 1, 2, 3, 4, 5, 6 }; int n = vec.size(); int d = 2; // Function call rotate(vec, d % n); return 0;}", "e": 1563, "s": 657, "text": null }, { "code": null, "e": 1576, "s": 1563, "text": "3 4 5 6 1 2 " }, { "code": null, "e": 1619, "s": 1576, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 1633, "s": 1619, "text": "prerna_mehraa" }, { "code": null, "e": 1649, "s": 1633, "text": "sachinvinod1904" }, { "code": null, "e": 1658, "s": 1649, "text": "rotation" }, { "code": null, "e": 1665, "s": 1658, "text": "Arrays" }, { "code": null, "e": 1678, "s": 1665, "text": "C++ Programs" }, { "code": null, "e": 1685, "s": 1678, "text": "Arrays" } ]
Python Program for Difference between sums of odd and even digits
09 Jun, 2022 Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for the leftmost digit). Examples: Input : 1212112 Output : Yes Explanation:- the odd position element is 2+2+1=5 the even position element is 1+1+1+2=5 the difference is 5-5=0.so print yes. Input :12345 Output : No Explanation:- the odd position element is 1+3+5=9 the even position element is 2+4=6 the difference is 9-6=3 not equal to zero. So print no. Method 1: One by one traverse digits and find the two sums. If the difference between two sums is 0, print yes, else no. Python3 # Python program to check if difference between sum of# odd digits and sum of even digits is 0 or not # Reading Inputnum = int(input())string1 = str(num)evensum = 0oddsum = 0 # Driver Codefor i in range(0, len(string1)): if(i % 2 == 0): evensum += int(string1[i]) else: oddsum += int(string1[i]) # Conditionif(oddsum-evensum == 0): print("Yes")else: print("No") Yes Method 2: This can be easily solved using divisibility of 11. This condition is only satisfied if the number is divisible by 11. So check the number is divisible by 11 or not. Example Python # Python program to check if difference between sum of# odd digits and sum of even digits is 0 or not def isDiff(n): return (n % 11 == 0) # Driver coden = 1243if (isDiff(n)): print("Yes")else: print("No") Yes Please refer complete article on Difference between sums of odd and even digits for more details! kogantibhavya Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jun, 2022" }, { "code": null, "e": 211, "s": 28, "text": "Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for the leftmost digit)." }, { "code": null, "e": 221, "s": 211, "text": "Examples:" }, { "code": null, "e": 377, "s": 221, "text": "Input : 1212112\nOutput : Yes\nExplanation:-\nthe odd position element is 2+2+1=5\nthe even position element is 1+1+1+2=5\nthe difference is 5-5=0.so print yes." }, { "code": null, "e": 544, "s": 377, "text": "Input :12345\nOutput : No\nExplanation:-\nthe odd position element is 1+3+5=9\nthe even position element is 2+4=6\nthe difference is 9-6=3 not equal\nto zero. So print no." }, { "code": null, "e": 665, "s": 544, "text": "Method 1: One by one traverse digits and find the two sums. If the difference between two sums is 0, print yes, else no." }, { "code": null, "e": 673, "s": 665, "text": "Python3" }, { "code": "# Python program to check if difference between sum of# odd digits and sum of even digits is 0 or not # Reading Inputnum = int(input())string1 = str(num)evensum = 0oddsum = 0 # Driver Codefor i in range(0, len(string1)): if(i % 2 == 0): evensum += int(string1[i]) else: oddsum += int(string1[i]) # Conditionif(oddsum-evensum == 0): print(\"Yes\")else: print(\"No\")", "e": 1063, "s": 673, "text": null }, { "code": null, "e": 1068, "s": 1063, "text": "Yes\n" }, { "code": null, "e": 1245, "s": 1068, "text": "Method 2: This can be easily solved using divisibility of 11. This condition is only satisfied if the number is divisible by 11. So check the number is divisible by 11 or not. " }, { "code": null, "e": 1253, "s": 1245, "text": "Example" }, { "code": null, "e": 1260, "s": 1253, "text": "Python" }, { "code": "# Python program to check if difference between sum of# odd digits and sum of even digits is 0 or not def isDiff(n): return (n % 11 == 0) # Driver coden = 1243if (isDiff(n)): print(\"Yes\")else: print(\"No\")", "e": 1476, "s": 1260, "text": null }, { "code": null, "e": 1481, "s": 1476, "text": "Yes\n" }, { "code": null, "e": 1579, "s": 1481, "text": "Please refer complete article on Difference between sums of odd and even digits for more details!" }, { "code": null, "e": 1593, "s": 1579, "text": "kogantibhavya" }, { "code": null, "e": 1609, "s": 1593, "text": "Python Programs" } ]
XMLStreamWriter in Java StAX
16 Sep, 2021 Streaming API for XML added in Java 6 provides a handy interface XMLStreamWriter which is used for writing XML documents. this API does not require building any specific object structure like in DOM and doing any intermediate tasks. It also supports namespaces by default which is very useful in more advanced situations. Methods that are incorporated in order to create XMLStreamWriter object and write data into it are listed below as follows: writeStartDocument() writeStartElement() writeCharacters() writeEndElement() writeEndDocument() There are certain limitations been attached with XMLStreamWriter in java StAX of which primarily are as follows: It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.XMLStreamWriter does not indent its output so it may be a bit hard to read using a plain text editor. Therefore, for reading, it is suggested to open it in a web browser most of which has a user-friendly interface to view the structure of XML documents. It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition. XMLStreamWriter does not indent its output so it may be a bit hard to read using a plain text editor. Therefore, for reading, it is suggested to open it in a web browser most of which has a user-friendly interface to view the structure of XML documents. Procedure: Create instance of XMLStreamWriter using XMLOutputFactoryWrite the header of the XML and proceed to write elements.After adding elements we can add attributes, character data, or CDATAClose opened elementsEmptying elements or write commentsClose and finish XML document Create instance of XMLStreamWriter using XMLOutputFactory Write the header of the XML and proceed to write elements. After adding elements we can add attributes, character data, or CDATA Close opened elements Emptying elements or write comments Close and finish XML document Now let us do discuss more how they are written later on implementing the same in our java program. Step 1: Create instance of XMLStreamWriter using XMLOutputFactory. XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream); Step 2: Write the header of the XML and proceed to write elements. xmlStreamWriter.writeStartElement("gfg"); Step 3: After adding elements we can add attributes, character data, or CDATA. xmlStreamWriter.writeAttribute("id", "10"); xmlStreamWriter.writeCharacters("hello world!"); xmlStreamWriter.writeCData("more text data"); Step 4: Closing opened elements xmlStreamWriter.writeEndElement(); Step 5: Emptying elements or write comments, but do note it is an optional step xmlStreamWriter.writeEmptyElement("used & new"); xmlStreamWriter.writeComment("Thank you!"); Step 6: Close and finish XML document. xmlStreamWriter.writeEndDocument(); xmlStreamWriter.close(); Example Java // Java Program to Illustrate XMLStreamWriter in Java StAX // Importing required classesimport java.io.FileNotFoundException;import java.io.FileWriter;import java.io.UnsupportedEncodingException;import java.io.Writer;import javax.xml.stream.XMLOutputFactory;import javax.xml.stream.XMLStreamException;import javax.xml.stream.XMLStreamWriter; // Main classpublic class StaxXMLStreamWriter { // Main driver method public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException { // Try block to check for exceptions try { // File Path String filePath = "D:\\gfg_file.xml"; // Creating FileWriter object Writer fileWriter = new FileWriter(filePath); // Getting the XMLOutputFactory instance XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); // Creating XMLStreamWriter object from // xmlOutputFactory. XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter( fileWriter); // Addoing elements to xmlStreamWriter // Custom input element addition xmlStreamWriter.writeStartElement("gfg"); xmlStreamWriter.writeAttribute("id", "10"); xmlStreamWriter.writeCharacters("hello world!"); xmlStreamWriter.writeCData("more text data"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEmptyElement("used & new"); xmlStreamWriter.writeComment("Thank you!"); xmlStreamWriter.writeEndDocument(); // Writing the content on XML file and // close xmlStreamWriter using close() method xmlStreamWriter.flush(); xmlStreamWriter.close(); // Display message for successful execution of // program System.out.println( "XML file created successfully."); } // Catch block to handle exceptions catch (Exception e) { // Print the line number where exception occurs e.printStackTrace(); } }} Output: <gfg id="10">hello world! <![CDATA[more text data]]> </gfg> <used & new/> <!--Thank you!--> Conclusion: Streaming API for XML provides a very convenient, fast, and memory-efficient way to write XML documents without worrying about details and escaping special characters. It is a great alternative to DOM especially when you don’t need to keep and manage DOM tree in memory for any reason. Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Sep, 2021" }, { "code": null, "e": 350, "s": 28, "text": "Streaming API for XML added in Java 6 provides a handy interface XMLStreamWriter which is used for writing XML documents. this API does not require building any specific object structure like in DOM and doing any intermediate tasks. It also supports namespaces by default which is very useful in more advanced situations." }, { "code": null, "e": 474, "s": 350, "text": "Methods that are incorporated in order to create XMLStreamWriter object and write data into it are listed below as follows:" }, { "code": null, "e": 495, "s": 474, "text": "writeStartDocument()" }, { "code": null, "e": 515, "s": 495, "text": "writeStartElement()" }, { "code": null, "e": 533, "s": 515, "text": "writeCharacters()" }, { "code": null, "e": 551, "s": 533, "text": "writeEndElement()" }, { "code": null, "e": 570, "s": 551, "text": "writeEndDocument()" }, { "code": null, "e": 684, "s": 570, "text": "There are certain limitations been attached with XMLStreamWriter in java StAX of which primarily are as follows:" }, { "code": null, "e": 1081, "s": 684, "text": "It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.XMLStreamWriter does not indent its output so it may be a bit hard to read using a plain text editor. Therefore, for reading, it is suggested to open it in a web browser most of which has a user-friendly interface to view the structure of XML documents." }, { "code": null, "e": 1225, "s": 1081, "text": "It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition." }, { "code": null, "e": 1479, "s": 1225, "text": "XMLStreamWriter does not indent its output so it may be a bit hard to read using a plain text editor. Therefore, for reading, it is suggested to open it in a web browser most of which has a user-friendly interface to view the structure of XML documents." }, { "code": null, "e": 1490, "s": 1479, "text": "Procedure:" }, { "code": null, "e": 1760, "s": 1490, "text": "Create instance of XMLStreamWriter using XMLOutputFactoryWrite the header of the XML and proceed to write elements.After adding elements we can add attributes, character data, or CDATAClose opened elementsEmptying elements or write commentsClose and finish XML document" }, { "code": null, "e": 1818, "s": 1760, "text": "Create instance of XMLStreamWriter using XMLOutputFactory" }, { "code": null, "e": 1877, "s": 1818, "text": "Write the header of the XML and proceed to write elements." }, { "code": null, "e": 1947, "s": 1877, "text": "After adding elements we can add attributes, character data, or CDATA" }, { "code": null, "e": 1969, "s": 1947, "text": "Close opened elements" }, { "code": null, "e": 2005, "s": 1969, "text": "Emptying elements or write comments" }, { "code": null, "e": 2035, "s": 2005, "text": "Close and finish XML document" }, { "code": null, "e": 2135, "s": 2035, "text": "Now let us do discuss more how they are written later on implementing the same in our java program." }, { "code": null, "e": 2202, "s": 2135, "text": "Step 1: Create instance of XMLStreamWriter using XMLOutputFactory." }, { "code": null, "e": 2351, "s": 2202, "text": "XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();\nXMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream);" }, { "code": null, "e": 2418, "s": 2351, "text": "Step 2: Write the header of the XML and proceed to write elements." }, { "code": null, "e": 2460, "s": 2418, "text": "xmlStreamWriter.writeStartElement(\"gfg\");" }, { "code": null, "e": 2539, "s": 2460, "text": "Step 3: After adding elements we can add attributes, character data, or CDATA." }, { "code": null, "e": 2678, "s": 2539, "text": "xmlStreamWriter.writeAttribute(\"id\", \"10\");\nxmlStreamWriter.writeCharacters(\"hello world!\");\nxmlStreamWriter.writeCData(\"more text data\");" }, { "code": null, "e": 2710, "s": 2678, "text": "Step 4: Closing opened elements" }, { "code": null, "e": 2745, "s": 2710, "text": "xmlStreamWriter.writeEndElement();" }, { "code": null, "e": 2825, "s": 2745, "text": "Step 5: Emptying elements or write comments, but do note it is an optional step" }, { "code": null, "e": 2918, "s": 2825, "text": "xmlStreamWriter.writeEmptyElement(\"used & new\");\nxmlStreamWriter.writeComment(\"Thank you!\");" }, { "code": null, "e": 2957, "s": 2918, "text": "Step 6: Close and finish XML document." }, { "code": null, "e": 3018, "s": 2957, "text": "xmlStreamWriter.writeEndDocument();\nxmlStreamWriter.close();" }, { "code": null, "e": 3026, "s": 3018, "text": "Example" }, { "code": null, "e": 3031, "s": 3026, "text": "Java" }, { "code": "// Java Program to Illustrate XMLStreamWriter in Java StAX // Importing required classesimport java.io.FileNotFoundException;import java.io.FileWriter;import java.io.UnsupportedEncodingException;import java.io.Writer;import javax.xml.stream.XMLOutputFactory;import javax.xml.stream.XMLStreamException;import javax.xml.stream.XMLStreamWriter; // Main classpublic class StaxXMLStreamWriter { // Main driver method public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException { // Try block to check for exceptions try { // File Path String filePath = \"D:\\\\gfg_file.xml\"; // Creating FileWriter object Writer fileWriter = new FileWriter(filePath); // Getting the XMLOutputFactory instance XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); // Creating XMLStreamWriter object from // xmlOutputFactory. XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter( fileWriter); // Addoing elements to xmlStreamWriter // Custom input element addition xmlStreamWriter.writeStartElement(\"gfg\"); xmlStreamWriter.writeAttribute(\"id\", \"10\"); xmlStreamWriter.writeCharacters(\"hello world!\"); xmlStreamWriter.writeCData(\"more text data\"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEmptyElement(\"used & new\"); xmlStreamWriter.writeComment(\"Thank you!\"); xmlStreamWriter.writeEndDocument(); // Writing the content on XML file and // close xmlStreamWriter using close() method xmlStreamWriter.flush(); xmlStreamWriter.close(); // Display message for successful execution of // program System.out.println( \"XML file created successfully.\"); } // Catch block to handle exceptions catch (Exception e) { // Print the line number where exception occurs e.printStackTrace(); } }}", "e": 5260, "s": 3031, "text": null }, { "code": null, "e": 5268, "s": 5260, "text": "Output:" }, { "code": null, "e": 5360, "s": 5268, "text": "<gfg id=\"10\">hello world!\n<![CDATA[more text data]]>\n</gfg>\n<used & new/>\n<!--Thank you!-->" }, { "code": null, "e": 5373, "s": 5360, "text": "Conclusion: " }, { "code": null, "e": 5659, "s": 5373, "text": "Streaming API for XML provides a very convenient, fast, and memory-efficient way to write XML documents without worrying about details and escaping special characters. It is a great alternative to DOM especially when you don’t need to keep and manage DOM tree in memory for any reason." }, { "code": null, "e": 5666, "s": 5659, "text": "Picked" }, { "code": null, "e": 5671, "s": 5666, "text": "Java" }, { "code": null, "e": 5676, "s": 5671, "text": "Java" }, { "code": null, "e": 5774, "s": 5676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5789, "s": 5774, "text": "Stream In Java" }, { "code": null, "e": 5810, "s": 5789, "text": "Introduction to Java" }, { "code": null, "e": 5831, "s": 5810, "text": "Constructors in Java" }, { "code": null, "e": 5850, "s": 5831, "text": "Exceptions in Java" }, { "code": null, "e": 5867, "s": 5850, "text": "Generics in Java" }, { "code": null, "e": 5897, "s": 5867, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5923, "s": 5897, "text": "Java Programming Examples" }, { "code": null, "e": 5939, "s": 5923, "text": "Strings in Java" }, { "code": null, "e": 5976, "s": 5939, "text": "Differences between JDK, JRE and JVM" } ]
Swing Examples - Show a Modal Dialog
Following example showcase how to create a modal dialog in swing based application. We are using the following APIs. JDialog − To create a standard dialog box. JDialog − To create a standard dialog box. JDialog.getContentPane() − To get the content panel of the dialog box. JDialog.getContentPane() − To get the content panel of the dialog box. Dialog.ModalityType.DOCUMENT_MODAL − To show a dialog box as a modal dialog box. Dialog.ModalityType.DOCUMENT_MODAL − To show a dialog box as a modal dialog box. import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JButton button = new JButton("Click Me!"); final JDialog modelDialog = createDialog(frame); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { modelDialog.setVisible(true); } }); panel.add(button); frame.getContentPane().add(panel, BorderLayout.CENTER); } private static JDialog createDialog(final JFrame frame){ final JDialog modelDialog = new JDialog(frame, "Swing Tester", Dialog.ModalityType.DOCUMENT_MODAL); modelDialog.setBounds(132, 132, 300, 200); Container dialogContainer = modelDialog.getContentPane(); dialogContainer.setLayout(new BorderLayout()); dialogContainer.add(new JLabel(" Welcome to Swing!") , BorderLayout.CENTER); JPanel panel1 = new JPanel(); panel1.setLayout(new FlowLayout()); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {
[ { "code": null, "e": 2257, "s": 2173, "text": "Following example showcase how to create a modal dialog in swing based application." }, { "code": null, "e": 2290, "s": 2257, "text": "We are using the following APIs." }, { "code": null, "e": 2333, "s": 2290, "text": "JDialog − To create a standard dialog box." }, { "code": null, "e": 2376, "s": 2333, "text": "JDialog − To create a standard dialog box." }, { "code": null, "e": 2447, "s": 2376, "text": "JDialog.getContentPane() − To get the content panel of the dialog box." }, { "code": null, "e": 2518, "s": 2447, "text": "JDialog.getContentPane() − To get the content panel of the dialog box." }, { "code": null, "e": 2599, "s": 2518, "text": "Dialog.ModalityType.DOCUMENT_MODAL − To show a dialog box as a modal dialog box." }, { "code": null, "e": 2680, "s": 2599, "text": "Dialog.ModalityType.DOCUMENT_MODAL − To show a dialog box as a modal dialog box." } ]
Check if a string has m consecutive 1’s or 0’s
27 May, 2021 Given a binary string and a number m, the task is to check if the string has m consecutive 1’s or 0’s. Examples: Input : str = “001001”, m = 2 Output : YES Input : str = “1000000001”, m = 10 Output : NO The approach is to count the consecutive 1’s or 0’s by traversing the binary string. While traversing the binary string, keep a count of the number of 1’s or 0’s appearing consecutively. If there are M consecutive 1’s or 0’s, return True, else return False. Given below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // Program to check if the binary string// contains m consecutive 1's or 0's#include <bits/stdc++.h>#include <stdio.h>using namespace std; // Function that checks if// the binary string contains m// consecutive 1's or 0'sbool check(string s, int m){ // length of binary string int l = s.length(); // counts zeros int c1 = 0; // counts 1's int c2 = 0; for (int i = 0; i < l; i++) { if (s[i] == '0') { c2 = 0; // count consecutive 0's c1++; } else { c1 = 0; // count consecutive 1's c2++; } if (c1 == m || c2 == m) return true; } return false;} // Drivers Codeint main(){ string s = "001001"; int m = 2; // function call if (check(s, m)) cout << "YES"; else cout << "NO"; return 0;} // Program to check if the// binary string contains// m consecutive 1's or 0'simport java.io.*; class GFG{ // Function that checks if// the binary string contains m// consecutive 1's or 0'sstatic boolean check(String s, int m){ // length of binary string int l = s.length(); // counts zeros int c1 = 0; // counts 1's int c2 = 0; for (int i = 0; i < l; i++) { if (s.charAt(i) == '0') { c2 = 0; // count consecutive 0's c1++; } else { c1 = 0; // count consecutive 1's c2++; } if (c1 == m || c2 == m) return true; } return false;} // Drivers Code public static void main (String[] args){ String s = "001001"; int m = 2; // function call if (check(s, m)) System.out.println( "YES"); else System.out.println( "NO");}} // This code is contributed by anuj_67. # Program to check if the binary string# contains m consecutive 1's or 0's # Function that checks if# the binary string contains m# consecutive 1's or 0'sdef check(s, m): # length of binary string l = len(s); # counts zeros c1 = 0; # counts 1's c2 = 0; for i in range(0, l - 1): if (s[i] == '0'): c2 = 0; # count consecutive 0's c1 = c1 + 1; else : c1 = 0; # count consecutive 1's c2 = c2 + 1; if (c1 == m or c2 == m): return True; return False; # Driver Codes = "001001";m = 2; # function callif (check(s, m)): print("YES");else : print("NO"); # This code is contributed# by Shivi_Agggarwal // Program to check if the// binary string contains// m consecutive 1's or 0'susing System; class GFG{ // Function that checks if// the binary string contains// m consecutive 1's or 0'sstatic bool check(string s, int m){ // length of // binary string int l = s.Length; // counts zeros int c1 = 0; // counts 1's int c2 = 0; for (int i = 0; i < l; i++) { if (s[i] == '0') { c2 = 0; // count consecutive // 0's c1++; } else { c1 = 0; // count consecutive // 1's c2++; } if (c1 == m || c2 == m) return true; } return false;} // Driver Codepublic static void Main (){ String s = "001001"; int m = 2; // function call if (check(s, m)) Console.WriteLine( "YES"); else Console.WriteLine( "NO");}} // This code is contributed// by anuj_67. <?php// Program to check if the// binary string contains m// consecutive 1's or 0's // Function that checks if// the binary string contains// m consecutive 1's or 0'sfunction check($s, $m){ // length of binary // string $l = count($s); // counts zeros $c1 = 0; // counts 1's $c2 = 0; for ($i = 0; $i <= $l; $i++) { if ($s[$i] == '0') { $c2 = 0; // count consecutive // 0's $c1++; } else { $c1 = 0; // count consecutive 1's $c2++; } if ($c1 == $m or $c2 == $m) return true; } return false;} // Driver Code$s = "001001";$m = 2; // function callif (check($s, $m)) echo "YES";else echo "NO"; // This code is contributed// by anuj_67.?> <script> // Program to check if the // binary string contains // m consecutive 1's or 0's // Function that checks if // the binary string contains // m consecutive 1's or 0's function check(s, m) { // length of // binary string let l = s.length; // counts zeros let c1 = 0; // counts 1's let c2 = 0; for (let i = 0; i < l; i++) { if (s[i] == '0') { c2 = 0; // count consecutive // 0's c1++; } else { c1 = 0; // count consecutive // 1's c2++; } if (c1 == m || c2 == m) return true; } return false; } let s = "001001"; let m = 2; // function call if (check(s, m)) document.write( "YES"); else document.write( "NO"); </script> YES Time Complexity: O(N), where N is the length of the binary string. vt_m Shivi_Aggarwal suresh07 binary-string C++ Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Program to implement Singly Linked List in C++ using class Different ways to print elements of vector Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 53, "s": 25, "text": "\n27 May, 2021" }, { "code": null, "e": 156, "s": 53, "text": "Given a binary string and a number m, the task is to check if the string has m consecutive 1’s or 0’s." }, { "code": null, "e": 167, "s": 156, "text": "Examples: " }, { "code": null, "e": 210, "s": 167, "text": "Input : str = “001001”, m = 2 Output : YES" }, { "code": null, "e": 258, "s": 210, "text": "Input : str = “1000000001”, m = 10 Output : NO " }, { "code": null, "e": 516, "s": 258, "text": "The approach is to count the consecutive 1’s or 0’s by traversing the binary string. While traversing the binary string, keep a count of the number of 1’s or 0’s appearing consecutively. If there are M consecutive 1’s or 0’s, return True, else return False." }, { "code": null, "e": 574, "s": 516, "text": "Given below is the implementation of the above approach: " }, { "code": null, "e": 578, "s": 574, "text": "C++" }, { "code": null, "e": 583, "s": 578, "text": "Java" }, { "code": null, "e": 592, "s": 583, "text": "Python 3" }, { "code": null, "e": 595, "s": 592, "text": "C#" }, { "code": null, "e": 599, "s": 595, "text": "PHP" }, { "code": null, "e": 610, "s": 599, "text": "Javascript" }, { "code": "// Program to check if the binary string// contains m consecutive 1's or 0's#include <bits/stdc++.h>#include <stdio.h>using namespace std; // Function that checks if// the binary string contains m// consecutive 1's or 0'sbool check(string s, int m){ // length of binary string int l = s.length(); // counts zeros int c1 = 0; // counts 1's int c2 = 0; for (int i = 0; i < l; i++) { if (s[i] == '0') { c2 = 0; // count consecutive 0's c1++; } else { c1 = 0; // count consecutive 1's c2++; } if (c1 == m || c2 == m) return true; } return false;} // Drivers Codeint main(){ string s = \"001001\"; int m = 2; // function call if (check(s, m)) cout << \"YES\"; else cout << \"NO\"; return 0;}", "e": 1480, "s": 610, "text": null }, { "code": "// Program to check if the// binary string contains// m consecutive 1's or 0'simport java.io.*; class GFG{ // Function that checks if// the binary string contains m// consecutive 1's or 0'sstatic boolean check(String s, int m){ // length of binary string int l = s.length(); // counts zeros int c1 = 0; // counts 1's int c2 = 0; for (int i = 0; i < l; i++) { if (s.charAt(i) == '0') { c2 = 0; // count consecutive 0's c1++; } else { c1 = 0; // count consecutive 1's c2++; } if (c1 == m || c2 == m) return true; } return false;} // Drivers Code public static void main (String[] args){ String s = \"001001\"; int m = 2; // function call if (check(s, m)) System.out.println( \"YES\"); else System.out.println( \"NO\");}} // This code is contributed by anuj_67.", "e": 2457, "s": 1480, "text": null }, { "code": "# Program to check if the binary string# contains m consecutive 1's or 0's # Function that checks if# the binary string contains m# consecutive 1's or 0'sdef check(s, m): # length of binary string l = len(s); # counts zeros c1 = 0; # counts 1's c2 = 0; for i in range(0, l - 1): if (s[i] == '0'): c2 = 0; # count consecutive 0's c1 = c1 + 1; else : c1 = 0; # count consecutive 1's c2 = c2 + 1; if (c1 == m or c2 == m): return True; return False; # Driver Codes = \"001001\";m = 2; # function callif (check(s, m)): print(\"YES\");else : print(\"NO\"); # This code is contributed# by Shivi_Agggarwal", "e": 3215, "s": 2457, "text": null }, { "code": "// Program to check if the// binary string contains// m consecutive 1's or 0'susing System; class GFG{ // Function that checks if// the binary string contains// m consecutive 1's or 0'sstatic bool check(string s, int m){ // length of // binary string int l = s.Length; // counts zeros int c1 = 0; // counts 1's int c2 = 0; for (int i = 0; i < l; i++) { if (s[i] == '0') { c2 = 0; // count consecutive // 0's c1++; } else { c1 = 0; // count consecutive // 1's c2++; } if (c1 == m || c2 == m) return true; } return false;} // Driver Codepublic static void Main (){ String s = \"001001\"; int m = 2; // function call if (check(s, m)) Console.WriteLine( \"YES\"); else Console.WriteLine( \"NO\");}} // This code is contributed// by anuj_67.", "e": 4196, "s": 3215, "text": null }, { "code": "<?php// Program to check if the// binary string contains m// consecutive 1's or 0's // Function that checks if// the binary string contains// m consecutive 1's or 0'sfunction check($s, $m){ // length of binary // string $l = count($s); // counts zeros $c1 = 0; // counts 1's $c2 = 0; for ($i = 0; $i <= $l; $i++) { if ($s[$i] == '0') { $c2 = 0; // count consecutive // 0's $c1++; } else { $c1 = 0; // count consecutive 1's $c2++; } if ($c1 == $m or $c2 == $m) return true; } return false;} // Driver Code$s = \"001001\";$m = 2; // function callif (check($s, $m)) echo \"YES\";else echo \"NO\"; // This code is contributed// by anuj_67.?>", "e": 5033, "s": 4196, "text": null }, { "code": "<script> // Program to check if the // binary string contains // m consecutive 1's or 0's // Function that checks if // the binary string contains // m consecutive 1's or 0's function check(s, m) { // length of // binary string let l = s.length; // counts zeros let c1 = 0; // counts 1's let c2 = 0; for (let i = 0; i < l; i++) { if (s[i] == '0') { c2 = 0; // count consecutive // 0's c1++; } else { c1 = 0; // count consecutive // 1's c2++; } if (c1 == m || c2 == m) return true; } return false; } let s = \"001001\"; let m = 2; // function call if (check(s, m)) document.write( \"YES\"); else document.write( \"NO\"); </script>", "e": 6029, "s": 5033, "text": null }, { "code": null, "e": 6033, "s": 6029, "text": "YES" }, { "code": null, "e": 6104, "s": 6035, "text": "Time Complexity: O(N), where N is the length of the binary string. " }, { "code": null, "e": 6109, "s": 6104, "text": "vt_m" }, { "code": null, "e": 6124, "s": 6109, "text": "Shivi_Aggarwal" }, { "code": null, "e": 6133, "s": 6124, "text": "suresh07" }, { "code": null, "e": 6147, "s": 6133, "text": "binary-string" }, { "code": null, "e": 6160, "s": 6147, "text": "C++ Programs" }, { "code": null, "e": 6168, "s": 6160, "text": "Strings" }, { "code": null, "e": 6176, "s": 6168, "text": "Strings" }, { "code": null, "e": 6274, "s": 6176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6315, "s": 6274, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 6336, "s": 6315, "text": "Const keyword in C++" }, { "code": null, "e": 6348, "s": 6336, "text": "cout in C++" }, { "code": null, "e": 6407, "s": 6348, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 6450, "s": 6407, "text": "Different ways to print elements of vector" }, { "code": null, "e": 6496, "s": 6450, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6521, "s": 6496, "text": "Reverse a string in Java" }, { "code": null, "e": 6581, "s": 6521, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6596, "s": 6581, "text": "C++ Data Types" } ]
Construct Binary Tree from String with bracket representation
04 May, 2022 Construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root’s value and a pair of parenthesis contains a child binary tree with the same structure. Always start to construct the left child node of the parent first if it exists. Examples: Input : "1(2)(3)" Output : 1 2 3 Explanation : 1 / \ 2 3 Explanation: first pair of parenthesis contains left subtree and second one contains the right subtree. Preorder of above tree is "1 2 3". Input : "4(2(3)(1))(6(5))" Output : 4 2 3 1 6 5 Explanation : 4 / \ 2 6 / \ / 3 1 5 We know first character in string is root. Substring inside the first adjacent pair of parenthesis is for left subtree and substring inside second pair of parenthesis is for right subtree as in the below diagram. We need to find the substring corresponding to left subtree and substring corresponding to right subtree and then recursively call on both of the substrings. For this first find the index of starting index and end index of each substring. To find the index of closing parenthesis of left subtree substring, use a stack. Let the found index be stored in index variable. C++ Java Python C# Javascript /* C++ program to construct a binary tree from the given string */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; Node *left, *right;};/* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} /* This function is here just to test */void preOrder(Node* node){ if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right);} // function to return the index of close parenthesisint findIndex(string str, int si, int ei){ if (si > ei) return -1; // Inbuilt stack stack<char> s; for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.top() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.empty()) return i; } } } // if not found return -1 return -1;} // function to construct tree from stringNode* treeFromString(string str, int si, int ei){ // Base case if (si > ei) return NULL; // new root Node* root = newNode(str[si] - '0'); int index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str[si + 1] == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root->left = treeFromString(str, si + 2, index - 1); // call for right subtree root->right = treeFromString(str, index + 2, ei - 1); } return root;} // Driver Codeint main(){ string str = "4(2(3)(1))(6(5))"; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root);} /* Java program to construct a binary tree from the given String */import java.util.*;class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; }; /* Helper function that allocates a new node */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /* This function is here just to test */ static void preOrder(Node node) { if (node == null) return; System.out.printf("%d ", node.data); preOrder(node.left); preOrder(node.right); } // function to return the index of close parenthesis static int findIndex(String str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack Stack<Character> s = new Stack<>(); for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str.charAt(i) == '(') s.add(str.charAt(i)); // if close parenthesis else if (str.charAt(i) == ')') { if (s.peek() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.isEmpty()) return i; } } } // if not found return -1 return -1; } // function to construct tree from String static Node treeFromString(String str, int si, int ei) { // Base case if (si > ei) return null; // new root Node root = newNode(str.charAt(si) - '0'); int index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str.charAt(si+1) == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root.left = treeFromString(str, si + 2, index - 1); // call for right subtree root.right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code public static void main(String[] args) { String str = "4(2(3)(1))(6(5))"; Node root = treeFromString(str, 0, str.length() - 1); preOrder(root); }} // This code is contributed by gauravrajput1 # Python3 program to conStruct a# binary tree from the given String # Helper class that allocates a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # This function is here just to test def preOrder(node): if (node == None): return print(node.data, end=" ") preOrder(node.left) preOrder(node.right) # function to return the index of# close parenthesis def findIndex(Str, si, ei): if (si > ei): return -1 # Inbuilt stack s = [] for i in range(si, ei + 1): # if open parenthesis, push it if (Str[i] == '('): s.append(Str[i]) # if close parenthesis elif (Str[i] == ')'): if (s[-1] == '('): s.pop(-1) # if stack is empty, this is # the required index if len(s) == 0: return i # if not found return -1 return -1 # function to conStruct tree from String def treeFromString(Str, si, ei): # Base case if (si > ei): return None # new root root = newNode(ord(Str[si]) - ord('0')) index = -1 # if next char is '(' find the # index of its complement ')' if (si + 1 <= ei and Str[si + 1] == '('): index = findIndex(Str, si + 1, ei) # if index found if (index != -1): # call for left subtree root.left = treeFromString(Str, si + 2, index - 1) # call for right subtree root.right = treeFromString(Str, index + 2, ei - 1) return root # Driver Codeif __name__ == '__main__': Str = "4(2(3)(1))(6(5))" root = treeFromString(Str, 0, len(Str) - 1) preOrder(root) # This code is contributed by pranchalK /* C# program to construct a binary tree from the given String */using System;using System.Collections.Generic; public class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; }; /* Helper function that allocates a new node */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /* This function is here just to test */ static void preOrder(Node node) { if (node == null) return; Console.Write("{0} ", node.data); preOrder(node.left); preOrder(node.right); } // function to return the index of close parenthesis static int findIndex(String str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack Stack<char> s = new Stack<char>(); for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.Push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.Peek() == '(') { s.Pop(); // if stack is empty, this is // the required index if (s.Count==0) return i; } } } // if not found return -1 return -1; } // function to construct tree from String static Node treeFromString(String str, int si, int ei) { // Base case if (si > ei) return null; // new root Node root = newNode(str[si] - '0'); int index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str[si+1] == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root.left = treeFromString(str, si + 2, index - 1); // call for right subtree root.right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code public static void Main(String[] args) { String str = "4(2(3)(1))(6(5))"; Node root = treeFromString(str, 0, str.Length - 1); preOrder(root); }} // This code is contributed by gauravrajput1 <script>/* Javascript program to construct a binary tree from the given String */ /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ constructor() { this.data = 0; this.left = this.right = null; }} /* Helper function that allocates a new node */function newNode(data){ let node = new Node(); node.data = data; node.left = node.right = null; return (node);} /* This function is here just to test */function preOrder(node){ if (node == null) return; document.write(node.data + " "); preOrder(node.left); preOrder(node.right);} // function to return the index of close parenthesisfunction findIndex(str, si, ei){ if (si > ei) return -1; // Inbuilt stack let s = []; for (let i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s[s.length-1] == '(') { s.pop(); // if stack is empty, this is // the required index if (s.length == 0) return i; } } } // if not found return -1 return -1;} // function to construct tree from Stringfunction treeFromString(str,si,ei){ // Base case if (si > ei) return null; // new root let root = newNode(str[si].charCodeAt(0) - '0'.charCodeAt(0)); let index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str[si + 1] == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root.left = treeFromString(str, si + 2, index - 1); // call for right subtree root.right = treeFromString(str, index + 2, ei - 1); } return root;} // Driver Codelet str = "4(2(3)(1))(6(5))";let root = treeFromString(str, 0, str.length - 1);preOrder(root); // This code is contributed by patel2127</script> 4 2 3 1 6 5 Time Complexity: O(N2)Auxiliary Space: O(N) Another recursive approach: Algorithm: The very first element of the string is the root.If the next two consecutive elements are “(” and “)”, this means there is no left child otherwise we will create and add the left child to the parent node recursively.Once the left child is added recursively, we will look for consecutive “(” and add the right child to the parent node.Encountering “)” means the end of either left or right node and we will increment the start indexThe recursion ends when the start index is greater than equal to the end index The very first element of the string is the root. If the next two consecutive elements are “(” and “)”, this means there is no left child otherwise we will create and add the left child to the parent node recursively. Once the left child is added recursively, we will look for consecutive “(” and add the right child to the parent node. Encountering “)” means the end of either left or right node and we will increment the start index The recursion ends when the start index is greater than equal to the end index C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // custom data type for tree buildingstruct Node { int data; struct Node* left; struct Node* right; Node(int val) { data = val; left = right = NULL; }}; // Below function accepts string and a pointer variable as// an argument// and draw the tree. Returns the root of the treeNode* constructtree(string s, int* start){ // Assuming there is/are no negative // character/characters in the string if (s.size() == 0 || *start >= s.size()) return NULL; // constructing a number from the continuous digits int num = 0; while (*start < s.size() && s[*start] != '(' && s[*start] != ')') { int num_here = (int)(s[*start] - '0'); num = num * 10 + num_here; *start = *start + 1; } // creating a node from the constructed number from // above loop struct Node* root = NULL; if(num > 0) root = new Node(num); // As soon as we see first right parenthesis from the // current node we start to construct the tree in the // left if (*start < s.size() && s[*start] == '(') { *start = *start + 1; root->left = constructtree(s, start); } if (*start < s.size() && s[*start] == ')') { *start = *start + 1; return root; } // As soon as we see second right parenthesis from the // current node we start to construct the tree in the // right if (*start < s.size() && s[*start] == '(') { *start = *start + 1; root->right = constructtree(s, start); } if (*start < s.size() && s[*start] == ')') *start = *start + 1; return root;}void preorder(Node* root){ if (root == NULL) return; cout << root->data << " "; preorder(root->left); preorder(root->right);}int main(){ string s = "4(2(3)(1))(6(5))"; // cin>>s; int start = 0; Node* root = constructtree(s, &start); preorder(root); return 0;}//This code is contributed by Chaitanya Sharma. import java.io.*;import java.util.*; class GFG{ // Node class for the Treestatic class Node{ int data; Node left,right; Node(int data) { this.data = data; this.left = this.right = null; }} // static variable to point to the// starting index of the string.static int start = 0; // Construct Tree Function which accepts// a string and return root of the tree;static Node constructTree(String s){ // Check for null or empty string // and return null; if (s.length() == 0 || s == null) { return null; } if (start >= s.length()) return null; // Boolean variable to check // for negative numbers boolean neg = false; // Condition to check for negative number if (s.charAt(start) == '-') { neg = true; start++; } // This loop basically construct the // number from the continuous digits int num = 0; while (start < s.length() && Character.isDigit(s.charAt(start))) { int digit = Character.getNumericValue( s.charAt(start)); num = num * 10 + digit; start++; } // If string contains - minus sign // then append - to the number; if (neg) num = -num; // Create the node object i.e. root of // the tree with data = num; Node node = new Node(num); if (start >= s.length()) { return node; } // Check for open bracket and add the // data to the left subtree recursively if (start < s.length() && s.charAt(start) == '(' ) { start++; node.left = constructTree(s); } if (start < s.length() && s.charAt(start) == ')') { start++; return node; } // Check for open bracket and add the data // to the right subtree recursively if (start < s.length() && s.charAt(start) == '(') { start++; node.right = constructTree(s); } if (start < s.length() && s.charAt(start) == ')') { start++; return node; } return node;} // Print tree functionpublic static void printTree(Node node){ if (node == null) return; System.out.println(node.data + " "); printTree(node.left); printTree(node.right);} // Driver Codepublic static void main(String[] args){ // Input String s = "4(2(3)(1))(6(5))"; // Call the function construct tree // to create the tree pass the string; Node root = constructTree(s); // Function to print preorder of the tree printTree(root);}} // This code is contributed by yash181999 class newNode: def __init__(self, data): self.data = data self.left = self.right = None def preOrder(node): if (node == None): return print(node.data, end=" ") preOrder(node.left) preOrder(node.right) def treeFromStringHelper(si, ei, arr, root): if si[0] >= ei: return None if arr[si[0]] == "(": if arr[si[0]+1] != ")": if root.left is None: if si[0] >= ei: return new_root = newNode(arr[si[0]+1]) root.left = new_root si[0] += 2 treeFromStringHelper(si, ei, arr, new_root) else: si[0] += 2 if root.right is None: if si[0] >= ei: return if arr[si[0]] != "(": si[0] += 1 return new_root = newNode(arr[si[0]+1]) root.right = new_root si[0] += 2 treeFromStringHelper(si, ei, arr, new_root) else: return if arr[si[0]] == ")": if si[0] >= ei: return si[0] += 1 return return def treeFromString(string): root = newNode(string[0]) if len(string) > 1: si = [1] ei = len(string)-1 treeFromStringHelper(si, ei, string, root) return root # Driver Codeif __name__ == '__main__': Str = "4(2(3)(1))(6(5))" root = treeFromString(Str) preOrder(root) # This code is contributed by dheerajalimchandani using System;class GFG { // Class containing left and // right child of current // node and key value class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } // static variable to point to the // starting index of the string. static int start = 0; // Construct Tree Function which accepts // a string and return root of the tree; static Node constructTree(string s) { // Check for null or empty string // and return null; if (s.Length == 0 || s == null) { return null; } if (start >= s.Length) return null; // Boolean variable to check // for negative numbers bool neg = false; // Condition to check for negative number if (s[start] == '-') { neg = true; start++; } // This loop basically construct the // number from the continuous digits int num = 0; while (start < s.Length && Char.IsDigit(s[start])) { int digit = (int)Char.GetNumericValue( s[start]); num = num * 10 + digit; start++; } // If string contains - minus sign // then append - to the number; if (neg) num = -num; // Create the node object i.e. root of // the tree with data = num; Node node = new Node(num); if (start >= s.Length) { return node; } // Check for open bracket and add the // data to the left subtree recursively if (start < s.Length && s[start] == '(' ) { start++; node.left = constructTree(s); } if (start < s.Length && s[start] == ')') { start++; return node; } // Check for open bracket and add the data // to the right subtree recursively if (start < s.Length && s[start] == '(') { start++; node.right = constructTree(s); } if (start < s.Length && s[start] == ')') { start++; return node; } return node; } // Print tree function static void printTree(Node node) { if (node == null) return; Console.Write(node.data + " "); printTree(node.left); printTree(node.right); } // Driver code static void Main() { // Input string s = "4(2(3)(1))(6(5))"; // Call the function construct tree // to create the tree pass the string; Node root = constructTree(s); // Function to print preorder of the tree printTree(root); }} // This code is contributed by decode2207. <script> // Node class for the Treeclass Node{ constructor(data) { this.data=data; this.left = this.right = null; }} // static variable to point to the// starting index of the string.let start = 0; // Construct Tree Function which accepts// a string and return root of the tree;function constructTree(s){ // Check for null or empty string // and return null; if (s.length == 0 || s == null) { return null; } if (start >= s.length) return null; // Boolean variable to check // for negative numbers let neg = false; // Condition to check for negative number if (s[start] == '-') { neg = true; start++; } // This loop basically construct the // number from the continuous digits let num = 0; while (start < s.length && !isNaN(s[start] - parseInt(s[start]))) { let digit = parseInt( s[start]); num = num * 10 + digit; start++; } // If string contains - minus sign // then append - to the number; if (neg) num = -num; // Create the node object i.e. root of // the tree with data = num; let node = new Node(num); if (start >= s.length) { return node; } // Check for open bracket and add the // data to the left subtree recursively if (start < s.length && s[start] == '(' ) { start++; node.left = constructTree(s); } if (start < s.length && s[start] == ')') { start++; return node; } // Check for open bracket and add the data // to the right subtree recursively if (start < s.length && s[start] == '(') { start++; node.right = constructTree(s); } if (start < s.length && s[start] == ')') { start++; return node; } return node;} // Print tree functionfunction printTree(node){ if (node == null) return; document.write(node.data + " "); printTree(node.left); printTree(node.right);} // Driver Code// Inputlet s = "4(2(3)(1))(6(5))"; // Call the function construct tree// to create the tree pass the string;let root = constructTree(s); // Function to print preorder of the treeprintTree(root); // This code is contributed by unknown2108 </script> 4 2 3 1 6 5 This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PranchalKatiyar Akanksha_Rai ujjwalgoel1103 dheerajalimchandani reapedjuggler GauravRajput1 yash181999 Chaitanya_Sharma kumardevansh8 patel2127 unknown2108 ruhelaa48 surindertarika1234 decode2207 akshaysingh98088 gautamsaurabh200 simmytarika5 surinderdawra388 codej Stack Strings Tree Strings Stack Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Next Greater Element What is Data Structure: Types, Classifications and Applications Merge Overlapping Intervals Stack | Set 4 (Evaluation of Postfix Expression) Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n04 May, 2022" }, { "code": null, "e": 448, "s": 54, "text": "Construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root’s value and a pair of parenthesis contains a child binary tree with the same structure. Always start to construct the left child node of the parent first if it exists." }, { "code": null, "e": 459, "s": 448, "text": "Examples: " }, { "code": null, "e": 832, "s": 459, "text": "Input : \"1(2)(3)\" \nOutput : 1 2 3\nExplanation :\n 1\n / \\\n 2 3\nExplanation: first pair of parenthesis contains \nleft subtree and second one contains the right \nsubtree. Preorder of above tree is \"1 2 3\". \n\nInput : \"4(2(3)(1))(6(5))\"\nOutput : 4 2 3 1 6 5\nExplanation :\n 4\n / \\\n 2 6\n / \\ / \n 3 1 5 " }, { "code": null, "e": 1046, "s": 832, "text": "We know first character in string is root. Substring inside the first adjacent pair of parenthesis is for left subtree and substring inside second pair of parenthesis is for right subtree as in the below diagram. " }, { "code": null, "e": 1205, "s": 1046, "text": "We need to find the substring corresponding to left subtree and substring corresponding to right subtree and then recursively call on both of the substrings. " }, { "code": null, "e": 1417, "s": 1205, "text": "For this first find the index of starting index and end index of each substring. To find the index of closing parenthesis of left subtree substring, use a stack. Let the found index be stored in index variable. " }, { "code": null, "e": 1421, "s": 1417, "text": "C++" }, { "code": null, "e": 1426, "s": 1421, "text": "Java" }, { "code": null, "e": 1433, "s": 1426, "text": "Python" }, { "code": null, "e": 1436, "s": 1433, "text": "C#" }, { "code": null, "e": 1447, "s": 1436, "text": "Javascript" }, { "code": "/* C++ program to construct a binary tree from the given string */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; Node *left, *right;};/* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} /* This function is here just to test */void preOrder(Node* node){ if (node == NULL) return; printf(\"%d \", node->data); preOrder(node->left); preOrder(node->right);} // function to return the index of close parenthesisint findIndex(string str, int si, int ei){ if (si > ei) return -1; // Inbuilt stack stack<char> s; for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.top() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.empty()) return i; } } } // if not found return -1 return -1;} // function to construct tree from stringNode* treeFromString(string str, int si, int ei){ // Base case if (si > ei) return NULL; // new root Node* root = newNode(str[si] - '0'); int index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str[si + 1] == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root->left = treeFromString(str, si + 2, index - 1); // call for right subtree root->right = treeFromString(str, index + 2, ei - 1); } return root;} // Driver Codeint main(){ string str = \"4(2(3)(1))(6(5))\"; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root);}", "e": 3490, "s": 1447, "text": null }, { "code": "/* Java program to construct a binary tree from the given String */import java.util.*;class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; }; /* Helper function that allocates a new node */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /* This function is here just to test */ static void preOrder(Node node) { if (node == null) return; System.out.printf(\"%d \", node.data); preOrder(node.left); preOrder(node.right); } // function to return the index of close parenthesis static int findIndex(String str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack Stack<Character> s = new Stack<>(); for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str.charAt(i) == '(') s.add(str.charAt(i)); // if close parenthesis else if (str.charAt(i) == ')') { if (s.peek() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.isEmpty()) return i; } } } // if not found return -1 return -1; } // function to construct tree from String static Node treeFromString(String str, int si, int ei) { // Base case if (si > ei) return null; // new root Node root = newNode(str.charAt(si) - '0'); int index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str.charAt(si+1) == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root.left = treeFromString(str, si + 2, index - 1); // call for right subtree root.right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code public static void main(String[] args) { String str = \"4(2(3)(1))(6(5))\"; Node root = treeFromString(str, 0, str.length() - 1); preOrder(root); }} // This code is contributed by gauravrajput1", "e": 5654, "s": 3490, "text": null }, { "code": "# Python3 program to conStruct a# binary tree from the given String # Helper class that allocates a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # This function is here just to test def preOrder(node): if (node == None): return print(node.data, end=\" \") preOrder(node.left) preOrder(node.right) # function to return the index of# close parenthesis def findIndex(Str, si, ei): if (si > ei): return -1 # Inbuilt stack s = [] for i in range(si, ei + 1): # if open parenthesis, push it if (Str[i] == '('): s.append(Str[i]) # if close parenthesis elif (Str[i] == ')'): if (s[-1] == '('): s.pop(-1) # if stack is empty, this is # the required index if len(s) == 0: return i # if not found return -1 return -1 # function to conStruct tree from String def treeFromString(Str, si, ei): # Base case if (si > ei): return None # new root root = newNode(ord(Str[si]) - ord('0')) index = -1 # if next char is '(' find the # index of its complement ')' if (si + 1 <= ei and Str[si + 1] == '('): index = findIndex(Str, si + 1, ei) # if index found if (index != -1): # call for left subtree root.left = treeFromString(Str, si + 2, index - 1) # call for right subtree root.right = treeFromString(Str, index + 2, ei - 1) return root # Driver Codeif __name__ == '__main__': Str = \"4(2(3)(1))(6(5))\" root = treeFromString(Str, 0, len(Str) - 1) preOrder(root) # This code is contributed by pranchalK", "e": 7442, "s": 5654, "text": null }, { "code": "/* C# program to construct a binary tree from the given String */using System;using System.Collections.Generic; public class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; }; /* Helper function that allocates a new node */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /* This function is here just to test */ static void preOrder(Node node) { if (node == null) return; Console.Write(\"{0} \", node.data); preOrder(node.left); preOrder(node.right); } // function to return the index of close parenthesis static int findIndex(String str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack Stack<char> s = new Stack<char>(); for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.Push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.Peek() == '(') { s.Pop(); // if stack is empty, this is // the required index if (s.Count==0) return i; } } } // if not found return -1 return -1; } // function to construct tree from String static Node treeFromString(String str, int si, int ei) { // Base case if (si > ei) return null; // new root Node root = newNode(str[si] - '0'); int index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str[si+1] == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root.left = treeFromString(str, si + 2, index - 1); // call for right subtree root.right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code public static void Main(String[] args) { String str = \"4(2(3)(1))(6(5))\"; Node root = treeFromString(str, 0, str.Length - 1); preOrder(root); }} // This code is contributed by gauravrajput1", "e": 9615, "s": 7442, "text": null }, { "code": "<script>/* Javascript program to construct a binary tree from the given String */ /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ constructor() { this.data = 0; this.left = this.right = null; }} /* Helper function that allocates a new node */function newNode(data){ let node = new Node(); node.data = data; node.left = node.right = null; return (node);} /* This function is here just to test */function preOrder(node){ if (node == null) return; document.write(node.data + \" \"); preOrder(node.left); preOrder(node.right);} // function to return the index of close parenthesisfunction findIndex(str, si, ei){ if (si > ei) return -1; // Inbuilt stack let s = []; for (let i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s[s.length-1] == '(') { s.pop(); // if stack is empty, this is // the required index if (s.length == 0) return i; } } } // if not found return -1 return -1;} // function to construct tree from Stringfunction treeFromString(str,si,ei){ // Base case if (si > ei) return null; // new root let root = newNode(str[si].charCodeAt(0) - '0'.charCodeAt(0)); let index = -1; // if next char is '(' find the index of // its complement ')' if (si + 1 <= ei && str[si + 1] == '(') index = findIndex(str, si + 1, ei); // if index found if (index != -1) { // call for left subtree root.left = treeFromString(str, si + 2, index - 1); // call for right subtree root.right = treeFromString(str, index + 2, ei - 1); } return root;} // Driver Codelet str = \"4(2(3)(1))(6(5))\";let root = treeFromString(str, 0, str.length - 1);preOrder(root); // This code is contributed by patel2127</script>", "e": 11641, "s": 9615, "text": null }, { "code": null, "e": 11654, "s": 11641, "text": "4 2 3 1 6 5 " }, { "code": null, "e": 11698, "s": 11654, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 11726, "s": 11698, "text": "Another recursive approach:" }, { "code": null, "e": 11737, "s": 11726, "text": "Algorithm:" }, { "code": null, "e": 12247, "s": 11737, "text": "The very first element of the string is the root.If the next two consecutive elements are “(” and “)”, this means there is no left child otherwise we will create and add the left child to the parent node recursively.Once the left child is added recursively, we will look for consecutive “(” and add the right child to the parent node.Encountering “)” means the end of either left or right node and we will increment the start indexThe recursion ends when the start index is greater than equal to the end index" }, { "code": null, "e": 12297, "s": 12247, "text": "The very first element of the string is the root." }, { "code": null, "e": 12465, "s": 12297, "text": "If the next two consecutive elements are “(” and “)”, this means there is no left child otherwise we will create and add the left child to the parent node recursively." }, { "code": null, "e": 12584, "s": 12465, "text": "Once the left child is added recursively, we will look for consecutive “(” and add the right child to the parent node." }, { "code": null, "e": 12682, "s": 12584, "text": "Encountering “)” means the end of either left or right node and we will increment the start index" }, { "code": null, "e": 12761, "s": 12682, "text": "The recursion ends when the start index is greater than equal to the end index" }, { "code": null, "e": 12765, "s": 12761, "text": "C++" }, { "code": null, "e": 12770, "s": 12765, "text": "Java" }, { "code": null, "e": 12778, "s": 12770, "text": "Python3" }, { "code": null, "e": 12781, "s": 12778, "text": "C#" }, { "code": null, "e": 12792, "s": 12781, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // custom data type for tree buildingstruct Node { int data; struct Node* left; struct Node* right; Node(int val) { data = val; left = right = NULL; }}; // Below function accepts string and a pointer variable as// an argument// and draw the tree. Returns the root of the treeNode* constructtree(string s, int* start){ // Assuming there is/are no negative // character/characters in the string if (s.size() == 0 || *start >= s.size()) return NULL; // constructing a number from the continuous digits int num = 0; while (*start < s.size() && s[*start] != '(' && s[*start] != ')') { int num_here = (int)(s[*start] - '0'); num = num * 10 + num_here; *start = *start + 1; } // creating a node from the constructed number from // above loop struct Node* root = NULL; if(num > 0) root = new Node(num); // As soon as we see first right parenthesis from the // current node we start to construct the tree in the // left if (*start < s.size() && s[*start] == '(') { *start = *start + 1; root->left = constructtree(s, start); } if (*start < s.size() && s[*start] == ')') { *start = *start + 1; return root; } // As soon as we see second right parenthesis from the // current node we start to construct the tree in the // right if (*start < s.size() && s[*start] == '(') { *start = *start + 1; root->right = constructtree(s, start); } if (*start < s.size() && s[*start] == ')') *start = *start + 1; return root;}void preorder(Node* root){ if (root == NULL) return; cout << root->data << \" \"; preorder(root->left); preorder(root->right);}int main(){ string s = \"4(2(3)(1))(6(5))\"; // cin>>s; int start = 0; Node* root = constructtree(s, &start); preorder(root); return 0;}//This code is contributed by Chaitanya Sharma.", "e": 14785, "s": 12792, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG{ // Node class for the Treestatic class Node{ int data; Node left,right; Node(int data) { this.data = data; this.left = this.right = null; }} // static variable to point to the// starting index of the string.static int start = 0; // Construct Tree Function which accepts// a string and return root of the tree;static Node constructTree(String s){ // Check for null or empty string // and return null; if (s.length() == 0 || s == null) { return null; } if (start >= s.length()) return null; // Boolean variable to check // for negative numbers boolean neg = false; // Condition to check for negative number if (s.charAt(start) == '-') { neg = true; start++; } // This loop basically construct the // number from the continuous digits int num = 0; while (start < s.length() && Character.isDigit(s.charAt(start))) { int digit = Character.getNumericValue( s.charAt(start)); num = num * 10 + digit; start++; } // If string contains - minus sign // then append - to the number; if (neg) num = -num; // Create the node object i.e. root of // the tree with data = num; Node node = new Node(num); if (start >= s.length()) { return node; } // Check for open bracket and add the // data to the left subtree recursively if (start < s.length() && s.charAt(start) == '(' ) { start++; node.left = constructTree(s); } if (start < s.length() && s.charAt(start) == ')') { start++; return node; } // Check for open bracket and add the data // to the right subtree recursively if (start < s.length() && s.charAt(start) == '(') { start++; node.right = constructTree(s); } if (start < s.length() && s.charAt(start) == ')') { start++; return node; } return node;} // Print tree functionpublic static void printTree(Node node){ if (node == null) return; System.out.println(node.data + \" \"); printTree(node.left); printTree(node.right);} // Driver Codepublic static void main(String[] args){ // Input String s = \"4(2(3)(1))(6(5))\"; // Call the function construct tree // to create the tree pass the string; Node root = constructTree(s); // Function to print preorder of the tree printTree(root);}} // This code is contributed by yash181999", "e": 17374, "s": 14785, "text": null }, { "code": "class newNode: def __init__(self, data): self.data = data self.left = self.right = None def preOrder(node): if (node == None): return print(node.data, end=\" \") preOrder(node.left) preOrder(node.right) def treeFromStringHelper(si, ei, arr, root): if si[0] >= ei: return None if arr[si[0]] == \"(\": if arr[si[0]+1] != \")\": if root.left is None: if si[0] >= ei: return new_root = newNode(arr[si[0]+1]) root.left = new_root si[0] += 2 treeFromStringHelper(si, ei, arr, new_root) else: si[0] += 2 if root.right is None: if si[0] >= ei: return if arr[si[0]] != \"(\": si[0] += 1 return new_root = newNode(arr[si[0]+1]) root.right = new_root si[0] += 2 treeFromStringHelper(si, ei, arr, new_root) else: return if arr[si[0]] == \")\": if si[0] >= ei: return si[0] += 1 return return def treeFromString(string): root = newNode(string[0]) if len(string) > 1: si = [1] ei = len(string)-1 treeFromStringHelper(si, ei, string, root) return root # Driver Codeif __name__ == '__main__': Str = \"4(2(3)(1))(6(5))\" root = treeFromString(Str) preOrder(root) # This code is contributed by dheerajalimchandani", "e": 18866, "s": 17374, "text": null }, { "code": "using System;class GFG { // Class containing left and // right child of current // node and key value class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } // static variable to point to the // starting index of the string. static int start = 0; // Construct Tree Function which accepts // a string and return root of the tree; static Node constructTree(string s) { // Check for null or empty string // and return null; if (s.Length == 0 || s == null) { return null; } if (start >= s.Length) return null; // Boolean variable to check // for negative numbers bool neg = false; // Condition to check for negative number if (s[start] == '-') { neg = true; start++; } // This loop basically construct the // number from the continuous digits int num = 0; while (start < s.Length && Char.IsDigit(s[start])) { int digit = (int)Char.GetNumericValue( s[start]); num = num * 10 + digit; start++; } // If string contains - minus sign // then append - to the number; if (neg) num = -num; // Create the node object i.e. root of // the tree with data = num; Node node = new Node(num); if (start >= s.Length) { return node; } // Check for open bracket and add the // data to the left subtree recursively if (start < s.Length && s[start] == '(' ) { start++; node.left = constructTree(s); } if (start < s.Length && s[start] == ')') { start++; return node; } // Check for open bracket and add the data // to the right subtree recursively if (start < s.Length && s[start] == '(') { start++; node.right = constructTree(s); } if (start < s.Length && s[start] == ')') { start++; return node; } return node; } // Print tree function static void printTree(Node node) { if (node == null) return; Console.Write(node.data + \" \"); printTree(node.left); printTree(node.right); } // Driver code static void Main() { // Input string s = \"4(2(3)(1))(6(5))\"; // Call the function construct tree // to create the tree pass the string; Node root = constructTree(s); // Function to print preorder of the tree printTree(root); }} // This code is contributed by decode2207.", "e": 21858, "s": 18866, "text": null }, { "code": "<script> // Node class for the Treeclass Node{ constructor(data) { this.data=data; this.left = this.right = null; }} // static variable to point to the// starting index of the string.let start = 0; // Construct Tree Function which accepts// a string and return root of the tree;function constructTree(s){ // Check for null or empty string // and return null; if (s.length == 0 || s == null) { return null; } if (start >= s.length) return null; // Boolean variable to check // for negative numbers let neg = false; // Condition to check for negative number if (s[start] == '-') { neg = true; start++; } // This loop basically construct the // number from the continuous digits let num = 0; while (start < s.length && !isNaN(s[start] - parseInt(s[start]))) { let digit = parseInt( s[start]); num = num * 10 + digit; start++; } // If string contains - minus sign // then append - to the number; if (neg) num = -num; // Create the node object i.e. root of // the tree with data = num; let node = new Node(num); if (start >= s.length) { return node; } // Check for open bracket and add the // data to the left subtree recursively if (start < s.length && s[start] == '(' ) { start++; node.left = constructTree(s); } if (start < s.length && s[start] == ')') { start++; return node; } // Check for open bracket and add the data // to the right subtree recursively if (start < s.length && s[start] == '(') { start++; node.right = constructTree(s); } if (start < s.length && s[start] == ')') { start++; return node; } return node;} // Print tree functionfunction printTree(node){ if (node == null) return; document.write(node.data + \" \"); printTree(node.left); printTree(node.right);} // Driver Code// Inputlet s = \"4(2(3)(1))(6(5))\"; // Call the function construct tree// to create the tree pass the string;let root = constructTree(s); // Function to print preorder of the treeprintTree(root); // This code is contributed by unknown2108 </script>", "e": 24176, "s": 21858, "text": null }, { "code": null, "e": 24189, "s": 24176, "text": "4 2 3 1 6 5 " }, { "code": null, "e": 24608, "s": 24189, "text": "This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 24624, "s": 24608, "text": "PranchalKatiyar" }, { "code": null, "e": 24637, "s": 24624, "text": "Akanksha_Rai" }, { "code": null, "e": 24652, "s": 24637, "text": "ujjwalgoel1103" }, { "code": null, "e": 24672, "s": 24652, "text": "dheerajalimchandani" }, { "code": null, "e": 24686, "s": 24672, "text": "reapedjuggler" }, { "code": null, "e": 24700, "s": 24686, "text": "GauravRajput1" }, { "code": null, "e": 24711, "s": 24700, "text": "yash181999" }, { "code": null, "e": 24728, "s": 24711, "text": "Chaitanya_Sharma" }, { "code": null, "e": 24742, "s": 24728, "text": "kumardevansh8" }, { "code": null, "e": 24752, "s": 24742, "text": "patel2127" }, { "code": null, "e": 24764, "s": 24752, "text": "unknown2108" }, { "code": null, "e": 24774, "s": 24764, "text": "ruhelaa48" }, { "code": null, "e": 24793, "s": 24774, "text": "surindertarika1234" }, { "code": null, "e": 24804, "s": 24793, "text": "decode2207" }, { "code": null, "e": 24821, "s": 24804, "text": "akshaysingh98088" }, { "code": null, "e": 24838, "s": 24821, "text": "gautamsaurabh200" }, { "code": null, "e": 24851, "s": 24838, "text": "simmytarika5" }, { "code": null, "e": 24868, "s": 24851, "text": "surinderdawra388" }, { "code": null, "e": 24874, "s": 24868, "text": "codej" }, { "code": null, "e": 24880, "s": 24874, "text": "Stack" }, { "code": null, "e": 24888, "s": 24880, "text": "Strings" }, { "code": null, "e": 24893, "s": 24888, "text": "Tree" }, { "code": null, "e": 24901, "s": 24893, "text": "Strings" }, { "code": null, "e": 24907, "s": 24901, "text": "Stack" }, { "code": null, "e": 24912, "s": 24907, "text": "Tree" }, { "code": null, "e": 25010, "s": 24912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25042, "s": 25010, "text": "Introduction to Data Structures" }, { "code": null, "e": 25063, "s": 25042, "text": "Next Greater Element" }, { "code": null, "e": 25127, "s": 25063, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 25155, "s": 25127, "text": "Merge Overlapping Intervals" }, { "code": null, "e": 25204, "s": 25155, "text": "Stack | Set 4 (Evaluation of Postfix Expression)" }, { "code": null, "e": 25250, "s": 25204, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 25275, "s": 25250, "text": "Reverse a string in Java" }, { "code": null, "e": 25335, "s": 25275, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 25350, "s": 25335, "text": "C++ Data Types" } ]
Vampire Number
14 Jun, 2019 Introduction to Vampire Number and its implementation using python. IntroductionIn mathematics, a vampire number (or true vampire number) is a composite natural number v, with an even number of digits n, that can be factored into two integers x and y each with n/2 digits and not both with trailing zeroes, where v contains precisely all the digits from x and from y, in any order, counting multiplicity. x and y are called the fangs. [Source Wiki] Examples: 1260 is a vampire number, with 21 and 60 as fangs, since 21 × 60 = 1260. 126000 (which can be expressed as 21 × 6000 or 210 × 600) is not, as 21 and 6000 do not have the correct length, and both 210 and 600 have trailing zeroes The vampire numbers are:1260, 1395, 1435, 1530, 1827, 2187, 6880, 102510, 104260, 105210, 105264, 105750, 108135, 110758, 115672, 116725, 117067, 118440, 120600, 123354, 124483, 125248, 125433, 125460, 125500, ... (sequence A014575 in the OEIS) There are many known sequences of infinitely many vampire numbers following a pattern, such as:1530 = 30×51, 150300 = 300×501, 15003000 = 3000×5001, ... Condition for a number to be Vampire Number: Has a pair number of digits. Lets call the number of digits : nYou can obtain the number by multiplying two integers, x and y, each with n/2 digits. x and y are the fangs.Both fangs cannot end simultaneously in 0.The number can be made with all digits from x and y, in any order and only using each digit once. Has a pair number of digits. Lets call the number of digits : n You can obtain the number by multiplying two integers, x and y, each with n/2 digits. x and y are the fangs. Both fangs cannot end simultaneously in 0. The number can be made with all digits from x and y, in any order and only using each digit once. Pseudocode if digitcount is odd return false if digitcount is 2 return false for A = each permutation of length digitcount/2 selected from all the digits, for B = each permutation of the remaining digits, if either A or B starts with a zero, continue if both A and B end in a zero, continue if A*B == the number, return true # Python code to check if a number is Vampire# and printing Vampire numbers upto n using# itimport itertools as it # function to get the required fangs of the# vampire numberdef getFangs(num_str): # to get all possible orderings of order that # is equal to the number of digits of the # vampire number num_iter = it.permutations(num_str, len(num_str)) # creating the possible pairs of number by # brute forcing, then checking the condition # if it satisfies what it takes to be the fangs # of a vampire number for num_list in num_iter: v = ''.join(num_list) x, y = v[:int(len(v)/2)], v[int(len(v)/2):] # if numbers have trailing zeroes then skip if x[-1] == '0' and y[-1] == '0': continue # if x * y is equal to the vampire number # then return the numbers as its fangs if int(x) * int(y) == int(num_str): return x,y return False # function to check whether the given number is # vampire or notdef isVampire(m_int): # converting the vampire number to string n_str = str(m_int) # if no of digits in the number is odd then # return false if len(n_str) % 2 == 1: return False # getting the fangs of the number fangs = getFangs(n_str) if not fangs: return False return True # main driver programn = 16000for test_num in range(n): if isVampire(test_num): print ("{}".format(test_num), end = ", ") Output: 1260, 1395, 1435, 1530, 1827, 2187, 6880, Refer to numberphile for more details:Vampire Numbers - Numberphile - YouTubeNumberphile4.12M subscribersVampire Numbers - NumberphileWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3ZMnVd4ivKQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: Rossetta CodeWikipedia – Vampire NumberStackoverflowPython Docs on itertools Rossetta Code Wikipedia – Vampire Number Stackoverflow Python Docs on itertools This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai number-digits series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2019" }, { "code": null, "e": 122, "s": 54, "text": "Introduction to Vampire Number and its implementation using python." }, { "code": null, "e": 503, "s": 122, "text": "IntroductionIn mathematics, a vampire number (or true vampire number) is a composite natural number v, with an even number of digits n, that can be factored into two integers x and y each with n/2 digits and not both with trailing zeroes, where v contains precisely all the digits from x and from y, in any order, counting multiplicity. x and y are called the fangs. [Source Wiki]" }, { "code": null, "e": 513, "s": 503, "text": "Examples:" }, { "code": null, "e": 586, "s": 513, "text": "1260 is a vampire number, with 21 and 60 as fangs, since 21 × 60 = 1260." }, { "code": null, "e": 741, "s": 586, "text": "126000 (which can be expressed as 21 × 6000 or 210 × 600) is not, as 21 and 6000 do not have the correct length, and both 210 and 600 have trailing zeroes" }, { "code": null, "e": 986, "s": 741, "text": "The vampire numbers are:1260, 1395, 1435, 1530, 1827, 2187, 6880, 102510, 104260, 105210, 105264, 105750, 108135, 110758, 115672, 116725, 117067, 118440, 120600, 123354, 124483, 125248, 125433, 125460, 125500, ... (sequence A014575 in the OEIS)" }, { "code": null, "e": 1139, "s": 986, "text": "There are many known sequences of infinitely many vampire numbers following a pattern, such as:1530 = 30×51, 150300 = 300×501, 15003000 = 3000×5001, ..." }, { "code": null, "e": 1184, "s": 1139, "text": "Condition for a number to be Vampire Number:" }, { "code": null, "e": 1495, "s": 1184, "text": "Has a pair number of digits. Lets call the number of digits : nYou can obtain the number by multiplying two integers, x and y, each with n/2 digits. x and y are the fangs.Both fangs cannot end simultaneously in 0.The number can be made with all digits from x and y, in any order and only using each digit once." }, { "code": null, "e": 1559, "s": 1495, "text": "Has a pair number of digits. Lets call the number of digits : n" }, { "code": null, "e": 1668, "s": 1559, "text": "You can obtain the number by multiplying two integers, x and y, each with n/2 digits. x and y are the fangs." }, { "code": null, "e": 1711, "s": 1668, "text": "Both fangs cannot end simultaneously in 0." }, { "code": null, "e": 1809, "s": 1711, "text": "The number can be made with all digits from x and y, in any order and only using each digit once." }, { "code": null, "e": 1820, "s": 1809, "text": "Pseudocode" }, { "code": null, "e": 2157, "s": 1820, "text": "if digitcount is odd return false\nif digitcount is 2 return false\nfor A = each permutation of length digitcount/2 \n selected from all the digits,\n for B = each permutation of the remaining digits,\n if either A or B starts with a zero, continue\n if both A and B end in a zero, continue\n if A*B == the number, return true" }, { "code": "# Python code to check if a number is Vampire# and printing Vampire numbers upto n using# itimport itertools as it # function to get the required fangs of the# vampire numberdef getFangs(num_str): # to get all possible orderings of order that # is equal to the number of digits of the # vampire number num_iter = it.permutations(num_str, len(num_str)) # creating the possible pairs of number by # brute forcing, then checking the condition # if it satisfies what it takes to be the fangs # of a vampire number for num_list in num_iter: v = ''.join(num_list) x, y = v[:int(len(v)/2)], v[int(len(v)/2):] # if numbers have trailing zeroes then skip if x[-1] == '0' and y[-1] == '0': continue # if x * y is equal to the vampire number # then return the numbers as its fangs if int(x) * int(y) == int(num_str): return x,y return False # function to check whether the given number is # vampire or notdef isVampire(m_int): # converting the vampire number to string n_str = str(m_int) # if no of digits in the number is odd then # return false if len(n_str) % 2 == 1: return False # getting the fangs of the number fangs = getFangs(n_str) if not fangs: return False return True # main driver programn = 16000for test_num in range(n): if isVampire(test_num): print (\"{}\".format(test_num), end = \", \")", "e": 3632, "s": 2157, "text": null }, { "code": null, "e": 3640, "s": 3632, "text": "Output:" }, { "code": null, "e": 3684, "s": 3640, "text": "1260, 1395, 1435, 1530, 1827, 2187, 6880, \n" }, { "code": null, "e": 4565, "s": 3684, "text": "Refer to numberphile for more details:Vampire Numbers - Numberphile - YouTubeNumberphile4.12M subscribersVampire Numbers - NumberphileWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3ZMnVd4ivKQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 4577, "s": 4565, "text": "References:" }, { "code": null, "e": 4654, "s": 4577, "text": "Rossetta CodeWikipedia – Vampire NumberStackoverflowPython Docs on itertools" }, { "code": null, "e": 4668, "s": 4654, "text": "Rossetta Code" }, { "code": null, "e": 4695, "s": 4668, "text": "Wikipedia – Vampire Number" }, { "code": null, "e": 4709, "s": 4695, "text": "Stackoverflow" }, { "code": null, "e": 4734, "s": 4709, "text": "Python Docs on itertools" }, { "code": null, "e": 5035, "s": 4734, "text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5160, "s": 5035, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5173, "s": 5160, "text": "Akanksha_Rai" }, { "code": null, "e": 5187, "s": 5173, "text": "number-digits" }, { "code": null, "e": 5194, "s": 5187, "text": "series" }, { "code": null, "e": 5207, "s": 5194, "text": "Mathematical" }, { "code": null, "e": 5220, "s": 5207, "text": "Mathematical" }, { "code": null, "e": 5227, "s": 5220, "text": "series" }, { "code": null, "e": 5325, "s": 5227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5349, "s": 5325, "text": "Merge two sorted arrays" }, { "code": null, "e": 5370, "s": 5349, "text": "Operators in C / C++" }, { "code": null, "e": 5384, "s": 5370, "text": "Prime Numbers" }, { "code": null, "e": 5421, "s": 5384, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 5474, "s": 5421, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 5517, "s": 5474, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 5549, "s": 5517, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5576, "s": 5549, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 5619, "s": 5576, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Working with Images – Python .docx Module
03 Jan, 2021 Prerequisites: docx Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add an image in a word document we use add_picture() method. This method is used to add an image in your Word document whenever called. Syntax: doc.add_picture(image_path, width=None, height=None) Parameters: image_path: It is a string containing the path of the image to be added. width: It sets the width of the image to be added in the document. height: It sets the height of the image to be added in the document. In the function given above, height and width are not specified then the image appears in its native size. Pip command to install this module is: pip install python-docx Import module Create docx object Declare add_picture() method where ever image is required to be inserted, along with the path to that image and dimensions(optional). Save document. Example 1: Adding an image in native size in a word document. Python3 # Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Image in its native sizedoc.add_heading('Image in Native Size:', 3)doc.add_picture('logo.png') # Now save the document to a locationdoc.save('gfg.docx') Output: gfg.docx Example 2: Adding an image in a defined size in a word document. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Image with defined sizedoc.add_heading('Image with Defined Size:', 3)doc.add_picture('logo.png', width=Inches(2), height=Inches(2)) # Now save the document to a locationdoc.save('gfg.docx') Output: gfg.docx Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2021" }, { "code": null, "e": 48, "s": 28, "text": "Prerequisites: docx" }, { "code": null, "e": 369, "s": 48, "text": "Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. " }, { "code": null, "e": 741, "s": 369, "text": "Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add an image in a word document we use add_picture() method. This method is used to add an image in your Word document whenever called." }, { "code": null, "e": 802, "s": 741, "text": "Syntax: doc.add_picture(image_path, width=None, height=None)" }, { "code": null, "e": 814, "s": 802, "text": "Parameters:" }, { "code": null, "e": 887, "s": 814, "text": "image_path: It is a string containing the path of the image to be added." }, { "code": null, "e": 954, "s": 887, "text": "width: It sets the width of the image to be added in the document." }, { "code": null, "e": 1023, "s": 954, "text": "height: It sets the height of the image to be added in the document." }, { "code": null, "e": 1130, "s": 1023, "text": "In the function given above, height and width are not specified then the image appears in its native size." }, { "code": null, "e": 1169, "s": 1130, "text": "Pip command to install this module is:" }, { "code": null, "e": 1193, "s": 1169, "text": "pip install python-docx" }, { "code": null, "e": 1207, "s": 1193, "text": "Import module" }, { "code": null, "e": 1226, "s": 1207, "text": "Create docx object" }, { "code": null, "e": 1360, "s": 1226, "text": "Declare add_picture() method where ever image is required to be inserted, along with the path to that image and dimensions(optional)." }, { "code": null, "e": 1375, "s": 1360, "text": "Save document." }, { "code": null, "e": 1437, "s": 1375, "text": "Example 1: Adding an image in native size in a word document." }, { "code": null, "e": 1445, "s": 1437, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Image in its native sizedoc.add_heading('Image in Native Size:', 3)doc.add_picture('logo.png') # Now save the document to a locationdoc.save('gfg.docx')", "e": 1771, "s": 1445, "text": null }, { "code": null, "e": 1779, "s": 1771, "text": "Output:" }, { "code": null, "e": 1788, "s": 1779, "text": "gfg.docx" }, { "code": null, "e": 1853, "s": 1788, "text": "Example 2: Adding an image in a defined size in a word document." }, { "code": null, "e": 1861, "s": 1853, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Image with defined sizedoc.add_heading('Image with Defined Size:', 3)doc.add_picture('logo.png', width=Inches(2), height=Inches(2)) # Now save the document to a locationdoc.save('gfg.docx')", "e": 2256, "s": 1861, "text": null }, { "code": null, "e": 2264, "s": 2256, "text": "Output:" }, { "code": null, "e": 2273, "s": 2264, "text": "gfg.docx" }, { "code": null, "e": 2297, "s": 2273, "text": "Technical Scripter 2020" }, { "code": null, "e": 2304, "s": 2297, "text": "Python" }, { "code": null, "e": 2323, "s": 2304, "text": "Technical Scripter" }, { "code": null, "e": 2421, "s": 2323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2453, "s": 2421, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2480, "s": 2453, "text": "Python Classes and Objects" }, { "code": null, "e": 2501, "s": 2480, "text": "Python OOPs Concepts" }, { "code": null, "e": 2524, "s": 2501, "text": "Introduction To PYTHON" }, { "code": null, "e": 2555, "s": 2524, "text": "Python | os.path.join() method" }, { "code": null, "e": 2611, "s": 2555, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2653, "s": 2611, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2695, "s": 2653, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2734, "s": 2695, "text": "Python | Get unique values from a list" } ]
Python | Ways to rotate a list
30 Nov, 2018 The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmers life to achieve various tasks. Let’s discuss different ways we can rotate a list. Method #1 : Using SlicingThis particular method is the generic method and mostly employed to achieve this task and also been discussed in many articles as well. It works by just joining the later sliced part to the initial sliced part given the rotation number. # Python3 code to demonstrate # rotation of list # using slice # initializing listtest_list = [1, 4, 6, 7, 2] # printing original list print ("Original list : " + str(test_list)) # using slicing to left rotate by 3test_list = test_list[3:] + test_list[:3] # Printing list after left rotateprint ("List after left rotate by 3 : " + str(test_list)) # using slicing to right rotate by 3# back to Originaltest_list = test_list[-3:] + test_list[:-3] # Printing after right rotateprint ("List after right rotate by 3(back to original) : " + str(test_list)) Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3 ( back to original) : [1, 4, 6, 7, 2] Method #2 : Using list ComprehensionThis problem can also be solved by naive method, but its shorter implementation would be with the help of list comprehension. In this method, we just reassign the index to each value to specific position after rotation. # Python3 code to demonstrate # rotation of list # using list comprehension # initializing listtest_list = [1, 4, 6, 7, 2] # printing original list print ("Original list : " + str(test_list)) # using list comprehension to left rotate by 3test_list = [test_list[(i + 3) % len(test_list)] for i, x in enumerate(test_list)] # Printing list after left rotateprint ("List after left rotate by 3 : " + str(test_list)) # using list comprehension to right rotate by 3# back to Originaltest_list = [test_list[(i - 3) % len(test_list)] for i, x in enumerate(test_list)] # Printing after right rotateprint ("List after right rotate by 3(back to original) : " + str(test_list)) Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3(back to original) : [1, 4, 6, 7, 2] Method #3 : Using collections.deque.rotate()The collections module has deque class which provides the rotate(), which is inbuilt function to allow rotation. This is lesser known function but has a greater utility. # Python3 code to demonstrate # rotation of list # using rotate()from collections import deque # initializing listtest_list = [1, 4, 6, 7, 2] # printing original list print ("Original list : " + str(test_list)) # using rotate() to left rotate by 3test_list = deque(test_list)test_list.rotate(-3)test_list = list(test_list) # Printing list after left rotateprint ("List after left rotate by 3 : " + str(test_list)) # using rotate() to right rotate by 3# back to Originaltest_list = deque(test_list)test_list.rotate(3)test_list = list(test_list) # Printing after right rotateprint ("List after right rotate by 3(back to original) : " + str(test_list)) Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3(back to original) : [1, 4, 6, 7, 2] Python list-programs python-list rotation Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Nov, 2018" }, { "code": null, "e": 313, "s": 53, "text": "The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmers life to achieve various tasks." }, { "code": null, "e": 364, "s": 313, "text": "Let’s discuss different ways we can rotate a list." }, { "code": null, "e": 626, "s": 364, "text": "Method #1 : Using SlicingThis particular method is the generic method and mostly employed to achieve this task and also been discussed in many articles as well. It works by just joining the later sliced part to the initial sliced part given the rotation number." }, { "code": "# Python3 code to demonstrate # rotation of list # using slice # initializing listtest_list = [1, 4, 6, 7, 2] # printing original list print (\"Original list : \" + str(test_list)) # using slicing to left rotate by 3test_list = test_list[3:] + test_list[:3] # Printing list after left rotateprint (\"List after left rotate by 3 : \" + str(test_list)) # using slicing to right rotate by 3# back to Originaltest_list = test_list[-3:] + test_list[:-3] # Printing after right rotateprint (\"List after right rotate by 3(back to original) : \" + str(test_list))", "e": 1224, "s": 626, "text": null }, { "code": null, "e": 1370, "s": 1224, "text": "Original list : [1, 4, 6, 7, 2]\nList after left rotate by 3 : [7, 2, 1, 4, 6]\nList after right rotate by 3 ( back to original) : [1, 4, 6, 7, 2]\n" }, { "code": null, "e": 1627, "s": 1370, "text": " Method #2 : Using list ComprehensionThis problem can also be solved by naive method, but its shorter implementation would be with the help of list comprehension. In this method, we just reassign the index to each value to specific position after rotation." }, { "code": "# Python3 code to demonstrate # rotation of list # using list comprehension # initializing listtest_list = [1, 4, 6, 7, 2] # printing original list print (\"Original list : \" + str(test_list)) # using list comprehension to left rotate by 3test_list = [test_list[(i + 3) % len(test_list)] for i, x in enumerate(test_list)] # Printing list after left rotateprint (\"List after left rotate by 3 : \" + str(test_list)) # using list comprehension to right rotate by 3# back to Originaltest_list = [test_list[(i - 3) % len(test_list)] for i, x in enumerate(test_list)] # Printing after right rotateprint (\"List after right rotate by 3(back to original) : \" + str(test_list))", "e": 2367, "s": 1627, "text": null }, { "code": null, "e": 2511, "s": 2367, "text": "Original list : [1, 4, 6, 7, 2]\nList after left rotate by 3 : [7, 2, 1, 4, 6]\nList after right rotate by 3(back to original) : [1, 4, 6, 7, 2]\n" }, { "code": null, "e": 2726, "s": 2511, "text": " Method #3 : Using collections.deque.rotate()The collections module has deque class which provides the rotate(), which is inbuilt function to allow rotation. This is lesser known function but has a greater utility." }, { "code": "# Python3 code to demonstrate # rotation of list # using rotate()from collections import deque # initializing listtest_list = [1, 4, 6, 7, 2] # printing original list print (\"Original list : \" + str(test_list)) # using rotate() to left rotate by 3test_list = deque(test_list)test_list.rotate(-3)test_list = list(test_list) # Printing list after left rotateprint (\"List after left rotate by 3 : \" + str(test_list)) # using rotate() to right rotate by 3# back to Originaltest_list = deque(test_list)test_list.rotate(3)test_list = list(test_list) # Printing after right rotateprint (\"List after right rotate by 3(back to original) : \" + str(test_list))", "e": 3421, "s": 2726, "text": null }, { "code": null, "e": 3565, "s": 3421, "text": "Original list : [1, 4, 6, 7, 2]\nList after left rotate by 3 : [7, 2, 1, 4, 6]\nList after right rotate by 3(back to original) : [1, 4, 6, 7, 2]\n" }, { "code": null, "e": 3586, "s": 3565, "text": "Python list-programs" }, { "code": null, "e": 3598, "s": 3586, "text": "python-list" }, { "code": null, "e": 3607, "s": 3598, "text": "rotation" }, { "code": null, "e": 3614, "s": 3607, "text": "Python" }, { "code": null, "e": 3626, "s": 3614, "text": "python-list" }, { "code": null, "e": 3724, "s": 3626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3742, "s": 3724, "text": "Python Dictionary" }, { "code": null, "e": 3784, "s": 3742, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3806, "s": 3784, "text": "Enumerate() in Python" }, { "code": null, "e": 3841, "s": 3806, "text": "Read a file line by line in Python" }, { "code": null, "e": 3867, "s": 3841, "text": "Python String | replace()" }, { "code": null, "e": 3899, "s": 3867, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3928, "s": 3899, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3958, "s": 3928, "text": "Iterate over a list in Python" }, { "code": null, "e": 3985, "s": 3958, "text": "Python Classes and Objects" } ]
How to Implement Chat Functionality in Social Media Android App?
09 May, 2022 This is the Part 14 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article: We are going to Create a Layout for chat & Send Messages in Chat. A user can send either a Message or an Image. A user can send an image either using a camera or gallery. Firstly a request for permission will be asked to send an image using a gallery or after clicking the image using the camera. If permission is given then the user can send the image, or it will again request for asking permission. Step 1: Create two new layout resource files and name them row_chat_left and row_chat_right Working with the row_chat_left.xml file. The received message will be on the left side. Similarly, Working with the row_chat_right.xml file. The message sends to the user will be on the right side. Below is the code for the row_chat_left.xml file and row_chat_right.xml file. XML XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/msglayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/profilec" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/profile_image" app:civ_border_color="@null" /> <TextView android:id="@+id/msgc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/bg_receiver" android:padding="15dp" android:text="His Message" android:textColor="@color/colorBlack" android:textSize="16sp" android:visibility="gone" /> <ImageView android:id="@+id/images" android:layout_width="200dp" android:layout_height="200dp" android:adjustViewBounds="true" android:background="@drawable/bg_receiver" android:padding="15dp" android:scaleType="fitCenter" android:src="@drawable/ic_images" /> <TextView android:id="@+id/timetv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="02/01/1990 06:19PM" android:textColor="@color/colorBlack" android:textSize="12sp" /> </LinearLayout> <TextView android:id="@+id/isSeen" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="end" android:text="Delivered" android:textAlignment="textEnd" android:visibility="gone" /> </LinearLayout> <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/msglayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/profilec" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/profile_image" android:visibility="gone" app:civ_border_color="@null" /> <TextView android:id="@+id/timetv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="02/01/1990 06:19PM" android:textColor="@color/colorBlack" android:textSize="12sp" /> <TextView android:id="@+id/msgc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_toEndOf="@id/timetv" android:background="@drawable/bg_sender" android:padding="15dp" android:text="His Message" android:textColor="@color/colorBlack" android:textSize="16sp" /> <ImageView android:id="@+id/images" android:layout_width="200dp" android:layout_height="200dp" android:layout_alignParentEnd="true" android:adjustViewBounds="true" android:background="@drawable/bg_sender" android:padding="15dp" android:scaleType="fitCenter" android:src="@drawable/ic_images" /> </RelativeLayout> <TextView android:id="@+id/isSeen" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="end" android:text="Delivered" android:textAlignment="textEnd" /> </LinearLayout> Step 2: Working with the activity_chat.xml file Here In the RecyclerView, we will be showing all the messages. In the TextView user will type the message and using the send button user will send the message. Below is the code for the activity_chat.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ChatActivity"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:background="@color/colorPrimaryDark" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/profiletv" android:layout_width="35dp" android:layout_height="35dp" android:scaleType="centerCrop" android:src="@drawable/profile_image" app:civ_circle_background_color="@color/colorPrimaryDark" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginLeft="20dp" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/nameptv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="HisName" android:textColor="@color/colorWhite" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/onlinetv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Online" android:textColor="@color/colorWhite" android:textStyle="bold" /> </LinearLayout> <ImageView android:id="@+id/block" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginEnd="5dp" android:src="@drawable/ic_unblock" /> </LinearLayout> </androidx.appcompat.widget.Toolbar> <androidx.recyclerview.widget.RecyclerView android:id="@+id/chatrecycle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/chatlayout" android:layout_below="@id/toolbar" /> <LinearLayout android:id="@+id/chatlayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@color/colorWhite" android:gravity="center" android:orientation="horizontal"> <ImageButton android:id="@+id/attachbtn" android:layout_width="50dp" android:layout_height="50dp" android:background="@null" android:src="@drawable/ic_iattach" /> <EditText android:id="@+id/messaget" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@null" android:hint="Start Typing" android:inputType="textCapSentences|textMultiLine" android:padding="15dp" /> <ImageButton android:id="@+id/sendmsg" android:layout_width="40dp" android:layout_height="40dp" android:background="@null" android:src="@drawable/send_message" /> </LinearLayout> </RelativeLayout> Step 3: Working with the row_chatlist.xml file Create another layout resource file and name the file as row_chatlist. Below is the code for the row_chatlist.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:contentPadding="3dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/profileimage" android:layout_width="70dp" android:layout_height="70dp" android:src="@drawable/profile_image" /> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/onlinestatus" android:layout_width="25dp" android:layout_height="25dp" /> <TextView android:id="@+id/nameonline" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="4dp" android:layout_toEndOf="@id/profileimage" android:layout_toRightOf="@id/profileimage" android:text="His Name" android:textColor="@color/colorBlack" android:textSize="18sp" /> <TextView android:id="@+id/lastmessge" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/nameonline" android:layout_marginStart="4dp" android:layout_toEndOf="@id/profileimage" android:layout_toRightOf="@id/profileimage" android:maxLines="2" android:text="Last Message" android:textColor="@color/colorBlack" /> <ImageView android:id="@+id/blocking" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_gravity="center_vertical" android:src="@drawable/ic_unblock" /> <ImageView android:id="@+id/seen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/blocking" android:layout_alignParentEnd="true" android:layout_gravity="center_vertical" android:src="@drawable/ic_unblock" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 4: Working with the ModelChat.java file Created this class to initialize the key so that we can retrieve the value of the key later. Java package com.example.socialmediaapp; public class ModelChat { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public boolean isDilihat() { return dilihat; } public void setDilihat(boolean dilihat) { this.dilihat = dilihat; } String receiver; public ModelChat() { } String sender; public String getType() { return type; } public void setType(String type) { this.type = type; } public ModelChat(String message, String receiver, String sender, String type, String timestamp, boolean dilihat) { this.message = message; this.receiver = receiver; this.sender = sender; this.type = type; this.timestamp = timestamp; this.dilihat = dilihat; } String type; String timestamp; boolean dilihat;} Step 5: Working with the AdpaterChat.java file Create a new java class and name the class as AdpaterChat. Below is the code for the AdpaterChat.java file. Java package com.example.socialmediaapp; import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.text.format.DateFormat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener; import java.util.Calendar;import java.util.List;import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; public class AdapterChat extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterChat.Myholder> { private static final int MSG_TYPE_LEFT = 0; private static final int MSG_TYPR_RIGHT = 1; Context context; List<ModelChat> list; String imageurl; FirebaseUser firebaseUser; public AdapterChat(Context context, List<ModelChat> list, String imageurl) { this.context = context; this.list = list; this.imageurl = imageurl; } @NonNull @Override public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == MSG_TYPE_LEFT) { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, parent, false); return new Myholder(view); } else { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, parent, false); return new Myholder(view); } } @Override public void onBindViewHolder(@NonNull Myholder holder, final int position) { String message = list.get(position).getMessage(); String timeStamp = list.get(position).getTimestamp(); String type = list.get(position).getType(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(timeStamp)); String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString(); holder.message.setText(message); holder.time.setText(timedate); try { Glide.with(context).load(imageurl).into(holder.image); } catch (Exception e) { } if (type.equals("text")) { holder.message.setVisibility(View.VISIBLE); holder.mimage.setVisibility(View.GONE); holder.message.setText(message); } else { holder.message.setVisibility(View.GONE); holder.mimage.setVisibility(View.VISIBLE); Glide.with(context).load(message).into(holder.mimage); } holder.msglayput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Delete Message"); builder.setMessage("Are You Sure To Delete This Message"); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteMsg(position); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } }); } private void deleteMsg(int position) { final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); String msgtimestmp = list.get(position).getTimestamp(); DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child("Chats"); Query query = dbref.orderByChild("timestamp").equalTo(msgtimestmp); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { if (dataSnapshot1.child("sender").getValue().equals(myuid)) { // any two of below can be used dataSnapshot1.getRef().removeValue(); /* HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("message", "This Message Was Deleted"); dataSnapshot1.getRef().updateChildren(hashMap); Toast.makeText(context,"Message Deleted.....",Toast.LENGTH_LONG).show();*/ } else { Toast.makeText(context, "you can delete only your msg....", Toast.LENGTH_LONG).show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return list.size(); } @Override public int getItemViewType(int position) { firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (list.get(position).getSender().equals(firebaseUser.getUid())) { return MSG_TYPR_RIGHT; } else { return MSG_TYPE_LEFT; } } class Myholder extends RecyclerView.ViewHolder { CircleImageView image; ImageView mimage; TextView message, time, isSee; LinearLayout msglayput; public Myholder(@NonNull View itemView) { super(itemView); image = itemView.findViewById(R.id.profilec); message = itemView.findViewById(R.id.msgc); time = itemView.findViewById(R.id.timetv); isSee = itemView.findViewById(R.id.isSeen); msglayput = itemView.findViewById(R.id.msglayout); mimage = itemView.findViewById(R.id.images); } }} Step 6: Working with the ChatActivity.java file We are Reading the user message from “Chats” Node in Firebase. Every time data changes this data will change accordingly chatList=new ArrayList<>(); DatabaseReference dbref= FirebaseDatabase.getInstance().getReference().child("Chats"); Loading the Data setting data value using adapter chat ModelChat modelChat=dataSnapshot1.getValue(ModelChat.class); if(modelChat.getSender().equals(myuid)&& modelChat.getReceiver().equals(uid)|| modelChat.getReceiver().equals(myuid) && modelChat.getSender().equals(uid)){ chatList.add(modelChat);//add the chat in chatlist } adapterChat=new AdapterChat(ChatActivity.this,chatList,image); adapterChat.notifyDataSetChanged(); recyclerView.setAdapter(adapterChat); Sending Messages in Chat Reference node value. Here is how we are saving data in the Firebase Realtime database DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference(); String timestamp=String.valueOf(System.currentTimeMillis()); HashMap<String,Object> hashMap=new HashMap<>(); hashMap.put("sender",myuid); hashMap.put("receiver",uid); hashMap.put("message",message); hashMap.put("timestamp",timestamp); hashMap.put("dilihat",false); hashMap.put("type","text"); databaseReference.child("Chats").push().setValue(hashMap); Below is the code for the ChatActivity.java file. Java package com.example.socialmediaapp; import android.Manifest;import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.text.TextUtils;import android.text.format.DateFormat;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar;import androidx.core.content.ContextCompat;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.StorageReference;import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List; public class ChatActivity extends AppCompatActivity { Toolbar toolbar; RecyclerView recyclerView; ImageView profile, block; TextView name, userstatus; EditText msg; ImageButton send, attach; FirebaseAuth firebaseAuth; String uid, myuid, image; ValueEventListener valueEventListener; List<ModelChat> chatList; AdapterChat adapterChat; private static final int IMAGEPICK_GALLERY_REQUEST = 300; private static final int IMAGE_PICKCAMERA_REQUEST = 400; private static final int CAMERA_REQUEST = 100; private static final int STORAGE_REQUEST = 200; String cameraPermission[]; String storagePermission[]; Uri imageuri = null; FirebaseDatabase firebaseDatabase; DatabaseReference users; boolean notify = false; boolean isBlocked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); firebaseAuth = FirebaseAuth.getInstance(); // initialise the text views and layouts profile = findViewById(R.id.profiletv); name = findViewById(R.id.nameptv); userstatus = findViewById(R.id.onlinetv); msg = findViewById(R.id.messaget); send = findViewById(R.id.sendmsg); attach = findViewById(R.id.attachbtn); block = findViewById(R.id.block); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setStackFromEnd(true); recyclerView = findViewById(R.id.chatrecycle); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(linearLayoutManager); uid = getIntent().getStringExtra("uid"); // getting uid of another user using intent firebaseDatabase = FirebaseDatabase.getInstance(); // initialising permissions cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; checkUserStatus(); users = firebaseDatabase.getReference("Users"); attach.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showImagePicDialog(); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notify = true; String message = msg.getText().toString().trim(); if (TextUtils.isEmpty(message)) {//if empty Toast.makeText(ChatActivity.this, "Please Write Something Here", Toast.LENGTH_LONG).show(); } else { sendmessage(message); } msg.setText(""); } }); Query userquery = users.orderByChild("uid").equalTo(uid); userquery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // retrieve user data for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String nameh = "" + dataSnapshot1.child("name").getValue(); image = "" + dataSnapshot1.child("image").getValue(); String onlinestatus = "" + dataSnapshot1.child("onlineStatus").getValue(); String typingto = "" + dataSnapshot1.child("typingTo").getValue(); if (typingto.equals(myuid)) {// if user is typing to my chat userstatus.setText("Typing....");// type status as typing } else { if (onlinestatus.equals("online")) { userstatus.setText(onlinestatus); } else { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(onlinestatus)); String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString(); userstatus.setText("Last Seen:" + timedate); } } name.setText(nameh); try { Glide.with(ChatActivity.this).load(image).placeholder(R.drawable.profile_image).into(profile); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); readMessages(); } @Override protected void onPause() { super.onPause(); String timestamp = String.valueOf(System.currentTimeMillis()); checkOnlineStatus(timestamp); checkTypingStatus("noOne"); } @Override protected void onResume() { checkOnlineStatus("online"); super.onResume(); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); } private void checkOnlineStatus(String status) { // check online status DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Users").child(myuid); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("onlineStatus", status); dbref.updateChildren(hashMap); } private void checkTypingStatus(String typing) { DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Users").child(myuid); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("typingTo", typing); dbref.updateChildren(hashMap); } @Override protected void onStart() { checkUserStatus(); checkOnlineStatus("online"); super.onStart(); } private void readMessages() { // show message after retrieving data chatList = new ArrayList<>(); DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child("Chats"); dbref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { chatList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelChat modelChat = dataSnapshot1.getValue(ModelChat.class); if (modelChat.getSender().equals(myuid) && modelChat.getReceiver().equals(uid) || modelChat.getReceiver().equals(myuid) && modelChat.getSender().equals(uid)) { chatList.add(modelChat); // add the chat in chatlist } adapterChat = new AdapterChat(ChatActivity.this, chatList, image); adapterChat.notifyDataSetChanged(); recyclerView.setAdapter(adapterChat); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void showImagePicDialog() { String options[] = {"Camera", "Gallery"}; AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this); builder.setTitle("Pick Image From"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { if (!checkCameraPermission()) { // if permission is not given requestCameraPermission(); // request for permission } else { pickFromCamera(); // if already access granted then click } } else if (which == 1) { if (!checkStoragePermission()) { // if permission is not given requestStoragePermission(); // request for permission } else { pickFromGallery(); // if already access granted then pick } } } }); builder.create().show(); } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // request for permission if not given switch (requestCode) { case CAMERA_REQUEST: { if (grantResults.length > 0) { boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (camera_accepted && writeStorageaccepted) { pickFromCamera(); // if access granted then click } else { Toast.makeText(this, "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show(); } } } break; case STORAGE_REQUEST: { if (grantResults.length > 0) { boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeStorageaccepted) { pickFromGallery(); // if access granted then pick } else { Toast.makeText(this, "Please Enable Storage Permissions", Toast.LENGTH_LONG).show(); } } } break; } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == RESULT_OK) { if (requestCode == IMAGEPICK_GALLERY_REQUEST) { imageuri = data.getData(); // get image data to upload try { sendImageMessage(imageuri); } catch (IOException e) { e.printStackTrace(); } } if (requestCode == IMAGE_PICKCAMERA_REQUEST) { try { sendImageMessage(imageuri); } catch (IOException e) { e.printStackTrace(); } } } super.onActivityResult(requestCode, resultCode, data); } private void sendImageMessage(Uri imageuri) throws IOException { notify = true; final ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage("Sending Image"); dialog.show(); // If we are sending image as a message // then we need to find the url of // image after uploading the // image in firebase storage final String timestamp = "" + System.currentTimeMillis(); String filepathandname = "ChatImages/" + "post" + timestamp; // filename Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageuri); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, arrayOutputStream); // compressing the image using bitmap final byte[] data = arrayOutputStream.toByteArray(); StorageReference ref = FirebaseStorage.getInstance().getReference().child(filepathandname); ref.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { dialog.dismiss(); Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()) ; String downloadUri = uriTask.getResult().toString(); // getting url if task is successful if (uriTask.isSuccessful()) { DatabaseReference re = FirebaseDatabase.getInstance().getReference(); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("sender", myuid); hashMap.put("receiver", uid); hashMap.put("message", downloadUri); hashMap.put("timestamp", timestamp); hashMap.put("dilihat", false); hashMap.put("type", "images"); re.child("Chats").push().setValue(hashMap); // push in firebase using unique id final DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference("ChatList").child(uid).child(myuid); ref1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref1.child("id").setValue(myuid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); final DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("ChatList").child(myuid).child(uid); ref2.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref2.child("id").setValue(uid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } private Boolean checkCameraPermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } private void requestCameraPermission() { requestPermissions(cameraPermission, CAMERA_REQUEST); } private void pickFromCamera() { ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.Images.Media.TITLE, "Temp_pic"); contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description"); imageuri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); camerIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri); startActivityForResult(camerIntent, IMAGE_PICKCAMERA_REQUEST); } private void pickFromGallery() { Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent, IMAGEPICK_GALLERY_REQUEST); } private Boolean checkStoragePermission() { boolean result = ContextCompat.checkSelfPermission(ChatActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } private void requestStoragePermission() { requestPermissions(storagePermission, STORAGE_REQUEST); } private void sendmessage(final String message) { // creating a reference to store data in firebase // We will be storing data using current time in "Chatlist" // and we are pushing data using unique id in "Chats" DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(); String timestamp = String.valueOf(System.currentTimeMillis()); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("sender", myuid); hashMap.put("receiver", uid); hashMap.put("message", message); hashMap.put("timestamp", timestamp); hashMap.put("dilihat", false); hashMap.put("type", "text"); databaseReference.child("Chats").push().setValue(hashMap); final DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference("ChatList").child(uid).child(myuid); ref1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref1.child("id").setValue(myuid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); final DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("ChatList").child(myuid).child(uid); ref2.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref2.child("id").setValue(uid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.logout) { firebaseAuth.signOut(); checkUserStatus(); } return super.onOptionsItemSelected(item); } private void checkUserStatus() { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { myuid = user.getUid(); } }} Output: Step 1: Working with the ModelChatlist.xml file Getting the id of users to whom we have sent messages. Java package com.example.socialmediaapp; class ModelChatList { public String getId() { return id; } public void setId(String id) { this.id = id; } public ModelChatList() { } public ModelChatList(String id) { this.id = id; } String id;} Step 2: Working with the AdapterChatList.java file Showing the users and the last message sent in the chat. Java package com.example.socialmediaapp; import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.firebase.auth.FirebaseAuth; import java.util.HashMap;import java.util.List; public class AdapterChatList extends RecyclerView.Adapter<AdapterChatList.Myholder> { Context context; FirebaseAuth firebaseAuth; String uid; public AdapterChatList(Context context, List<ModelUsers> users) { this.context = context; this.usersList = users; lastMessageMap = new HashMap<>(); firebaseAuth = FirebaseAuth.getInstance(); uid = firebaseAuth.getUid(); } List<ModelUsers> usersList; private HashMap<String, String> lastMessageMap; @NonNull @Override public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_chatlist, parent, false); return new Myholder(view); } @Override public void onBindViewHolder(@NonNull Myholder holder, final int position) { final String hisuid = usersList.get(position).getUid(); String userimage = usersList.get(position).getImage(); String username = usersList.get(position).getName(); String lastmess = lastMessageMap.get(hisuid); holder.name.setText(username); holder.block.setImageResource(R.drawable.ic_unblock); // if no last message then Hide the layout if (lastmess == null || lastmess.equals("default")) { holder.lastmessage.setVisibility(View.GONE); } else { holder.lastmessage.setVisibility(View.VISIBLE); holder.lastmessage.setText(lastmess); } try { // loading profile pic of user Glide.with(context).load(userimage).into(holder.profile); } catch (Exception e) { } // redirecting to chat activity on item click holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ChatActivity.class); // putting uid of user in extras intent.putExtra("uid", hisuid); context.startActivity(intent); } }); } // setting last message sent by users. public void setlastMessageMap(String userId, String lastmessage) { lastMessageMap.put(userId, lastmessage); } @Override public int getItemCount() { return usersList.size(); } class Myholder extends RecyclerView.ViewHolder { ImageView profile, status, block, seen; TextView name, lastmessage; public Myholder(@NonNull View itemView) { super(itemView); profile = itemView.findViewById(R.id.profileimage); status = itemView.findViewById(R.id.onlinestatus); name = itemView.findViewById(R.id.nameonline); lastmessage = itemView.findViewById(R.id.lastmessge); block = itemView.findViewById(R.id.blocking); seen = itemView.findViewById(R.id.seen); } }} Step 3: Working with the fragment_chatlist.xml file Showing all the users using the recycler view. XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ChatListFragment"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/chatlistrecycle" android:layout_width="match_parent" android:layout_height="match_parent" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" tools:listitem="@layout/row_chatlist" /> </FrameLayout> Step 4: Working with the ChatlistFragment.java file Here we are showing all the users to whom we have sent messages. This is how we will get the last message of the current user. If the message type is images then simply set the last message as “Sent a photo”. if(chat.getReceiver().equals(firebaseUser.getUid())&& chat.getSender().equals(uid)|| chat.getReceiver().equals(uid)&& chat.getSender().equals(firebaseUser.getUid())){ if(chat.getType().equals("images")){ lastmess="Sent a Photo"; } else { lastmess = chat.getMessage(); } } Below is the code for the ChatlistFragment.java file. Java package com.example.socialmediaapp; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.util.ArrayList;import java.util.List; /** * A simple {@link Fragment} subclass. */public class ChatListFragment extends Fragment { FirebaseAuth firebaseAuth; RecyclerView recyclerView; List<ModelChatList> chatListList; List<ModelUsers> usersList; DatabaseReference reference; FirebaseUser firebaseUser; AdapterChatList adapterChatList; List<ModelChat> chatList; public ChatListFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_chat_list, container, false); firebaseAuth = FirebaseAuth.getInstance(); // getting current user firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); recyclerView = view.findViewById(R.id.chatlistrecycle); chatListList = new ArrayList<>(); chatList = new ArrayList<>(); reference = FirebaseDatabase.getInstance().getReference("ChatList").child(firebaseUser.getUid()); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { chatListList.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { ModelChatList modelChatList = ds.getValue(ModelChatList.class); if (!modelChatList.getId().equals(firebaseUser.getUid())) { chatListList.add(modelChatList); } } loadChats(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); return view; } // loading the user chat layout using chat node private void loadChats() { usersList = new ArrayList<>(); reference = FirebaseDatabase.getInstance().getReference("Users"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { usersList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelUsers user = dataSnapshot1.getValue(ModelUsers.class); for (ModelChatList chatList : chatListList) { if (user.getUid() != null && user.getUid().equals(chatList.getId())) { usersList.add(user); break; } } adapterChatList = new AdapterChatList(getActivity(), usersList); recyclerView.setAdapter(adapterChatList); // getting last message of the user for (int i = 0; i < usersList.size(); i++) { lastMessage(usersList.get(i).getUid()); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void lastMessage(final String uid) { DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Chats"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String lastmess = "default"; for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelChat chat = dataSnapshot1.getValue(ModelChat.class); if (chat == null) { continue; } String sender = chat.getSender(); String receiver = chat.getReceiver(); if (sender == null || receiver == null) { continue; } // checking for the type of message if // message type is image then set // last message as sent a photo if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(uid) || chat.getReceiver().equals(uid) && chat.getSender().equals(firebaseUser.getUid())) { if (chat.getType().equals("images")) { lastmess = "Sent a Photo"; } else { lastmess = chat.getMessage(); } } } adapterChatList.setlastMessageMap(uid, lastmess); adapterChatList.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { setHasOptionsMenu(true); super.onCreate(savedInstanceState); } } Output: For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing Below is the file structure after performing these operations: surinderdawra388 rkbhola5 Firebase Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2022" }, { "code": null, "e": 179, "s": 28, "text": "This is the Part 14 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:" }, { "code": null, "e": 245, "s": 179, "text": "We are going to Create a Layout for chat & Send Messages in Chat." }, { "code": null, "e": 291, "s": 245, "text": "A user can send either a Message or an Image." }, { "code": null, "e": 350, "s": 291, "text": "A user can send an image either using a camera or gallery." }, { "code": null, "e": 476, "s": 350, "text": "Firstly a request for permission will be asked to send an image using a gallery or after clicking the image using the camera." }, { "code": null, "e": 581, "s": 476, "text": "If permission is given then the user can send the image, or it will again request for asking permission." }, { "code": null, "e": 673, "s": 581, "text": "Step 1: Create two new layout resource files and name them row_chat_left and row_chat_right" }, { "code": null, "e": 949, "s": 673, "text": "Working with the row_chat_left.xml file. The received message will be on the left side. Similarly, Working with the row_chat_right.xml file. The message sends to the user will be on the right side. Below is the code for the row_chat_left.xml file and row_chat_right.xml file." }, { "code": null, "e": 953, "s": 949, "text": "XML" }, { "code": null, "e": 957, "s": 953, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/msglayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:padding=\"10dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/profilec\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:src=\"@drawable/profile_image\" app:civ_border_color=\"@null\" /> <TextView android:id=\"@+id/msgc\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:background=\"@drawable/bg_receiver\" android:padding=\"15dp\" android:text=\"His Message\" android:textColor=\"@color/colorBlack\" android:textSize=\"16sp\" android:visibility=\"gone\" /> <ImageView android:id=\"@+id/images\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:adjustViewBounds=\"true\" android:background=\"@drawable/bg_receiver\" android:padding=\"15dp\" android:scaleType=\"fitCenter\" android:src=\"@drawable/ic_images\" /> <TextView android:id=\"@+id/timetv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"02/01/1990 06:19PM\" android:textColor=\"@color/colorBlack\" android:textSize=\"12sp\" /> </LinearLayout> <TextView android:id=\"@+id/isSeen\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"end\" android:text=\"Delivered\" android:textAlignment=\"textEnd\" android:visibility=\"gone\" /> </LinearLayout>", "e": 3085, "s": 957, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/msglayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:padding=\"10dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/profilec\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:src=\"@drawable/profile_image\" android:visibility=\"gone\" app:civ_border_color=\"@null\" /> <TextView android:id=\"@+id/timetv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"02/01/1990 06:19PM\" android:textColor=\"@color/colorBlack\" android:textSize=\"12sp\" /> <TextView android:id=\"@+id/msgc\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_toEndOf=\"@id/timetv\" android:background=\"@drawable/bg_sender\" android:padding=\"15dp\" android:text=\"His Message\" android:textColor=\"@color/colorBlack\" android:textSize=\"16sp\" /> <ImageView android:id=\"@+id/images\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_alignParentEnd=\"true\" android:adjustViewBounds=\"true\" android:background=\"@drawable/bg_sender\" android:padding=\"15dp\" android:scaleType=\"fitCenter\" android:src=\"@drawable/ic_images\" /> </RelativeLayout> <TextView android:id=\"@+id/isSeen\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"end\" android:text=\"Delivered\" android:textAlignment=\"textEnd\" /> </LinearLayout>", "e": 5287, "s": 3085, "text": null }, { "code": null, "e": 5337, "s": 5287, "text": " Step 2: Working with the activity_chat.xml file " }, { "code": null, "e": 5548, "s": 5337, "text": "Here In the RecyclerView, we will be showing all the messages. In the TextView user will type the message and using the send button user will send the message. Below is the code for the activity_chat.xml file. " }, { "code": null, "e": 5552, "s": 5548, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".ChatActivity\"> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"?android:attr/actionBarSize\" android:background=\"@color/colorPrimaryDark\" android:theme=\"@style/ThemeOverlay.AppCompat.Dark.ActionBar\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/profiletv\" android:layout_width=\"35dp\" android:layout_height=\"35dp\" android:scaleType=\"centerCrop\" android:src=\"@drawable/profile_image\" app:civ_circle_background_color=\"@color/colorPrimaryDark\" /> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginLeft=\"20dp\" android:layout_weight=\"1\" android:gravity=\"center\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/nameptv\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"HisName\" android:textColor=\"@color/colorWhite\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/onlinetv\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Online\" android:textColor=\"@color/colorWhite\" android:textStyle=\"bold\" /> </LinearLayout> <ImageView android:id=\"@+id/block\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:layout_marginEnd=\"5dp\" android:src=\"@drawable/ic_unblock\" /> </LinearLayout> </androidx.appcompat.widget.Toolbar> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/chatrecycle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_above=\"@id/chatlayout\" android:layout_below=\"@id/toolbar\" /> <LinearLayout android:id=\"@+id/chatlayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:background=\"@color/colorWhite\" android:gravity=\"center\" android:orientation=\"horizontal\"> <ImageButton android:id=\"@+id/attachbtn\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:background=\"@null\" android:src=\"@drawable/ic_iattach\" /> <EditText android:id=\"@+id/messaget\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:background=\"@null\" android:hint=\"Start Typing\" android:inputType=\"textCapSentences|textMultiLine\" android:padding=\"15dp\" /> <ImageButton android:id=\"@+id/sendmsg\" android:layout_width=\"40dp\" android:layout_height=\"40dp\" android:background=\"@null\" android:src=\"@drawable/send_message\" /> </LinearLayout> </RelativeLayout>", "e": 9649, "s": 5552, "text": null }, { "code": null, "e": 9697, "s": 9649, "text": " Step 3: Working with the row_chatlist.xml file" }, { "code": null, "e": 9818, "s": 9697, "text": "Create another layout resource file and name the file as row_chatlist. Below is the code for the row_chatlist.xml file. " }, { "code": null, "e": 9822, "s": 9818, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" app:contentPadding=\"3dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/profileimage\" android:layout_width=\"70dp\" android:layout_height=\"70dp\" android:src=\"@drawable/profile_image\" /> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/onlinestatus\" android:layout_width=\"25dp\" android:layout_height=\"25dp\" /> <TextView android:id=\"@+id/nameonline\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"4dp\" android:layout_toEndOf=\"@id/profileimage\" android:layout_toRightOf=\"@id/profileimage\" android:text=\"His Name\" android:textColor=\"@color/colorBlack\" android:textSize=\"18sp\" /> <TextView android:id=\"@+id/lastmessge\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/nameonline\" android:layout_marginStart=\"4dp\" android:layout_toEndOf=\"@id/profileimage\" android:layout_toRightOf=\"@id/profileimage\" android:maxLines=\"2\" android:text=\"Last Message\" android:textColor=\"@color/colorBlack\" /> <ImageView android:id=\"@+id/blocking\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_gravity=\"center_vertical\" android:src=\"@drawable/ic_unblock\" /> <ImageView android:id=\"@+id/seen\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/blocking\" android:layout_alignParentEnd=\"true\" android:layout_gravity=\"center_vertical\" android:src=\"@drawable/ic_unblock\" /> </RelativeLayout> </androidx.cardview.widget.CardView>", "e": 12283, "s": 9822, "text": null }, { "code": null, "e": 12330, "s": 12283, "text": " Step 4: Working with the ModelChat.java file " }, { "code": null, "e": 12424, "s": 12330, "text": "Created this class to initialize the key so that we can retrieve the value of the key later. " }, { "code": null, "e": 12429, "s": 12424, "text": "Java" }, { "code": "package com.example.socialmediaapp; public class ModelChat { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public boolean isDilihat() { return dilihat; } public void setDilihat(boolean dilihat) { this.dilihat = dilihat; } String receiver; public ModelChat() { } String sender; public String getType() { return type; } public void setType(String type) { this.type = type; } public ModelChat(String message, String receiver, String sender, String type, String timestamp, boolean dilihat) { this.message = message; this.receiver = receiver; this.sender = sender; this.type = type; this.timestamp = timestamp; this.dilihat = dilihat; } String type; String timestamp; boolean dilihat;}", "e": 13798, "s": 12429, "text": null }, { "code": null, "e": 13846, "s": 13798, "text": " Step 5: Working with the AdpaterChat.java file" }, { "code": null, "e": 13955, "s": 13846, "text": "Create a new java class and name the class as AdpaterChat. Below is the code for the AdpaterChat.java file. " }, { "code": null, "e": 13960, "s": 13955, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.text.format.DateFormat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener; import java.util.Calendar;import java.util.List;import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; public class AdapterChat extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterChat.Myholder> { private static final int MSG_TYPE_LEFT = 0; private static final int MSG_TYPR_RIGHT = 1; Context context; List<ModelChat> list; String imageurl; FirebaseUser firebaseUser; public AdapterChat(Context context, List<ModelChat> list, String imageurl) { this.context = context; this.list = list; this.imageurl = imageurl; } @NonNull @Override public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == MSG_TYPE_LEFT) { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, parent, false); return new Myholder(view); } else { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, parent, false); return new Myholder(view); } } @Override public void onBindViewHolder(@NonNull Myholder holder, final int position) { String message = list.get(position).getMessage(); String timeStamp = list.get(position).getTimestamp(); String type = list.get(position).getType(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(timeStamp)); String timedate = DateFormat.format(\"dd/MM/yyyy hh:mm aa\", calendar).toString(); holder.message.setText(message); holder.time.setText(timedate); try { Glide.with(context).load(imageurl).into(holder.image); } catch (Exception e) { } if (type.equals(\"text\")) { holder.message.setVisibility(View.VISIBLE); holder.mimage.setVisibility(View.GONE); holder.message.setText(message); } else { holder.message.setVisibility(View.GONE); holder.mimage.setVisibility(View.VISIBLE); Glide.with(context).load(message).into(holder.mimage); } holder.msglayput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(\"Delete Message\"); builder.setMessage(\"Are You Sure To Delete This Message\"); builder.setPositiveButton(\"Delete\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteMsg(position); } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } }); } private void deleteMsg(int position) { final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); String msgtimestmp = list.get(position).getTimestamp(); DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child(\"Chats\"); Query query = dbref.orderByChild(\"timestamp\").equalTo(msgtimestmp); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { if (dataSnapshot1.child(\"sender\").getValue().equals(myuid)) { // any two of below can be used dataSnapshot1.getRef().removeValue(); /* HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"message\", \"This Message Was Deleted\"); dataSnapshot1.getRef().updateChildren(hashMap); Toast.makeText(context,\"Message Deleted.....\",Toast.LENGTH_LONG).show();*/ } else { Toast.makeText(context, \"you can delete only your msg....\", Toast.LENGTH_LONG).show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return list.size(); } @Override public int getItemViewType(int position) { firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (list.get(position).getSender().equals(firebaseUser.getUid())) { return MSG_TYPR_RIGHT; } else { return MSG_TYPE_LEFT; } } class Myholder extends RecyclerView.ViewHolder { CircleImageView image; ImageView mimage; TextView message, time, isSee; LinearLayout msglayput; public Myholder(@NonNull View itemView) { super(itemView); image = itemView.findViewById(R.id.profilec); message = itemView.findViewById(R.id.msgc); time = itemView.findViewById(R.id.timetv); isSee = itemView.findViewById(R.id.isSeen); msglayput = itemView.findViewById(R.id.msglayout); mimage = itemView.findViewById(R.id.images); } }}", "e": 20355, "s": 13960, "text": null }, { "code": null, "e": 20404, "s": 20355, "text": " Step 6: Working with the ChatActivity.java file" }, { "code": null, "e": 20526, "s": 20404, "text": "We are Reading the user message from “Chats” Node in Firebase. Every time data changes this data will change accordingly " }, { "code": null, "e": 20641, "s": 20526, "text": "chatList=new ArrayList<>();\nDatabaseReference dbref= FirebaseDatabase.getInstance().getReference().child(\"Chats\");" }, { "code": null, "e": 20697, "s": 20641, "text": "Loading the Data setting data value using adapter chat " }, { "code": null, "e": 21320, "s": 20697, "text": "ModelChat modelChat=dataSnapshot1.getValue(ModelChat.class);\n if(modelChat.getSender().equals(myuid)&&\n modelChat.getReceiver().equals(uid)||\n modelChat.getReceiver().equals(myuid)\n && modelChat.getSender().equals(uid)){\n chatList.add(modelChat);//add the chat in chatlist\n }\n adapterChat=new AdapterChat(ChatActivity.this,chatList,image);\n adapterChat.notifyDataSetChanged();\n recyclerView.setAdapter(adapterChat);" }, { "code": null, "e": 21433, "s": 21320, "text": "Sending Messages in Chat Reference node value. Here is how we are saving data in the Firebase Realtime database " }, { "code": null, "e": 21941, "s": 21433, "text": "DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();\n String timestamp=String.valueOf(System.currentTimeMillis());\n HashMap<String,Object> hashMap=new HashMap<>();\n hashMap.put(\"sender\",myuid);\n hashMap.put(\"receiver\",uid);\n hashMap.put(\"message\",message);\n hashMap.put(\"timestamp\",timestamp);\n hashMap.put(\"dilihat\",false);\n hashMap.put(\"type\",\"text\");\n databaseReference.child(\"Chats\").push().setValue(hashMap);" }, { "code": null, "e": 21992, "s": 21941, "text": "Below is the code for the ChatActivity.java file. " }, { "code": null, "e": 21997, "s": 21992, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.Manifest;import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.text.TextUtils;import android.text.format.DateFormat;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar;import androidx.core.content.ContextCompat;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.StorageReference;import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List; public class ChatActivity extends AppCompatActivity { Toolbar toolbar; RecyclerView recyclerView; ImageView profile, block; TextView name, userstatus; EditText msg; ImageButton send, attach; FirebaseAuth firebaseAuth; String uid, myuid, image; ValueEventListener valueEventListener; List<ModelChat> chatList; AdapterChat adapterChat; private static final int IMAGEPICK_GALLERY_REQUEST = 300; private static final int IMAGE_PICKCAMERA_REQUEST = 400; private static final int CAMERA_REQUEST = 100; private static final int STORAGE_REQUEST = 200; String cameraPermission[]; String storagePermission[]; Uri imageuri = null; FirebaseDatabase firebaseDatabase; DatabaseReference users; boolean notify = false; boolean isBlocked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); firebaseAuth = FirebaseAuth.getInstance(); // initialise the text views and layouts profile = findViewById(R.id.profiletv); name = findViewById(R.id.nameptv); userstatus = findViewById(R.id.onlinetv); msg = findViewById(R.id.messaget); send = findViewById(R.id.sendmsg); attach = findViewById(R.id.attachbtn); block = findViewById(R.id.block); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setStackFromEnd(true); recyclerView = findViewById(R.id.chatrecycle); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(linearLayoutManager); uid = getIntent().getStringExtra(\"uid\"); // getting uid of another user using intent firebaseDatabase = FirebaseDatabase.getInstance(); // initialising permissions cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; checkUserStatus(); users = firebaseDatabase.getReference(\"Users\"); attach.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showImagePicDialog(); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notify = true; String message = msg.getText().toString().trim(); if (TextUtils.isEmpty(message)) {//if empty Toast.makeText(ChatActivity.this, \"Please Write Something Here\", Toast.LENGTH_LONG).show(); } else { sendmessage(message); } msg.setText(\"\"); } }); Query userquery = users.orderByChild(\"uid\").equalTo(uid); userquery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // retrieve user data for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String nameh = \"\" + dataSnapshot1.child(\"name\").getValue(); image = \"\" + dataSnapshot1.child(\"image\").getValue(); String onlinestatus = \"\" + dataSnapshot1.child(\"onlineStatus\").getValue(); String typingto = \"\" + dataSnapshot1.child(\"typingTo\").getValue(); if (typingto.equals(myuid)) {// if user is typing to my chat userstatus.setText(\"Typing....\");// type status as typing } else { if (onlinestatus.equals(\"online\")) { userstatus.setText(onlinestatus); } else { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(onlinestatus)); String timedate = DateFormat.format(\"dd/MM/yyyy hh:mm aa\", calendar).toString(); userstatus.setText(\"Last Seen:\" + timedate); } } name.setText(nameh); try { Glide.with(ChatActivity.this).load(image).placeholder(R.drawable.profile_image).into(profile); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); readMessages(); } @Override protected void onPause() { super.onPause(); String timestamp = String.valueOf(System.currentTimeMillis()); checkOnlineStatus(timestamp); checkTypingStatus(\"noOne\"); } @Override protected void onResume() { checkOnlineStatus(\"online\"); super.onResume(); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); } private void checkOnlineStatus(String status) { // check online status DatabaseReference dbref = FirebaseDatabase.getInstance().getReference(\"Users\").child(myuid); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"onlineStatus\", status); dbref.updateChildren(hashMap); } private void checkTypingStatus(String typing) { DatabaseReference dbref = FirebaseDatabase.getInstance().getReference(\"Users\").child(myuid); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"typingTo\", typing); dbref.updateChildren(hashMap); } @Override protected void onStart() { checkUserStatus(); checkOnlineStatus(\"online\"); super.onStart(); } private void readMessages() { // show message after retrieving data chatList = new ArrayList<>(); DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child(\"Chats\"); dbref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { chatList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelChat modelChat = dataSnapshot1.getValue(ModelChat.class); if (modelChat.getSender().equals(myuid) && modelChat.getReceiver().equals(uid) || modelChat.getReceiver().equals(myuid) && modelChat.getSender().equals(uid)) { chatList.add(modelChat); // add the chat in chatlist } adapterChat = new AdapterChat(ChatActivity.this, chatList, image); adapterChat.notifyDataSetChanged(); recyclerView.setAdapter(adapterChat); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void showImagePicDialog() { String options[] = {\"Camera\", \"Gallery\"}; AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this); builder.setTitle(\"Pick Image From\"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { if (!checkCameraPermission()) { // if permission is not given requestCameraPermission(); // request for permission } else { pickFromCamera(); // if already access granted then click } } else if (which == 1) { if (!checkStoragePermission()) { // if permission is not given requestStoragePermission(); // request for permission } else { pickFromGallery(); // if already access granted then pick } } } }); builder.create().show(); } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // request for permission if not given switch (requestCode) { case CAMERA_REQUEST: { if (grantResults.length > 0) { boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (camera_accepted && writeStorageaccepted) { pickFromCamera(); // if access granted then click } else { Toast.makeText(this, \"Please Enable Camera and Storage Permissions\", Toast.LENGTH_LONG).show(); } } } break; case STORAGE_REQUEST: { if (grantResults.length > 0) { boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeStorageaccepted) { pickFromGallery(); // if access granted then pick } else { Toast.makeText(this, \"Please Enable Storage Permissions\", Toast.LENGTH_LONG).show(); } } } break; } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == RESULT_OK) { if (requestCode == IMAGEPICK_GALLERY_REQUEST) { imageuri = data.getData(); // get image data to upload try { sendImageMessage(imageuri); } catch (IOException e) { e.printStackTrace(); } } if (requestCode == IMAGE_PICKCAMERA_REQUEST) { try { sendImageMessage(imageuri); } catch (IOException e) { e.printStackTrace(); } } } super.onActivityResult(requestCode, resultCode, data); } private void sendImageMessage(Uri imageuri) throws IOException { notify = true; final ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage(\"Sending Image\"); dialog.show(); // If we are sending image as a message // then we need to find the url of // image after uploading the // image in firebase storage final String timestamp = \"\" + System.currentTimeMillis(); String filepathandname = \"ChatImages/\" + \"post\" + timestamp; // filename Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageuri); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, arrayOutputStream); // compressing the image using bitmap final byte[] data = arrayOutputStream.toByteArray(); StorageReference ref = FirebaseStorage.getInstance().getReference().child(filepathandname); ref.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { dialog.dismiss(); Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()) ; String downloadUri = uriTask.getResult().toString(); // getting url if task is successful if (uriTask.isSuccessful()) { DatabaseReference re = FirebaseDatabase.getInstance().getReference(); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"sender\", myuid); hashMap.put(\"receiver\", uid); hashMap.put(\"message\", downloadUri); hashMap.put(\"timestamp\", timestamp); hashMap.put(\"dilihat\", false); hashMap.put(\"type\", \"images\"); re.child(\"Chats\").push().setValue(hashMap); // push in firebase using unique id final DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference(\"ChatList\").child(uid).child(myuid); ref1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref1.child(\"id\").setValue(myuid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); final DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference(\"ChatList\").child(myuid).child(uid); ref2.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref2.child(\"id\").setValue(uid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } private Boolean checkCameraPermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } private void requestCameraPermission() { requestPermissions(cameraPermission, CAMERA_REQUEST); } private void pickFromCamera() { ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.Images.Media.TITLE, \"Temp_pic\"); contentValues.put(MediaStore.Images.Media.DESCRIPTION, \"Temp Description\"); imageuri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); camerIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri); startActivityForResult(camerIntent, IMAGE_PICKCAMERA_REQUEST); } private void pickFromGallery() { Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType(\"image/*\"); startActivityForResult(galleryIntent, IMAGEPICK_GALLERY_REQUEST); } private Boolean checkStoragePermission() { boolean result = ContextCompat.checkSelfPermission(ChatActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } private void requestStoragePermission() { requestPermissions(storagePermission, STORAGE_REQUEST); } private void sendmessage(final String message) { // creating a reference to store data in firebase // We will be storing data using current time in \"Chatlist\" // and we are pushing data using unique id in \"Chats\" DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(); String timestamp = String.valueOf(System.currentTimeMillis()); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"sender\", myuid); hashMap.put(\"receiver\", uid); hashMap.put(\"message\", message); hashMap.put(\"timestamp\", timestamp); hashMap.put(\"dilihat\", false); hashMap.put(\"type\", \"text\"); databaseReference.child(\"Chats\").push().setValue(hashMap); final DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference(\"ChatList\").child(uid).child(myuid); ref1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref1.child(\"id\").setValue(myuid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); final DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference(\"ChatList\").child(myuid).child(uid); ref2.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.exists()) { ref2.child(\"id\").setValue(uid); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.logout) { firebaseAuth.signOut(); checkUserStatus(); } return super.onOptionsItemSelected(item); } private void checkUserStatus() { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { myuid = user.getUid(); } }}", "e": 41705, "s": 21997, "text": null }, { "code": null, "e": 41715, "s": 41705, "text": " Output: " }, { "code": null, "e": 41763, "s": 41715, "text": "Step 1: Working with the ModelChatlist.xml file" }, { "code": null, "e": 41819, "s": 41763, "text": "Getting the id of users to whom we have sent messages. " }, { "code": null, "e": 41824, "s": 41819, "text": "Java" }, { "code": "package com.example.socialmediaapp; class ModelChatList { public String getId() { return id; } public void setId(String id) { this.id = id; } public ModelChatList() { } public ModelChatList(String id) { this.id = id; } String id;}", "e": 42108, "s": 41824, "text": null }, { "code": null, "e": 42160, "s": 42108, "text": " Step 2: Working with the AdapterChatList.java file" }, { "code": null, "e": 42218, "s": 42160, "text": "Showing the users and the last message sent in the chat. " }, { "code": null, "e": 42223, "s": 42218, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.firebase.auth.FirebaseAuth; import java.util.HashMap;import java.util.List; public class AdapterChatList extends RecyclerView.Adapter<AdapterChatList.Myholder> { Context context; FirebaseAuth firebaseAuth; String uid; public AdapterChatList(Context context, List<ModelUsers> users) { this.context = context; this.usersList = users; lastMessageMap = new HashMap<>(); firebaseAuth = FirebaseAuth.getInstance(); uid = firebaseAuth.getUid(); } List<ModelUsers> usersList; private HashMap<String, String> lastMessageMap; @NonNull @Override public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_chatlist, parent, false); return new Myholder(view); } @Override public void onBindViewHolder(@NonNull Myholder holder, final int position) { final String hisuid = usersList.get(position).getUid(); String userimage = usersList.get(position).getImage(); String username = usersList.get(position).getName(); String lastmess = lastMessageMap.get(hisuid); holder.name.setText(username); holder.block.setImageResource(R.drawable.ic_unblock); // if no last message then Hide the layout if (lastmess == null || lastmess.equals(\"default\")) { holder.lastmessage.setVisibility(View.GONE); } else { holder.lastmessage.setVisibility(View.VISIBLE); holder.lastmessage.setText(lastmess); } try { // loading profile pic of user Glide.with(context).load(userimage).into(holder.profile); } catch (Exception e) { } // redirecting to chat activity on item click holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ChatActivity.class); // putting uid of user in extras intent.putExtra(\"uid\", hisuid); context.startActivity(intent); } }); } // setting last message sent by users. public void setlastMessageMap(String userId, String lastmessage) { lastMessageMap.put(userId, lastmessage); } @Override public int getItemCount() { return usersList.size(); } class Myholder extends RecyclerView.ViewHolder { ImageView profile, status, block, seen; TextView name, lastmessage; public Myholder(@NonNull View itemView) { super(itemView); profile = itemView.findViewById(R.id.profileimage); status = itemView.findViewById(R.id.onlinestatus); name = itemView.findViewById(R.id.nameonline); lastmessage = itemView.findViewById(R.id.lastmessge); block = itemView.findViewById(R.id.blocking); seen = itemView.findViewById(R.id.seen); } }}", "e": 45617, "s": 42223, "text": null }, { "code": null, "e": 45670, "s": 45617, "text": " Step 3: Working with the fragment_chatlist.xml file" }, { "code": null, "e": 45718, "s": 45670, "text": "Showing all the users using the recycler view. " }, { "code": null, "e": 45722, "s": 45718, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".ChatListFragment\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/chatlistrecycle\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:layoutManager=\"androidx.recyclerview.widget.LinearLayoutManager\" tools:listitem=\"@layout/row_chatlist\" /> </FrameLayout>", "e": 46371, "s": 45722, "text": null }, { "code": null, "e": 46424, "s": 46371, "text": " Step 4: Working with the ChatlistFragment.java file" }, { "code": null, "e": 46634, "s": 46424, "text": "Here we are showing all the users to whom we have sent messages. This is how we will get the last message of the current user. If the message type is images then simply set the last message as “Sent a photo”. " }, { "code": null, "e": 47170, "s": 46634, "text": "if(chat.getReceiver().equals(firebaseUser.getUid())&&\n chat.getSender().equals(uid)||\n chat.getReceiver().equals(uid)&&\n chat.getSender().equals(firebaseUser.getUid())){\n if(chat.getType().equals(\"images\")){\n lastmess=\"Sent a Photo\";\n }\n else {\n lastmess = chat.getMessage();\n }\n }" }, { "code": null, "e": 47225, "s": 47170, "text": "Below is the code for the ChatlistFragment.java file. " }, { "code": null, "e": 47230, "s": 47225, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.util.ArrayList;import java.util.List; /** * A simple {@link Fragment} subclass. */public class ChatListFragment extends Fragment { FirebaseAuth firebaseAuth; RecyclerView recyclerView; List<ModelChatList> chatListList; List<ModelUsers> usersList; DatabaseReference reference; FirebaseUser firebaseUser; AdapterChatList adapterChatList; List<ModelChat> chatList; public ChatListFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_chat_list, container, false); firebaseAuth = FirebaseAuth.getInstance(); // getting current user firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); recyclerView = view.findViewById(R.id.chatlistrecycle); chatListList = new ArrayList<>(); chatList = new ArrayList<>(); reference = FirebaseDatabase.getInstance().getReference(\"ChatList\").child(firebaseUser.getUid()); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { chatListList.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { ModelChatList modelChatList = ds.getValue(ModelChatList.class); if (!modelChatList.getId().equals(firebaseUser.getUid())) { chatListList.add(modelChatList); } } loadChats(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); return view; } // loading the user chat layout using chat node private void loadChats() { usersList = new ArrayList<>(); reference = FirebaseDatabase.getInstance().getReference(\"Users\"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { usersList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelUsers user = dataSnapshot1.getValue(ModelUsers.class); for (ModelChatList chatList : chatListList) { if (user.getUid() != null && user.getUid().equals(chatList.getId())) { usersList.add(user); break; } } adapterChatList = new AdapterChatList(getActivity(), usersList); recyclerView.setAdapter(adapterChatList); // getting last message of the user for (int i = 0; i < usersList.size(); i++) { lastMessage(usersList.get(i).getUid()); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void lastMessage(final String uid) { DatabaseReference ref = FirebaseDatabase.getInstance().getReference(\"Chats\"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String lastmess = \"default\"; for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelChat chat = dataSnapshot1.getValue(ModelChat.class); if (chat == null) { continue; } String sender = chat.getSender(); String receiver = chat.getReceiver(); if (sender == null || receiver == null) { continue; } // checking for the type of message if // message type is image then set // last message as sent a photo if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(uid) || chat.getReceiver().equals(uid) && chat.getSender().equals(firebaseUser.getUid())) { if (chat.getType().equals(\"images\")) { lastmess = \"Sent a Photo\"; } else { lastmess = chat.getMessage(); } } } adapterChatList.setlastMessageMap(uid, lastmess); adapterChatList.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { setHasOptionsMenu(true); super.onCreate(savedInstanceState); } }", "e": 53041, "s": 47230, "text": null }, { "code": null, "e": 53051, "s": 53041, "text": " Output: " }, { "code": null, "e": 53210, "s": 53051, "text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing" }, { "code": null, "e": 53273, "s": 53210, "text": "Below is the file structure after performing these operations:" }, { "code": null, "e": 53292, "s": 53275, "text": "surinderdawra388" }, { "code": null, "e": 53301, "s": 53292, "text": "rkbhola5" }, { "code": null, "e": 53310, "s": 53301, "text": "Firebase" }, { "code": null, "e": 53318, "s": 53310, "text": "Android" }, { "code": null, "e": 53323, "s": 53318, "text": "Java" }, { "code": null, "e": 53328, "s": 53323, "text": "Java" }, { "code": null, "e": 53336, "s": 53328, "text": "Android" } ]
Python – Create window button in GTK+ 3
30 Jun, 2021 GTK+ 3 is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License. Along with Qt, it is one of the most popular toolkits for the Wayland and X11 windowing systems. Let’s see how to create a window and a button using GTK+ 3.Follow the below steps: import GTK+ 3 moduleCreate the main window.Create Button. import GTK+ 3 module Create the main window. Create Button. We have to import the Gtk module to be able to access GTK+’s classes and functions.Note: In IDEs like Pycharm we can install a package named PyGObject in order to use GTK+ 3.Code #1: Create an empty 200 x 200-pixel window. Python3 import gi # Since a system can have multiple versions# of GTK + installed, we want to make# sure that we are importing GTK + 3.gi.require_version("Gtk", "3.0") from gi.repository import Gtk # Creates an empty window.window = Gtk.Window() # Connecting to the window’s delete event# to ensure that the application is terminated# whenever we click close button window.connect("destroy", Gtk.main_quit)# Display the window.window.show_all() Gtk.main() Output: Code #2: Create a button Python3 import gi gi.require_version("Gtk", "3.0")from gi.repository import Gtk # Define our own newWindow class.class newWindow(Gtk.Window): def __init__(self): # Call the constructor of the super class. # Set the value of the property title to Geeks for Geeks. Gtk.Window.__init__(self, title ="Geeks for Geeks") # Create a button widget, connect to its clicked signal # and add it as child to the top-level window. self.button = Gtk.Button(label ="Click Here") self.button.connect("clicked", self.on_button_clicked) self.add(self.button) # When we click on the button this method # will be called def on_button_clicked(self, widget): print("Geeks for Geeks") win = newWindow()win.connect("destroy", Gtk.main_quit)win.show_all()Gtk.main() Output: amateurcoderrrrrrr Python-GTK Python-gui Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 417, "s": 52, "text": "GTK+ 3 is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License. Along with Qt, it is one of the most popular toolkits for the Wayland and X11 windowing systems. Let’s see how to create a window and a button using GTK+ 3.Follow the below steps: " }, { "code": null, "e": 475, "s": 417, "text": "import GTK+ 3 moduleCreate the main window.Create Button." }, { "code": null, "e": 496, "s": 475, "text": "import GTK+ 3 module" }, { "code": null, "e": 520, "s": 496, "text": "Create the main window." }, { "code": null, "e": 535, "s": 520, "text": "Create Button." }, { "code": null, "e": 760, "s": 535, "text": "We have to import the Gtk module to be able to access GTK+’s classes and functions.Note: In IDEs like Pycharm we can install a package named PyGObject in order to use GTK+ 3.Code #1: Create an empty 200 x 200-pixel window. " }, { "code": null, "e": 768, "s": 760, "text": "Python3" }, { "code": "import gi # Since a system can have multiple versions# of GTK + installed, we want to make# sure that we are importing GTK + 3.gi.require_version(\"Gtk\", \"3.0\") from gi.repository import Gtk # Creates an empty window.window = Gtk.Window() # Connecting to the window’s delete event# to ensure that the application is terminated# whenever we click close button window.connect(\"destroy\", Gtk.main_quit)# Display the window.window.show_all() Gtk.main()", "e": 1216, "s": 768, "text": null }, { "code": null, "e": 1226, "s": 1216, "text": "Output: " }, { "code": null, "e": 1253, "s": 1226, "text": "Code #2: Create a button " }, { "code": null, "e": 1261, "s": 1253, "text": "Python3" }, { "code": "import gi gi.require_version(\"Gtk\", \"3.0\")from gi.repository import Gtk # Define our own newWindow class.class newWindow(Gtk.Window): def __init__(self): # Call the constructor of the super class. # Set the value of the property title to Geeks for Geeks. Gtk.Window.__init__(self, title =\"Geeks for Geeks\") # Create a button widget, connect to its clicked signal # and add it as child to the top-level window. self.button = Gtk.Button(label =\"Click Here\") self.button.connect(\"clicked\", self.on_button_clicked) self.add(self.button) # When we click on the button this method # will be called def on_button_clicked(self, widget): print(\"Geeks for Geeks\") win = newWindow()win.connect(\"destroy\", Gtk.main_quit)win.show_all()Gtk.main()", "e": 2073, "s": 1261, "text": null }, { "code": null, "e": 2083, "s": 2073, "text": "Output: " }, { "code": null, "e": 2104, "s": 2085, "text": "amateurcoderrrrrrr" }, { "code": null, "e": 2115, "s": 2104, "text": "Python-GTK" }, { "code": null, "e": 2126, "s": 2115, "text": "Python-gui" }, { "code": null, "e": 2133, "s": 2126, "text": "Python" }, { "code": null, "e": 2149, "s": 2133, "text": "Write From Home" } ]
LocalDate getMonthValue() method in Java with Examples
29 Nov, 2018 The getMonthValue() method of LocalDate class in Java gets the month-of-year field from 1 to 12. Syntax: public int getMonthValue() Parameter: This method does not accepts any parameter. Return Value: The function returns the month of the year from 1-12 in numbers. Below programs illustrate the getMonthValue() method of LocalDate in Java:Program 1: // Program to illustrate the getMonthValue() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-11-27"); // Prints the day number System.out.println(dt.getMonthValue()); }} 11 Program 2: // Program to illustrate the getMonthValue() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-01-02"); // Prints the day number System.out.println(dt.getMonthValue()); }} 1 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getMonthValue() Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 125, "s": 28, "text": "The getMonthValue() method of LocalDate class in Java gets the month-of-year field from 1 to 12." }, { "code": null, "e": 133, "s": 125, "text": "Syntax:" }, { "code": null, "e": 161, "s": 133, "text": "public int getMonthValue()\n" }, { "code": null, "e": 216, "s": 161, "text": "Parameter: This method does not accepts any parameter." }, { "code": null, "e": 295, "s": 216, "text": "Return Value: The function returns the month of the year from 1-12 in numbers." }, { "code": null, "e": 380, "s": 295, "text": "Below programs illustrate the getMonthValue() method of LocalDate in Java:Program 1:" }, { "code": "// Program to illustrate the getMonthValue() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-11-27\"); // Prints the day number System.out.println(dt.getMonthValue()); }}", "e": 705, "s": 380, "text": null }, { "code": null, "e": 709, "s": 705, "text": "11\n" }, { "code": null, "e": 720, "s": 709, "text": "Program 2:" }, { "code": "// Program to illustrate the getMonthValue() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-01-02\"); // Prints the day number System.out.println(dt.getMonthValue()); }}", "e": 1045, "s": 720, "text": null }, { "code": null, "e": 1048, "s": 1045, "text": "1\n" }, { "code": null, "e": 1143, "s": 1048, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getMonthValue()" }, { "code": null, "e": 1158, "s": 1143, "text": "Java-Functions" }, { "code": null, "e": 1173, "s": 1158, "text": "Java-LocalDate" }, { "code": null, "e": 1191, "s": 1173, "text": "Java-time package" }, { "code": null, "e": 1196, "s": 1191, "text": "Java" }, { "code": null, "e": 1201, "s": 1196, "text": "Java" } ]
Python | Ways to merge strings into list
27 Feb, 2019 Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requirement. Let’s understand it better with help of examples. Method #1: Using ast # Python code to merge all strings into a single list. # Importingimport ast # Initialization of stringsstr1 ="'Geeks', 'for', 'Geeks'"str2 ="'paras.j', 'jain.l'"str3 ="'india'" # Initialization of listlist = [] # Extending into single listfor x in (str1, str2, str3): list.extend(ast.literal_eval(x)) # printing outputprint(list) ['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'i', 'n', 'd', 'i', 'a'] Method #2: Using eval # Python code to merge all strings into a single list. # Initialization of stringsstr1 ="['Geeks', 'for', 'Geeks']"str2 ="['paras.j', 'jain.l']"str3 ="['india']" out = [str1, str2, str3] out = eval('+'.join(out)) # printing outputprint(out) ['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'india'] # Python code to merge all strings into a single list. # Initialization of stringsstr1 ="'Geeks', 'for', 'Geeks'"str2 = "'121', '142'"str3 ="'extend', 'India'" out = [str1, str2, str3] out = eval('+'.join(out)) # printing outputprint(list(out)) ['Geeks', 'for', 'Geeks121', '142extend', 'India'] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2019" }, { "code": null, "e": 98, "s": 28, "text": "Given n strings, the task is to merge all strings into a single list." }, { "code": null, "e": 385, "s": 98, "text": "While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requirement. Let’s understand it better with help of examples." }, { "code": null, "e": 406, "s": 385, "text": "Method #1: Using ast" }, { "code": "# Python code to merge all strings into a single list. # Importingimport ast # Initialization of stringsstr1 =\"'Geeks', 'for', 'Geeks'\"str2 =\"'paras.j', 'jain.l'\"str3 =\"'india'\" # Initialization of listlist = [] # Extending into single listfor x in (str1, str2, str3): list.extend(ast.literal_eval(x)) # printing outputprint(list)", "e": 747, "s": 406, "text": null }, { "code": null, "e": 820, "s": 747, "text": "['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'i', 'n', 'd', 'i', 'a']\n" }, { "code": null, "e": 842, "s": 820, "text": "Method #2: Using eval" }, { "code": "# Python code to merge all strings into a single list. # Initialization of stringsstr1 =\"['Geeks', 'for', 'Geeks']\"str2 =\"['paras.j', 'jain.l']\"str3 =\"['india']\" out = [str1, str2, str3] out = eval('+'.join(out)) # printing outputprint(out)", "e": 1089, "s": 842, "text": null }, { "code": null, "e": 1146, "s": 1089, "text": "['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'india']\n" }, { "code": "# Python code to merge all strings into a single list. # Initialization of stringsstr1 =\"'Geeks', 'for', 'Geeks'\"str2 = \"'121', '142'\"str3 =\"'extend', 'India'\" out = [str1, str2, str3] out = eval('+'.join(out)) # printing outputprint(list(out))", "e": 1397, "s": 1146, "text": null }, { "code": null, "e": 1449, "s": 1397, "text": "['Geeks', 'for', 'Geeks121', '142extend', 'India']\n" }, { "code": null, "e": 1470, "s": 1449, "text": "Python list-programs" }, { "code": null, "e": 1493, "s": 1470, "text": "Python string-programs" }, { "code": null, "e": 1500, "s": 1493, "text": "Python" }, { "code": null, "e": 1516, "s": 1500, "text": "Python Programs" }, { "code": null, "e": 1614, "s": 1516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1632, "s": 1614, "text": "Python Dictionary" }, { "code": null, "e": 1674, "s": 1632, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1696, "s": 1674, "text": "Enumerate() in Python" }, { "code": null, "e": 1722, "s": 1696, "text": "Python String | replace()" }, { "code": null, "e": 1754, "s": 1722, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1776, "s": 1754, "text": "Defaultdict in Python" }, { "code": null, "e": 1815, "s": 1776, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1853, "s": 1815, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1890, "s": 1853, "text": "Python Program for Fibonacci numbers" } ]
Matplotlib.figure.Figure.align_labels() in Python - GeeksforGeeks
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The align_labels() method figure module of matplotlib library is used to Align the xlabels and ylabels of subplots with the same subplots row or column if label alignment is being done automatically. Syntax: align_labels(self, axs=None) Parameters: This accept the following parameters that are described below: axs : This parameter is the list of Axes to align the labels. Returns: This method does not return any value. Below examples illustrate the matplotlib.figure.Figure.align_labels() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec fig = plt.figure()gs = gridspec.GridSpec(2, 2) for i in range(2): ax = fig.add_subplot(gs[1, i]) ax.set_ylabel('Y label') ax.set_xlabel('X label') if i == 0: for tick in ax.get_xticklabels(): tick.set_rotation(45) fig.align_labels() fig.suptitle('matplotlib.figure.Figure.align_labels() \function Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec fig = plt.figure(tight_layout = True)gs = gridspec.GridSpec(2, 2) ax = fig.add_subplot(gs[0, :])ax.plot(np.arange(0, 1e6, 1000)) ax.set_ylabel('YLabel0')ax.set_xlabel('XLabel0') for i in range(2): ax = fig.add_subplot(gs[1, i]) ax.plot(np.arange(1., 0., -0.1) * 2000., np.arange(1., 0., -0.1)) ax.set_ylabel('YLabel1 % d' % i) ax.set_xlabel('XLabel1 % d' % i) if i == 0: for tick in ax.get_xticklabels(): tick.set_rotation(55) fig.align_labels() fig.suptitle('matplotlib.figure.Figure.align_labels() \function Example\n\n', fontweight ="bold") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24916, "s": 24888, "text": "\n30 Apr, 2020" }, { "code": null, "e": 25227, "s": 24916, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 25427, "s": 25227, "text": "The align_labels() method figure module of matplotlib library is used to Align the xlabels and ylabels of subplots with the same subplots row or column if label alignment is being done automatically." }, { "code": null, "e": 25464, "s": 25427, "text": "Syntax: align_labels(self, axs=None)" }, { "code": null, "e": 25539, "s": 25464, "text": "Parameters: This accept the following parameters that are described below:" }, { "code": null, "e": 25601, "s": 25539, "text": "axs : This parameter is the list of Axes to align the labels." }, { "code": null, "e": 25649, "s": 25601, "text": "Returns: This method does not return any value." }, { "code": null, "e": 25750, "s": 25649, "text": "Below examples illustrate the matplotlib.figure.Figure.align_labels() function in matplotlib.figure:" }, { "code": null, "e": 25761, "s": 25750, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec fig = plt.figure()gs = gridspec.GridSpec(2, 2) for i in range(2): ax = fig.add_subplot(gs[1, i]) ax.set_ylabel('Y label') ax.set_xlabel('X label') if i == 0: for tick in ax.get_xticklabels(): tick.set_rotation(45) fig.align_labels() fig.suptitle('matplotlib.figure.Figure.align_labels() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 26265, "s": 25761, "text": null }, { "code": null, "e": 26273, "s": 26265, "text": "Output:" }, { "code": null, "e": 26284, "s": 26273, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec fig = plt.figure(tight_layout = True)gs = gridspec.GridSpec(2, 2) ax = fig.add_subplot(gs[0, :])ax.plot(np.arange(0, 1e6, 1000)) ax.set_ylabel('YLabel0')ax.set_xlabel('XLabel0') for i in range(2): ax = fig.add_subplot(gs[1, i]) ax.plot(np.arange(1., 0., -0.1) * 2000., np.arange(1., 0., -0.1)) ax.set_ylabel('YLabel1 % d' % i) ax.set_xlabel('XLabel1 % d' % i) if i == 0: for tick in ax.get_xticklabels(): tick.set_rotation(55) fig.align_labels() fig.suptitle('matplotlib.figure.Figure.align_labels() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 27045, "s": 26284, "text": null }, { "code": null, "e": 27053, "s": 27045, "text": "Output:" }, { "code": null, "e": 27071, "s": 27053, "text": "Python-matplotlib" }, { "code": null, "e": 27078, "s": 27071, "text": "Python" }, { "code": null, "e": 27176, "s": 27078, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27194, "s": 27176, "text": "Python Dictionary" }, { "code": null, "e": 27229, "s": 27194, "text": "Read a file line by line in Python" }, { "code": null, "e": 27251, "s": 27229, "text": "Enumerate() in Python" }, { "code": null, "e": 27283, "s": 27251, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27313, "s": 27283, "text": "Iterate over a list in Python" }, { "code": null, "e": 27355, "s": 27313, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27381, "s": 27355, "text": "Python String | replace()" }, { "code": null, "e": 27418, "s": 27381, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27461, "s": 27418, "text": "Python program to convert a list to string" } ]
Group Management in Linux - GeeksforGeeks
21 Apr, 2020 There are 2 categories of groups in the Linux operating system i.e. Primary and Secondary groups. The Primary Group is a group that is automatically generated while creating a user with a unique user ID simultaneously a group with ID same as the user ID is created and the user gets added to the group and becomes the first and only member of the group. This group is called the primary group. The secondary group is a group that can be created separately with the help of commands and we can then add users to it by changing the group ID of users. 1. Command to Make a group (Secondary Group): Below command created a group with the name as provided. The group while creation gets a group ID and we can get to know everything about the group as its name, ID, and the users present in it in the file “/etc/group”. groupadd group_name Example: groupadd Group1 2. Command to Set the Password for the Group: Below command is used to set the password of the group. After executing the command we have to enter the new password which we want to assign to the group. The password has to be given twice for confirmation purposes. gpasswd group_name Example: gpasswd Group1 3. Command to Display the Group Password File: The below command gives us the password file as output. The file is present in a form such that no information about the file is open for the viewers. Instead of this try: “cat /etc/group” to get more information about the groups. cat /etc/gshadow 4. Command to Add a User to an Existing Group: Below command is used to add a user to an existing group. The users which may be present in any primary or secondary group will exit the other groups and will become the part of this group. usermod -G group_name username usermod -G group1 John_Doe Note: If we add a user to a group then it automatically gets removed from the previous groups, we can prevent this by the command given below. 5. Command to Add User to Group Without Removing From Existing Groups: This command is used to add a user to a new group while preventing him from getting removed from his existing groups. usermod -aG *group_name *username Example: usermod -aG group1 John_Doe 6. Command to Add Multiple Users to a Group at once: gpasswd -M *username1, *username2, *username3 ...., *usernamen *group_name Example: gpasswd -M Person1, Person2, Person3 Group1 7. Command to Delete a User From a Group: Below command is used to delete a user from a group. The user is then removed from the group though it is still a valid user in the system but it is no more a part of the group. The user remains part of the groups which it was in and if it was part of no other group then it will be part of its primary group. gpasswd -d *username1 *group_name Example: gpasswd -d Person1 Group1 8. Command to Delete a Group: Below Command is used to delete the group. The users present in the group will not be deleted. They will remain as they were, but now they will no more be part of this group as the group will be deleted. groupdel *group_name Example: groupdel Group1 Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples scp command in Linux with Examples chown command in Linux with Examples Array Basics in Shell Scripting | Set 1 mv command in Linux with examples Basic Operators in Shell Scripting SED command in Linux | Set 2 Docker - COPY Instruction Named Pipe or FIFO with example C program
[ { "code": null, "e": 24406, "s": 24378, "text": "\n21 Apr, 2020" }, { "code": null, "e": 24955, "s": 24406, "text": "There are 2 categories of groups in the Linux operating system i.e. Primary and Secondary groups. The Primary Group is a group that is automatically generated while creating a user with a unique user ID simultaneously a group with ID same as the user ID is created and the user gets added to the group and becomes the first and only member of the group. This group is called the primary group. The secondary group is a group that can be created separately with the help of commands and we can then add users to it by changing the group ID of users." }, { "code": null, "e": 25220, "s": 24955, "text": "1. Command to Make a group (Secondary Group): Below command created a group with the name as provided. The group while creation gets a group ID and we can get to know everything about the group as its name, ID, and the users present in it in the file “/etc/group”." }, { "code": null, "e": 25241, "s": 25220, "text": "groupadd group_name\n" }, { "code": null, "e": 25250, "s": 25241, "text": "Example:" }, { "code": null, "e": 25266, "s": 25250, "text": "groupadd Group1" }, { "code": null, "e": 25530, "s": 25266, "text": "2. Command to Set the Password for the Group: Below command is used to set the password of the group. After executing the command we have to enter the new password which we want to assign to the group. The password has to be given twice for confirmation purposes." }, { "code": null, "e": 25550, "s": 25530, "text": "gpasswd group_name\n" }, { "code": null, "e": 25559, "s": 25550, "text": "Example:" }, { "code": null, "e": 25574, "s": 25559, "text": "gpasswd Group1" }, { "code": null, "e": 25852, "s": 25574, "text": "3. Command to Display the Group Password File: The below command gives us the password file as output. The file is present in a form such that no information about the file is open for the viewers. Instead of this try: “cat /etc/group” to get more information about the groups." }, { "code": null, "e": 25870, "s": 25852, "text": "cat /etc/gshadow\n" }, { "code": null, "e": 26107, "s": 25870, "text": "4. Command to Add a User to an Existing Group: Below command is used to add a user to an existing group. The users which may be present in any primary or secondary group will exit the other groups and will become the part of this group." }, { "code": null, "e": 26140, "s": 26107, "text": "usermod -G group_name username\n" }, { "code": null, "e": 26167, "s": 26140, "text": "usermod -G group1 John_Doe" }, { "code": null, "e": 26310, "s": 26167, "text": "Note: If we add a user to a group then it automatically gets removed from the previous groups, we can prevent this by the command given below." }, { "code": null, "e": 26499, "s": 26310, "text": "5. Command to Add User to Group Without Removing From Existing Groups: This command is used to add a user to a new group while preventing him from getting removed from his existing groups." }, { "code": null, "e": 26535, "s": 26499, "text": "usermod -aG *group_name *username\n" }, { "code": null, "e": 26544, "s": 26535, "text": "Example:" }, { "code": null, "e": 26572, "s": 26544, "text": "usermod -aG group1 John_Doe" }, { "code": null, "e": 26625, "s": 26572, "text": "6. Command to Add Multiple Users to a Group at once:" }, { "code": null, "e": 26701, "s": 26625, "text": "gpasswd -M *username1, *username2, *username3 ...., *usernamen *group_name\n" }, { "code": null, "e": 26710, "s": 26701, "text": "Example:" }, { "code": null, "e": 26754, "s": 26710, "text": "gpasswd -M Person1, Person2, Person3 Group1" }, { "code": null, "e": 27106, "s": 26754, "text": "7. Command to Delete a User From a Group: Below command is used to delete a user from a group. The user is then removed from the group though it is still a valid user in the system but it is no more a part of the group. The user remains part of the groups which it was in and if it was part of no other group then it will be part of its primary group." }, { "code": null, "e": 27144, "s": 27106, "text": "gpasswd -d *username1 *group_name \n" }, { "code": null, "e": 27153, "s": 27144, "text": "Example:" }, { "code": null, "e": 27180, "s": 27153, "text": "gpasswd -d Person1 Group1" }, { "code": null, "e": 27414, "s": 27180, "text": "8. Command to Delete a Group: Below Command is used to delete the group. The users present in the group will not be deleted. They will remain as they were, but now they will no more be part of this group as the group will be deleted." }, { "code": null, "e": 27436, "s": 27414, "text": "groupdel *group_name\n" }, { "code": null, "e": 27445, "s": 27436, "text": "Example:" }, { "code": null, "e": 27462, "s": 27445, "text": "groupdel Group1" }, { "code": null, "e": 27473, "s": 27462, "text": "Linux-Unix" }, { "code": null, "e": 27571, "s": 27473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27580, "s": 27571, "text": "Comments" }, { "code": null, "e": 27593, "s": 27580, "text": "Old Comments" }, { "code": null, "e": 27619, "s": 27593, "text": "Thread functions in C/C++" }, { "code": null, "e": 27656, "s": 27619, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27691, "s": 27656, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27728, "s": 27691, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27768, "s": 27728, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 27802, "s": 27768, "text": "mv command in Linux with examples" }, { "code": null, "e": 27837, "s": 27802, "text": "Basic Operators in Shell Scripting" }, { "code": null, "e": 27866, "s": 27837, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27892, "s": 27866, "text": "Docker - COPY Instruction" } ]
Bias-variance tradeoff in machine learning: an intuition | by Mahbubul Alam | Towards Data Science
If we had more money in our pockets, we tend to spend more — that’s almost a fact that everyone knows. But what’s often not known is the exact relationship between income and expenditure, i.e. how much people would spend on a known income. An approximate solution is to build a statistical model by observing people’s income and expenditure. The more data there is, the better the model. We can then take this model and apply it to an unknown place or population with reasonable confidence. But the model wouldn’t be able to make a 100% accurate prediction, because people’s behavior changes over time and space (well, that’s why this is called a statistical model rather than a deterministic model). However, even if the model is not universal, we want to make it sufficiently generalizable — an “average model” that is resilient to a wide range of variations and situations. Let’s think of a different context, when we actually do want to build a model for a homogenous group of population, whose behavior is more-or-less predictable. In that case, we’ll aim for a “better-than-average model” that is suitable for that particular population. However, we know that this model is such customized for the target population that it will fall flat in an exotic context. The average model we built is biased, but it has high flexibility and works in a variety of situations, whereas, the better-than-average model is customized, less biased but will perform poorly outside the population it was trained on. Now let’s take both these models to the extremes. In one spectrum we simplified the model so much that it lost all its predictive power; a random guess performs better than the model. On the other extreme, let’s build the model based on every individual in a population and tune the model so much that it has high predictive power for that population. So which model is better? Depends on how do you want to use the model. A bad model performs badly everywhere, an average model performs on par in most circumstances, whereas a fine-tuned model performs great in one situation but not so good in others. The purpose of building a model is to explain real-world phenomena and we use models because those phenomena can change in space and time. But can we build a model that is applicable everywhere and at every point in time? The answer is no. And that’s where the concept of bias-variance tradeoff is useful. Let’s now connect this intuition with the formal concept of bias-variance tradeoff. In machine learning, each model is specified with a number of parameters that determine model performance. A good model performs well both in training and out-of-sample data. Some models can be used out-of-the-box with default parameters. But if we do not tune the parameters, there is always the possibility that the model will not perform at its best. This situation is known as underfitting. So we tune the parameters to fit the training data and then evaluate model performance against testing data. This process is repeated until the model reaches the desired performance. But how will this customized model perform if released into the wild? It is highly likely that this highly tuned model performs poorly in out-of-sample data — a problem known as overfitting. Underfitting and overfitting are bad in a similar way — they are not good at making general predictions. So the bias-variance tradeoff is nothing but maintaining the balance between under and overfitting, choosing between high variance and high bias. Data scientists find a sweet spot so they are confident that the model will perform well in out-of-sample data. Let’s now extend the intuition and the concept of bias-variance tradeoff with an example in Python. For that, I will first import a couple of libraries (numpy and seaborn) and create two small arrays — x and y — to demonstrate. import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsx = [0, 1, 2, 3, 4, 5, 6]y = [0, 1, 2, 14, 18, 32, 52] Now let’s plot the x and y variables and fit a linear regression line. # linear fitsns.regplot(x,y, ci=False); The linear model does not seem to fit the data very well, it clearly looks like a bad model with most data points far from the line. It is highly biased with very little variance. So clearly there is an opportunity to improve this model. Now let’s fit a high-order polynomial line and see how the model performs. # polynomial fitpoly_fit = np.poly1d(np.polyfit(x,y, 6))plt.plot(x, poly_fit(x), linestyle='-')plt.scatter(x, y); How amazing! A 6-degree polynomial fits the data perfectly — actually too perfectly, with zero errors. The model captures every bit of noise in the data. This model has a high (perfect) variance and no bias. Is this the model we want? Probably not. With an increase in polynomial order the complexity of the model increases. There’s no guarantee that this model will perform just like that on other data. So what a better model should look like? Something between too bad and too good? Let’s try lowering the polynomial degree from 6 to 2. # polynomial fitpoly_fit = np.poly1d(np.polyfit(x,y, 2))plt.plot(x, poly_fit(x), linestyle='-')plt.scatter(x, y); This 2-degree polynomial model has some errors and is certainly not as good as 6-degree, but it’s also not as bad as a simple linear fit. So it turns out that a higher degree polynomial fits the data better, but it also makes the model complex. A complex model overfits training data but fails to make high-quality predictions in testing and out-of-sample data. A simple model, on the other hand, underfits training data and does not perform well in testing data either. So data scientists aim to find a sweet spot to balance the tradeoff. But how exactly in practice? Underfitting is easy to spot because it shows up in the model performance. Whereas, overfitting is difficult to catch because models show good performance in the error metrics. It is also really hard for a data scientist to throw away a really good fit model and choose a lower performing one. But there are some tools available to make this decision easier. Here’s a couple of options: 1) Visual interpretation of error vs complexity: Generally, a good practice is to choose a model is by plotting: error vs complexity in training data error vs complexity in testing data examine where two curves intersect and tune parameters accordingly In regression, the bias-variance tradeoff can be examined by plotting Mean Squared Error (MSE) against model complexity. In classification, the same can be examined by plotting the number of misclassification against complexity. 2) Regularization: It is a technique to optimize model performance by adding a small bias in the cost function. This small bias shrinks feature coefficients and reduces their sensitivity. If there are too many features in a dataset, regularization controls their effects and makes them less sensitive. It is done by shrinking model coefficients towards zero. Two types of regularization are commonly used — L1 (LASSO regression) and L2 (Ridge regression) and they are controlled by a hyperparameter λ. To summarize the concept of bias-variance tradeoff: If a model is too simple and underfits the training data, it performs poorly in real prediction as well. A model highly tuned on training data may not perform well either. The bias-variance tradeoff allows for examining the balance to find a suitable model. There are two ways to examine the tradeoff — a. visual interpretation of errors vs complexity and b. regularization. Hope it was a useful discussion on this important concept in machine learning, if you have comments feel free to write them down below or connect with me via Medium, Twitter or LinkedIn.
[ { "code": null, "e": 412, "s": 172, "text": "If we had more money in our pockets, we tend to spend more — that’s almost a fact that everyone knows. But what’s often not known is the exact relationship between income and expenditure, i.e. how much people would spend on a known income." }, { "code": null, "e": 663, "s": 412, "text": "An approximate solution is to build a statistical model by observing people’s income and expenditure. The more data there is, the better the model. We can then take this model and apply it to an unknown place or population with reasonable confidence." }, { "code": null, "e": 1049, "s": 663, "text": "But the model wouldn’t be able to make a 100% accurate prediction, because people’s behavior changes over time and space (well, that’s why this is called a statistical model rather than a deterministic model). However, even if the model is not universal, we want to make it sufficiently generalizable — an “average model” that is resilient to a wide range of variations and situations." }, { "code": null, "e": 1439, "s": 1049, "text": "Let’s think of a different context, when we actually do want to build a model for a homogenous group of population, whose behavior is more-or-less predictable. In that case, we’ll aim for a “better-than-average model” that is suitable for that particular population. However, we know that this model is such customized for the target population that it will fall flat in an exotic context." }, { "code": null, "e": 1675, "s": 1439, "text": "The average model we built is biased, but it has high flexibility and works in a variety of situations, whereas, the better-than-average model is customized, less biased but will perform poorly outside the population it was trained on." }, { "code": null, "e": 2027, "s": 1675, "text": "Now let’s take both these models to the extremes. In one spectrum we simplified the model so much that it lost all its predictive power; a random guess performs better than the model. On the other extreme, let’s build the model based on every individual in a population and tune the model so much that it has high predictive power for that population." }, { "code": null, "e": 2053, "s": 2027, "text": "So which model is better?" }, { "code": null, "e": 2279, "s": 2053, "text": "Depends on how do you want to use the model. A bad model performs badly everywhere, an average model performs on par in most circumstances, whereas a fine-tuned model performs great in one situation but not so good in others." }, { "code": null, "e": 2501, "s": 2279, "text": "The purpose of building a model is to explain real-world phenomena and we use models because those phenomena can change in space and time. But can we build a model that is applicable everywhere and at every point in time?" }, { "code": null, "e": 2585, "s": 2501, "text": "The answer is no. And that’s where the concept of bias-variance tradeoff is useful." }, { "code": null, "e": 2669, "s": 2585, "text": "Let’s now connect this intuition with the formal concept of bias-variance tradeoff." }, { "code": null, "e": 2844, "s": 2669, "text": "In machine learning, each model is specified with a number of parameters that determine model performance. A good model performs well both in training and out-of-sample data." }, { "code": null, "e": 3064, "s": 2844, "text": "Some models can be used out-of-the-box with default parameters. But if we do not tune the parameters, there is always the possibility that the model will not perform at its best. This situation is known as underfitting." }, { "code": null, "e": 3438, "s": 3064, "text": "So we tune the parameters to fit the training data and then evaluate model performance against testing data. This process is repeated until the model reaches the desired performance. But how will this customized model perform if released into the wild? It is highly likely that this highly tuned model performs poorly in out-of-sample data — a problem known as overfitting." }, { "code": null, "e": 3801, "s": 3438, "text": "Underfitting and overfitting are bad in a similar way — they are not good at making general predictions. So the bias-variance tradeoff is nothing but maintaining the balance between under and overfitting, choosing between high variance and high bias. Data scientists find a sweet spot so they are confident that the model will perform well in out-of-sample data." }, { "code": null, "e": 4029, "s": 3801, "text": "Let’s now extend the intuition and the concept of bias-variance tradeoff with an example in Python. For that, I will first import a couple of libraries (numpy and seaborn) and create two small arrays — x and y — to demonstrate." }, { "code": null, "e": 4154, "s": 4029, "text": "import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsx = [0, 1, 2, 3, 4, 5, 6]y = [0, 1, 2, 14, 18, 32, 52]" }, { "code": null, "e": 4225, "s": 4154, "text": "Now let’s plot the x and y variables and fit a linear regression line." }, { "code": null, "e": 4265, "s": 4225, "text": "# linear fitsns.regplot(x,y, ci=False);" }, { "code": null, "e": 4503, "s": 4265, "text": "The linear model does not seem to fit the data very well, it clearly looks like a bad model with most data points far from the line. It is highly biased with very little variance. So clearly there is an opportunity to improve this model." }, { "code": null, "e": 4578, "s": 4503, "text": "Now let’s fit a high-order polynomial line and see how the model performs." }, { "code": null, "e": 4692, "s": 4578, "text": "# polynomial fitpoly_fit = np.poly1d(np.polyfit(x,y, 6))plt.plot(x, poly_fit(x), linestyle='-')plt.scatter(x, y);" }, { "code": null, "e": 4900, "s": 4692, "text": "How amazing! A 6-degree polynomial fits the data perfectly — actually too perfectly, with zero errors. The model captures every bit of noise in the data. This model has a high (perfect) variance and no bias." }, { "code": null, "e": 4927, "s": 4900, "text": "Is this the model we want?" }, { "code": null, "e": 5097, "s": 4927, "text": "Probably not. With an increase in polynomial order the complexity of the model increases. There’s no guarantee that this model will perform just like that on other data." }, { "code": null, "e": 5232, "s": 5097, "text": "So what a better model should look like? Something between too bad and too good? Let’s try lowering the polynomial degree from 6 to 2." }, { "code": null, "e": 5346, "s": 5232, "text": "# polynomial fitpoly_fit = np.poly1d(np.polyfit(x,y, 2))plt.plot(x, poly_fit(x), linestyle='-')plt.scatter(x, y);" }, { "code": null, "e": 5591, "s": 5346, "text": "This 2-degree polynomial model has some errors and is certainly not as good as 6-degree, but it’s also not as bad as a simple linear fit. So it turns out that a higher degree polynomial fits the data better, but it also makes the model complex." }, { "code": null, "e": 5817, "s": 5591, "text": "A complex model overfits training data but fails to make high-quality predictions in testing and out-of-sample data. A simple model, on the other hand, underfits training data and does not perform well in testing data either." }, { "code": null, "e": 5915, "s": 5817, "text": "So data scientists aim to find a sweet spot to balance the tradeoff. But how exactly in practice?" }, { "code": null, "e": 6302, "s": 5915, "text": "Underfitting is easy to spot because it shows up in the model performance. Whereas, overfitting is difficult to catch because models show good performance in the error metrics. It is also really hard for a data scientist to throw away a really good fit model and choose a lower performing one. But there are some tools available to make this decision easier. Here’s a couple of options:" }, { "code": null, "e": 6415, "s": 6302, "text": "1) Visual interpretation of error vs complexity: Generally, a good practice is to choose a model is by plotting:" }, { "code": null, "e": 6452, "s": 6415, "text": "error vs complexity in training data" }, { "code": null, "e": 6488, "s": 6452, "text": "error vs complexity in testing data" }, { "code": null, "e": 6555, "s": 6488, "text": "examine where two curves intersect and tune parameters accordingly" }, { "code": null, "e": 6784, "s": 6555, "text": "In regression, the bias-variance tradeoff can be examined by plotting Mean Squared Error (MSE) against model complexity. In classification, the same can be examined by plotting the number of misclassification against complexity." }, { "code": null, "e": 6972, "s": 6784, "text": "2) Regularization: It is a technique to optimize model performance by adding a small bias in the cost function. This small bias shrinks feature coefficients and reduces their sensitivity." }, { "code": null, "e": 7286, "s": 6972, "text": "If there are too many features in a dataset, regularization controls their effects and makes them less sensitive. It is done by shrinking model coefficients towards zero. Two types of regularization are commonly used — L1 (LASSO regression) and L2 (Ridge regression) and they are controlled by a hyperparameter λ." }, { "code": null, "e": 7338, "s": 7286, "text": "To summarize the concept of bias-variance tradeoff:" }, { "code": null, "e": 7443, "s": 7338, "text": "If a model is too simple and underfits the training data, it performs poorly in real prediction as well." }, { "code": null, "e": 7510, "s": 7443, "text": "A model highly tuned on training data may not perform well either." }, { "code": null, "e": 7596, "s": 7510, "text": "The bias-variance tradeoff allows for examining the balance to find a suitable model." }, { "code": null, "e": 7713, "s": 7596, "text": "There are two ways to examine the tradeoff — a. visual interpretation of errors vs complexity and b. regularization." } ]
ios fail() function in C++ with Examples - GeeksforGeeks
02 Sep, 2019 The fail() method of ios class in C++ is used to check if the stream is has raised any fail error. It means that this function will check if this stream has its failbit set. Syntax: bool fail() const; Parameters: This method does not accept any parameter. Return Value: This method returns true if the stream has failbit set, else false. Example 1: // C++ code to demonstrate// the working of fail() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; // Using fail() function bool isFail = ss.fail(); // print result cout << "is stream fail: " << isFail << endl; return 0;} is stream fail: 0 Example 2: // C++ code to demonstrate// the working of fail() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; ss.clear(ss.failbit); // Using fail() function bool isFail = ss.fail(); // print result cout << "is stream fail: " << isFail << endl; return 0;} is stream fail: 1 Reference: hhttp://www.cplusplus.com/reference/ios/ios/fail/ CPP-Functions cpp-ios C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Array of Strings in C++ (5 Different Ways to Create) Pair in C++ Standard Template Library (STL) Inline Functions in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL)
[ { "code": null, "e": 24221, "s": 24193, "text": "\n02 Sep, 2019" }, { "code": null, "e": 24395, "s": 24221, "text": "The fail() method of ios class in C++ is used to check if the stream is has raised any fail error. It means that this function will check if this stream has its failbit set." }, { "code": null, "e": 24403, "s": 24395, "text": "Syntax:" }, { "code": null, "e": 24423, "s": 24403, "text": "bool fail() const;\n" }, { "code": null, "e": 24478, "s": 24423, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 24560, "s": 24478, "text": "Return Value: This method returns true if the stream has failbit set, else false." }, { "code": null, "e": 24571, "s": 24560, "text": "Example 1:" }, { "code": "// C++ code to demonstrate// the working of fail() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; // Using fail() function bool isFail = ss.fail(); // print result cout << \"is stream fail: \" << isFail << endl; return 0;}", "e": 24877, "s": 24571, "text": null }, { "code": null, "e": 24896, "s": 24877, "text": "is stream fail: 0\n" }, { "code": null, "e": 24907, "s": 24896, "text": "Example 2:" }, { "code": "// C++ code to demonstrate// the working of fail() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; ss.clear(ss.failbit); // Using fail() function bool isFail = ss.fail(); // print result cout << \"is stream fail: \" << isFail << endl; return 0;}", "e": 25238, "s": 24907, "text": null }, { "code": null, "e": 25257, "s": 25238, "text": "is stream fail: 1\n" }, { "code": null, "e": 25318, "s": 25257, "text": "Reference: hhttp://www.cplusplus.com/reference/ios/ios/fail/" }, { "code": null, "e": 25332, "s": 25318, "text": "CPP-Functions" }, { "code": null, "e": 25340, "s": 25332, "text": "cpp-ios" }, { "code": null, "e": 25344, "s": 25340, "text": "C++" }, { "code": null, "e": 25348, "s": 25344, "text": "CPP" }, { "code": null, "e": 25446, "s": 25348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25474, "s": 25446, "text": "Operator Overloading in C++" }, { "code": null, "e": 25494, "s": 25474, "text": "Polymorphism in C++" }, { "code": null, "e": 25527, "s": 25494, "text": "Friend class and function in C++" }, { "code": null, "e": 25551, "s": 25527, "text": "Sorting a vector in C++" }, { "code": null, "e": 25576, "s": 25551, "text": "std::string class in C++" }, { "code": null, "e": 25629, "s": 25576, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 25673, "s": 25629, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 25697, "s": 25673, "text": "Inline Functions in C++" }, { "code": null, "e": 25733, "s": 25697, "text": "Convert string to char array in C++" } ]
How to Install SQLAlchemy in Python in Windows? - GeeksforGeeks
22 Sep, 2021 SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that is used as flexible database access using SQL. In this article, we will look into the process of installing SQLAlchemy on a windows machine. The only thing that you need for installing Numpy on Windows are: Python PIP or Conda (depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c anaconda sqlalchemy Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge To verify if SQLAlchemy has been successfully installed in your system run the below command in Anaconda Powershell Prompt: conda list pyglet You’ll get the below message if the installation is complete: If you want the installation to be done through PIP, open up the command Prompt and use the below command: pip install pyglet You will get a similar message once the installation is complete: To verify if the SQLAlchemy has been successfully installed in your system run the below command in Command Prompt: python -m pip show sqlalchemy You’ll get the below message if the installation is complete: Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to pass data into table from a form using React Components SQL Query to Convert Datetime to Date How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to filter object array based on attributes?
[ { "code": null, "e": 26207, "s": 26179, "text": "\n22 Sep, 2021" }, { "code": null, "e": 26420, "s": 26207, "text": "SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that is used as flexible database access using SQL. In this article, we will look into the process of installing SQLAlchemy on a windows machine." }, { "code": null, "e": 26486, "s": 26420, "text": "The only thing that you need for installing Numpy on Windows are:" }, { "code": null, "e": 26494, "s": 26486, "text": "Python " }, { "code": null, "e": 26540, "s": 26494, "text": "PIP or Conda (depending upon user preference)" }, { "code": null, "e": 26662, "s": 26540, "text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:" }, { "code": null, "e": 26699, "s": 26662, "text": "conda install -c anaconda sqlalchemy" }, { "code": null, "e": 26729, "s": 26699, "text": "Type y for yes when prompted." }, { "code": null, "e": 26795, "s": 26729, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 26868, "s": 26795, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 26965, "s": 26868, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 27010, "s": 26965, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 27096, "s": 27010, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 27142, "s": 27096, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 27267, "s": 27142, "text": "To verify if SQLAlchemy has been successfully installed in your system run the below command in Anaconda Powershell Prompt:" }, { "code": null, "e": 27285, "s": 27267, "text": "conda list pyglet" }, { "code": null, "e": 27347, "s": 27285, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 27455, "s": 27347, "text": "If you want the installation to be done through PIP, open up the command Prompt and use the below command:" }, { "code": null, "e": 27474, "s": 27455, "text": "pip install pyglet" }, { "code": null, "e": 27540, "s": 27474, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 27657, "s": 27540, "text": "To verify if the SQLAlchemy has been successfully installed in your system run the below command in Command Prompt:" }, { "code": null, "e": 27689, "s": 27657, "text": "python -m pip show sqlalchemy " }, { "code": null, "e": 27751, "s": 27689, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 27766, "s": 27751, "text": "Blogathon-2021" }, { "code": null, "e": 27781, "s": 27766, "text": "how-to-install" }, { "code": null, "e": 27788, "s": 27781, "text": "Picked" }, { "code": null, "e": 27798, "s": 27788, "text": "Blogathon" }, { "code": null, "e": 27805, "s": 27798, "text": "How To" }, { "code": null, "e": 27824, "s": 27805, "text": "Installation Guide" }, { "code": null, "e": 27922, "s": 27824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27979, "s": 27922, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28020, "s": 27979, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 28050, "s": 28020, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 28113, "s": 28050, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 28151, "s": 28113, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 28183, "s": 28151, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28236, "s": 28183, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 28280, "s": 28236, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 28307, "s": 28280, "text": "How to Align Text in HTML?" } ]
Differences between Functional Components and Class Components in React - GeeksforGeeks
29 Mar, 2022 Make a counter app that will increase the number of counts as users click on the “Add” button using Functional and Class components. Functional Components: Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function. Syntax: const Car=()=> { return <h2>Hi, I am also a Car!</h2>; } Example: Javascript import React, { useState } from "react"; const FunctionalComponent=()=>{ const [count, setCount] = useState(0); const increase = () => { setCount(count+1); } return ( <div style={{margin:'50px'}}> <h1>Welcome to Geeks for Geeks </h1> <h3>Counter App using Functional Component : </h3> <h2>{count}</h2> <button onClick={increase}>Add</button> </div> )} export default FunctionalComponent; Output: Class Component: This is the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application). Syntax: class Car extends React.Component { render() { return <h2>Hi, I am a Car!</h2>; } } Example: Javascript import React, { Component } from "react"; class ClassComponent extends React.Component{ constructor(){ super(); this.state={ count :0 }; this.increase=this.increase.bind(this); } increase(){ this.setState({count : this.state.count +1}); } render(){ return ( <div style={{margin:'50px'}}> <h1>Welcome to Geeks for Geeks </h1> <h3>Counter App using Class Component : </h3> <h2> {this.state.count}</h2> <button onClick={this.increase}> Add</button> </div> ) }} export default ClassComponent; Output: Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class. In the above example, for functional components, we use hooks (useState) to manage the state. If you write a function component and realise you need to add some state to it, previously you had to convert it to a class component. Now you can use a Hook inside the existing function component to manage the state and no need to convert it into the Class component. Instead of Classes, one can use Hooks in the Functional component as this is a much easier way of managing the state. Hooks can only be used in functional components, not in-class components. Functional Components vs Class Components: Hooks can be easily used in functional components to make them Stateful. example: const [name,SetName]= React.useState(‘ ‘) It requires different syntax inside a class component to implement hooks. example: constructor(props) { super(props); this.state = {name: ‘ ‘} } shubhamyadav4 simranarora5sos vaibhavjoshi8 xggrjpzot8i9qz6nfag3shf6gzrq31yds32mogh4 react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? File uploading in React.js Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28522, "s": 28494, "text": "\n29 Mar, 2022" }, { "code": null, "e": 28655, "s": 28522, "text": "Make a counter app that will increase the number of counts as users click on the “Add” button using Functional and Class components." }, { "code": null, "e": 28904, "s": 28655, "text": "Functional Components: Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function." }, { "code": null, "e": 28912, "s": 28904, "text": "Syntax:" }, { "code": null, "e": 28971, "s": 28912, "text": "const Car=()=> {\n return <h2>Hi, I am also a Car!</h2>;\n}" }, { "code": null, "e": 28980, "s": 28971, "text": "Example:" }, { "code": null, "e": 28991, "s": 28980, "text": "Javascript" }, { "code": "import React, { useState } from \"react\"; const FunctionalComponent=()=>{ const [count, setCount] = useState(0); const increase = () => { setCount(count+1); } return ( <div style={{margin:'50px'}}> <h1>Welcome to Geeks for Geeks </h1> <h3>Counter App using Functional Component : </h3> <h2>{count}</h2> <button onClick={increase}>Add</button> </div> )} export default FunctionalComponent;", "e": 29467, "s": 28991, "text": null }, { "code": null, "e": 29476, "s": 29467, "text": " Output:" }, { "code": null, "e": 29675, "s": 29476, "text": "Class Component: This is the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application)." }, { "code": null, "e": 29683, "s": 29675, "text": "Syntax:" }, { "code": null, "e": 29775, "s": 29683, "text": "class Car extends React.Component {\n render() {\n return <h2>Hi, I am a Car!</h2>;\n }\n}" }, { "code": null, "e": 29784, "s": 29775, "text": "Example:" }, { "code": null, "e": 29795, "s": 29784, "text": "Javascript" }, { "code": "import React, { Component } from \"react\"; class ClassComponent extends React.Component{ constructor(){ super(); this.state={ count :0 }; this.increase=this.increase.bind(this); } increase(){ this.setState({count : this.state.count +1}); } render(){ return ( <div style={{margin:'50px'}}> <h1>Welcome to Geeks for Geeks </h1> <h3>Counter App using Class Component : </h3> <h2> {this.state.count}</h2> <button onClick={this.increase}> Add</button> </div> ) }} export default ClassComponent;", "e": 30451, "s": 29795, "text": null }, { "code": null, "e": 30459, "s": 30451, "text": "Output:" }, { "code": null, "e": 30572, "s": 30459, "text": "Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class." }, { "code": null, "e": 31127, "s": 30572, "text": "In the above example, for functional components, we use hooks (useState) to manage the state. If you write a function component and realise you need to add some state to it, previously you had to convert it to a class component. Now you can use a Hook inside the existing function component to manage the state and no need to convert it into the Class component. Instead of Classes, one can use Hooks in the Functional component as this is a much easier way of managing the state. Hooks can only be used in functional components, not in-class components." }, { "code": null, "e": 31170, "s": 31127, "text": "Functional Components vs Class Components:" }, { "code": null, "e": 31243, "s": 31170, "text": "Hooks can be easily used in functional components to make them Stateful." }, { "code": null, "e": 31294, "s": 31243, "text": "example: const [name,SetName]= React.useState(‘ ‘)" }, { "code": null, "e": 31368, "s": 31294, "text": "It requires different syntax inside a class component to implement hooks." }, { "code": null, "e": 31398, "s": 31368, "text": "example: constructor(props) {" }, { "code": null, "e": 31415, "s": 31398, "text": " super(props);" }, { "code": null, "e": 31443, "s": 31415, "text": " this.state = {name: ‘ ‘}" }, { "code": null, "e": 31445, "s": 31443, "text": "}" }, { "code": null, "e": 31459, "s": 31445, "text": "shubhamyadav4" }, { "code": null, "e": 31475, "s": 31459, "text": "simranarora5sos" }, { "code": null, "e": 31489, "s": 31475, "text": "vaibhavjoshi8" }, { "code": null, "e": 31530, "s": 31489, "text": "xggrjpzot8i9qz6nfag3shf6gzrq31yds32mogh4" }, { "code": null, "e": 31539, "s": 31530, "text": "react-js" }, { "code": null, "e": 31550, "s": 31539, "text": "JavaScript" }, { "code": null, "e": 31567, "s": 31550, "text": "Web Technologies" }, { "code": null, "e": 31665, "s": 31567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31705, "s": 31665, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31750, "s": 31705, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31811, "s": 31750, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31880, "s": 31811, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 31907, "s": 31880, "text": "File uploading in React.js" }, { "code": null, "e": 31947, "s": 31907, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31980, "s": 31947, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32025, "s": 31980, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32068, "s": 32025, "text": "How to fetch data from an API in ReactJS ?" } ]
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks
11 Oct, 2021 For any two languages L1 and L2 such that L1 is context free and L2 is recursively enumerable but not recursive, which of the following is/are necessarily true? 1. L1' (complement of L1) is recursive 2. L2' (complement of L2) is recursive 3. L1' is context-free 4. L1' ∪ L2 is recursively enumerable (A) 1 only(B) 3 only(C) 3 and 4 only(D) 1 and 4 onlyAnswer: (D)Explanation: 1. L1′ (complement of L1) is recursive is trueL1 is context free. Every context free language is also recursive and recursive languages are closed under complement. 4. L1′ ∪ L2 is recursively enumerable is trueSince L1′ is recursive, it is also recursively enumerable and recursively enumerable languages are closed under union.Recursively enumerable languages are known as type-0 languages in the Chomsky hierarchy of formal languages. All regular, context-free, context-sensitive and recursive languages are recursively enumerable. (Source: Wiki) 3. L1′ is context-free:Context-free languages are not closed under complement, intersection, or difference. 2. L2′ (complement of L2) is recursive is false:Recursively enumerable languages are not closed under set difference or complementation YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ's on Theory of Computation with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:23 / 56:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=iNOmopKv0aY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2012 | Question 40 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24075, "s": 24047, "text": "\n11 Oct, 2021" }, { "code": null, "e": 24236, "s": 24075, "text": "For any two languages L1 and L2 such that L1 is context free and L2 is recursively enumerable but not recursive, which of the following is/are necessarily true?" }, { "code": null, "e": 24378, "s": 24236, "text": "1. L1' (complement of L1) is recursive \n2. L2' (complement of L2) is recursive\n3. L1' is context-free \n4. L1' ∪ L2 is recursively enumerable " }, { "code": null, "e": 24619, "s": 24378, "text": "(A) 1 only(B) 3 only(C) 3 and 4 only(D) 1 and 4 onlyAnswer: (D)Explanation: 1. L1′ (complement of L1) is recursive is trueL1 is context free. Every context free language is also recursive and recursive languages are closed under complement." }, { "code": null, "e": 25003, "s": 24619, "text": "4. L1′ ∪ L2 is recursively enumerable is trueSince L1′ is recursive, it is also recursively enumerable and recursively enumerable languages are closed under union.Recursively enumerable languages are known as type-0 languages in the Chomsky hierarchy of formal languages. All regular, context-free, context-sensitive and recursive languages are recursively enumerable. (Source: Wiki)" }, { "code": null, "e": 25111, "s": 25003, "text": "3. L1′ is context-free:Context-free languages are not closed under complement, intersection, or difference." }, { "code": null, "e": 25247, "s": 25111, "text": "2. L2′ (complement of L2) is recursive is false:Recursively enumerable languages are not closed under set difference or complementation" }, { "code": null, "e": 26164, "s": 25247, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ's on Theory of Computation with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:23 / 56:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=iNOmopKv0aY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 26185, "s": 26164, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26211, "s": 26185, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26216, "s": 26211, "text": "GATE" }, { "code": null, "e": 26314, "s": 26216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26323, "s": 26314, "text": "Comments" }, { "code": null, "e": 26336, "s": 26323, "text": "Old Comments" }, { "code": null, "e": 26378, "s": 26336, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 26420, "s": 26378, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 26454, "s": 26420, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 26496, "s": 26454, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26529, "s": 26496, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26563, "s": 26529, "text": "GATE | GATE CS 2012 | Question 40" }, { "code": null, "e": 26617, "s": 26563, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 26659, "s": 26617, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 26693, "s": 26659, "text": "GATE | GATE-CS-2006 | Question 49" } ]
How to remove margin introduced in pre tag in bootstrap 4? - GeeksforGeeks
25 May, 2020 The problem is that whenever you apply margin space as per your margin value it will give you output. But in <pre> tag if you apply it by keeping any space then it will consider as margin. Because pre is acted vice versa, means as you have written inside the pre tag the output will be the same. Note: The examples will act same with the bootstrap. Example 1: The approach of the pre tag is basically used if you want to write the code and print it as a normal text. Program:<!DOCTYPE html><html> <head> <title>Pre tag usage</title></head> <body> <!-- Notice the spces inside of the pre tag --> <pre> GeeskforGeeks </pre> <pre> A Computer Science Portal For Geeks </pre></body> </html> <!DOCTYPE html><html> <head> <title>Pre tag usage</title></head> <body> <!-- Notice the spces inside of the pre tag --> <pre> GeeskforGeeks </pre> <pre> A Computer Science Portal For Geeks </pre></body> </html> Output: GeeskforGeeks A Computer Science Portal For Geeks GeeskforGeeks A Computer Science Portal For Geeks Example 2: Sometimes it happens that you have written some code and give some space or margin inside the pre tag then the output also gives the margin.Inside pre tag the way you write the code same it will give as an output. Program:<!DOCTYPE html><html> <head> <title>Demo</title></head> <body> <div class="row"> <div class="col-md-3"> <pre><p><b>GeeksforGeeks</b>This paragraph is on remove marginintroduced in pre tag in bootstrap 4</p></pre> </div> </div></body> </html> <!DOCTYPE html><html> <head> <title>Demo</title></head> <body> <div class="row"> <div class="col-md-3"> <pre><p><b>GeeksforGeeks</b>This paragraph is on remove marginintroduced in pre tag in bootstrap 4</p></pre> </div> </div></body> </html> Output:GeeksforGeeks This paragraph is on remove margin introduced in pre tag in bootstrap 4 GeeksforGeeks This paragraph is on remove margin introduced in pre tag in bootstrap 4 Bootstrap-4 Picked Bootstrap Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23791, "s": 23763, "text": "\n25 May, 2020" }, { "code": null, "e": 24087, "s": 23791, "text": "The problem is that whenever you apply margin space as per your margin value it will give you output. But in <pre> tag if you apply it by keeping any space then it will consider as margin. Because pre is acted vice versa, means as you have written inside the pre tag the output will be the same." }, { "code": null, "e": 24140, "s": 24087, "text": "Note: The examples will act same with the bootstrap." }, { "code": null, "e": 24258, "s": 24140, "text": "Example 1: The approach of the pre tag is basically used if you want to write the code and print it as a normal text." }, { "code": null, "e": 24511, "s": 24258, "text": "Program:<!DOCTYPE html><html> <head> <title>Pre tag usage</title></head> <body> <!-- Notice the spces inside of the pre tag --> <pre> GeeskforGeeks </pre> <pre> A Computer Science Portal For Geeks </pre></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title>Pre tag usage</title></head> <body> <!-- Notice the spces inside of the pre tag --> <pre> GeeskforGeeks </pre> <pre> A Computer Science Portal For Geeks </pre></body> </html>", "e": 24756, "s": 24511, "text": null }, { "code": null, "e": 24832, "s": 24756, "text": "Output: GeeskforGeeks \n A Computer Science Portal\n For Geeks\n " }, { "code": null, "e": 24901, "s": 24832, "text": " GeeskforGeeks \n A Computer Science Portal\n For Geeks\n " }, { "code": null, "e": 25126, "s": 24901, "text": "Example 2: Sometimes it happens that you have written some code and give some space or margin inside the pre tag then the output also gives the margin.Inside pre tag the way you write the code same it will give as an output." }, { "code": null, "e": 25433, "s": 25126, "text": "Program:<!DOCTYPE html><html> <head> <title>Demo</title></head> <body> <div class=\"row\"> <div class=\"col-md-3\"> <pre><p><b>GeeksforGeeks</b>This paragraph is on remove marginintroduced in pre tag in bootstrap 4</p></pre> </div> </div></body> </html> " }, { "code": "<!DOCTYPE html><html> <head> <title>Demo</title></head> <body> <div class=\"row\"> <div class=\"col-md-3\"> <pre><p><b>GeeksforGeeks</b>This paragraph is on remove marginintroduced in pre tag in bootstrap 4</p></pre> </div> </div></body> </html> ", "e": 25732, "s": 25433, "text": null }, { "code": null, "e": 25825, "s": 25732, "text": "Output:GeeksforGeeks\nThis paragraph is on remove margin\nintroduced in pre tag in bootstrap 4" }, { "code": null, "e": 25911, "s": 25825, "text": "GeeksforGeeks\nThis paragraph is on remove margin\nintroduced in pre tag in bootstrap 4" }, { "code": null, "e": 25923, "s": 25911, "text": "Bootstrap-4" }, { "code": null, "e": 25930, "s": 25923, "text": "Picked" }, { "code": null, "e": 25940, "s": 25930, "text": "Bootstrap" }, { "code": null, "e": 25957, "s": 25940, "text": "Web Technologies" }, { "code": null, "e": 25984, "s": 25957, "text": "Web technologies Questions" }, { "code": null, "e": 26082, "s": 25984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26091, "s": 26082, "text": "Comments" }, { "code": null, "e": 26104, "s": 26091, "text": "Old Comments" }, { "code": null, "e": 26145, "s": 26104, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 26186, "s": 26145, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 26249, "s": 26186, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 26282, "s": 26249, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 26329, "s": 26282, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 26385, "s": 26329, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26418, "s": 26385, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26480, "s": 26418, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26523, "s": 26480, "text": "How to fetch data from an API in ReactJS ?" } ]
How to split a big data frame into smaller ones in R?
Dealing with big data frames is not an easy task therefore we might want to split that into some smaller data frames. These smaller data frames can be extracted from the big one based on some criteria such as for levels of a factor variable or with some other conditions. This can be done by using split function. Consider the below data frame − > set.seed(1) > Grades<-rep(c("A","B","C","D","E"),times=10) > Age<-sample(1:30,50,replace=TRUE) > Category<-sample(1:10,50,replace=TRUE) > df<-data.frame(Grades,Age,Category) > head(df,20) Grades Age Category 1 A 25 6 2 B 4 9 3 C 7 8 4 D 1 9 5 E 2 7 6 A 29 8 7 B 23 6 8 C 11 10 9 D 14 7 10 E 18 3 11 A 27 10 12 B 19 6 13 C 1 8 14 D 21 2 15 E 21 2 16 A 10 6 17 B 22 6 18 C 14 1 19 D 10 3 20 E 7 3 Splitting the data frame on the basis of grades − > Split_based_on_Grades<-split(df,f=df$Grades) > Split_based_on_Grades $A Grades Age Category 1 A 25 6 6 A 29 8 11 A 27 10 16 A 10 6 21 A 9 8 26 A 25 7 31 A 10 9 36 A 1 1 41 A 10 7 46 A 20 10 $B Grades Age Category 2 B 4 9 7 B 23 6 12 B 19 6 17 B 22 6 22 B 15 6 27 B 14 1 32 B 30 7 37 B 20 5 42 B 6 7 47 B 26 10 $C Grades Age Category 3 C 7 8 8 C 11 10 13 C 1 8 18 C 14 1 23 C 21 7 28 C 5 4 33 C 25 4 38 C 3 6 43 C 15 3 48 C 12 7 $D Grades Age Category 4 D 1 9 9 D 14 7 14 D 21 2 19 D 10 3 24 D 5 6 29 D 5 8 34 D 12 7 39 D 6 1 44 D 20 6 49 D 25 3 $E Grades Age Category 5 E 2 7 10 E 18 3 15 E 21 2 20 E 7 3 25 E 9 8 30 E 2 9 35 E 15 6 40 E 10 9 45 E 28 2 50 E 23 2 Now we can access each grade as shown below − > Split_based_on_Grades[[1]] Grades Age Category 1 A 25 6 6 A 29 8 11 A 27 10 16 A 10 6 21 A 9 8 26 A 25 7 31 A 10 9 36 A 1 1 41 A 10 7 46 A 20 10 > Split_based_on_Grades[[4]] Grades Age Category 4 D 1 9 9 D 14 7 14 D 21 2 19 D 10 3 24 D 5 6 29 D 5 8 34 D 12 7 39 D 6 1 44 D 20 6 49 D 25 3
[ { "code": null, "e": 1376, "s": 1062, "text": "Dealing with big data frames is not an easy task therefore we might want to split that into some smaller data frames. These smaller data frames can be extracted from the big one based on some criteria such as for levels of a factor variable or with some other conditions. This can be done by using split function." }, { "code": null, "e": 1408, "s": 1376, "text": "Consider the below data frame −" }, { "code": null, "e": 1980, "s": 1408, "text": "> set.seed(1)\n> Grades<-rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),times=10)\n> Age<-sample(1:30,50,replace=TRUE)\n> Category<-sample(1:10,50,replace=TRUE)\n> df<-data.frame(Grades,Age,Category)\n> head(df,20)\n Grades Age Category\n1 A 25 6\n2 B 4 9\n3 C 7 8\n4 D 1 9\n5 E 2 7\n6 A 29 8\n7 B 23 6\n8 C 11 10\n9 D 14 7\n10 E 18 3\n11 A 27 10\n12 B 19 6\n13 C 1 8\n14 D 21 2\n15 E 21 2\n16 A 10 6\n17 B 22 6\n18 C 14 1\n19 D 10 3\n20 E 7 3" }, { "code": null, "e": 2030, "s": 1980, "text": "Splitting the data frame on the basis of grades −" }, { "code": null, "e": 3187, "s": 2030, "text": "> Split_based_on_Grades<-split(df,f=df$Grades)\n> Split_based_on_Grades\n$A\n Grades Age Category\n1 A 25 6\n6 A 29 8\n11 A 27 10\n16 A 10 6\n21 A 9 8\n26 A 25 7\n31 A 10 9\n36 A 1 1\n41 A 10 7\n46 A 20 10\n$B\n Grades Age Category\n2 B 4 9\n7 B 23 6\n12 B 19 6\n17 B 22 6\n22 B 15 6\n27 B 14 1\n32 B 30 7\n37 B 20 5\n42 B 6 7\n47 B 26 10\n$C\n Grades Age Category\n3 C 7 8\n8 C 11 10\n13 C 1 8\n18 C 14 1\n23 C 21 7\n28 C 5 4\n33 C 25 4\n38 C 3 6\n43 C 15 3\n48 C 12 7\n$D\n Grades Age Category\n4 D 1 9\n9 D 14 7\n14 D 21 2\n19 D 10 3\n24 D 5 6\n29 D 5 8\n34 D 12 7\n39 D 6 1\n44 D 20 6\n49 D 25 3\n$E\n Grades Age Category\n5 E 2 7\n10 E 18 3\n15 E 21 2\n20 E 7 3\n25 E 9 8\n30 E 2 9\n35 E 15 6\n40 E 10 9\n45 E 28 2\n50 E 23 2 " }, { "code": null, "e": 3233, "s": 3187, "text": "Now we can access each grade as shown below −" }, { "code": null, "e": 3708, "s": 3233, "text": "> Split_based_on_Grades[[1]]\n Grades Age Category\n1 A 25 6\n6 A 29 8\n11 A 27 10\n16 A 10 6\n21 A 9 8\n26 A 25 7\n31 A 10 9\n36 A 1 1\n41 A 10 7\n46 A 20 10\n> Split_based_on_Grades[[4]]\n Grades Age Category\n4 D 1 9\n9 D 14 7\n14 D 21 2 \n19 D 10 3\n24 D 5 6\n29 D 5 8\n34 D 12 7\n39 D 6 1\n44 D 20 6\n49 D 25 3" } ]
🎲 Picking a Random Sample From a Non-Uniform Distribution | by Marte Løge | Towards Data Science
I bet you have come across the situation where you have to pick a random item for a set of items? This has a quite simple solution as all items have the same probability of being picked. But what if each item has a different probability for being picked — in other words — the distribution is not uniform. How can this be solved? It is not a hard problem to solve, but you might not find yourself bumping into this problem very often in your daily programming work. Let's have a look at an example and solve it using java, python, and javascript. When you go fishing — what fish biting on the hook is random. Buy taking some notes you might see more occurrences of some types of fish than others — meaning that the probability of getting some types of fish are higher than others. Today we will go fishing together at our imaginary place where you will find 3 kinds of fishes: cod, halibut, and mackerel. Based on my last 50 catches I caught 15 cod, 5 halibut, and 30 mackerel. Based on the observations, the likelihood of getting a mackerel is 60%, 30% for getting cod, and only 10% of getting a halibut on the hook. halibut: 10% (5)cod: 30% (15)mackerel: 60% (30) Let's make a “fishing simulator” simulating our fishing trip. If we got the same probability of getting any kind of fish we could just run a random generator giving us a number between say 1–3 telling what kind of fish we got. Tada! Unfortunately — the world does not work that way. How can we then simulate the fishing experience using the non-uniform probability distribution for cod, halibut, and mackerel? The solution is “aggregated probability”. If you want to win a lottery you buy yourself as many tickets as you can. Because when they call a number you are more likely to be the winner. We are gonna think in the same way picking a random number in a non-uniform distribution! So if we have 10 tickets, the cod will get 1 ticket, the halibut will get 3 tickets and the mackerel will get 6 tickets. halibut: 10% (5) - 10 tickets --> ticket #1cod: 30% (15) - 30 tickets --> ticket #2 - #4mackerel: 60% (30) - 60 tickets --> ticket #5 - #10 Now, to try our luck we can run a random generator giving us a number between 1 and 10 telling us what fish we got 🎉 Since the mackerel has more tickets (eg has a higher likelihood of being caught) it will have more chances of being picked. You maybe have the same problem you want to solve so I put together some different solutions written in different languages. It is just one way of solving it and each language probably has many different neat solutions. If you have a nicer way of solving this — please share with us all in a comment 🙌 In Java, you can use a TreeMap to make it easy for you to catch a random fish. Add all fishes with the aggregated probabilities (eg giving out the “tickets”). The TreeMap has a built-in higherEntry that will pick the items aggregated probability strictly greater than the given random number. Here, the halibut has the tickets up to 0.1, the cod has the tickets starting from 0.1 to 0.4 and the mackerel has the tickets starting from 0.4 to 1. TreeMap<Double, Fish> fishes = new TreeMap<>();movies.put(0.1, new Movie("Halibut")); //0.1movies.put(0.4, new Movie("Cod")); //0.1 + 0.3 --> 0.4movies.put(1.0, new Movie("Mackerel")); //0.4 + 0.6 --> 1Fish catched = fishes.higherEntry(Math.random()).getValue(); In javascript, we first assign the fishes their tickets using the map function by aggregate the probability. Then we use find for finding the fish closest to the random aggregated probability. const fishes = [ {type: "halibut", prob: 0.1}, {type: "cod", prob: 0.3}, {type: "mackerel", prob: 0.6}];const random = Math.random();let aggregated_probability = 0;const randomFish = fishes.map((fish) => { aggregated_probability += fish.prob; return { type: fish.type, prob: aggregated_probability };}).find((fish) => fish.prob >= random);// outputs random fish When using a map on fishes it will give us a new array looking like this: [{type: "halibut", prob: 0.1}, {type: "cod", prob: 0.4}, {type: "mackerel", prob: 1.0}] The find will look for the fish having the random lottery in their lottery range. For example — if Math.random() results in the number 0.678 the mackerel are caught. If Math.random() results in 0.0923 a halibut are caught. For python, NumPy has already solved this for us with the “random choice”. You input your elements fishes, the number of times you want to “draw”/fish (1), and the probability distribution [0.1, 0.3, 0.6]: import numpy as npfish = ['halibut', 'cod', 'mackerel']np.random.choice(fish, 1, p=[0.1, 0.3, 0.6])# outputs random selected fish [<fish>] Happy coding 🙌
[ { "code": null, "e": 358, "s": 171, "text": "I bet you have come across the situation where you have to pick a random item for a set of items? This has a quite simple solution as all items have the same probability of being picked." }, { "code": null, "e": 637, "s": 358, "text": "But what if each item has a different probability for being picked — in other words — the distribution is not uniform. How can this be solved? It is not a hard problem to solve, but you might not find yourself bumping into this problem very often in your daily programming work." }, { "code": null, "e": 718, "s": 637, "text": "Let's have a look at an example and solve it using java, python, and javascript." }, { "code": null, "e": 952, "s": 718, "text": "When you go fishing — what fish biting on the hook is random. Buy taking some notes you might see more occurrences of some types of fish than others — meaning that the probability of getting some types of fish are higher than others." }, { "code": null, "e": 1289, "s": 952, "text": "Today we will go fishing together at our imaginary place where you will find 3 kinds of fishes: cod, halibut, and mackerel. Based on my last 50 catches I caught 15 cod, 5 halibut, and 30 mackerel. Based on the observations, the likelihood of getting a mackerel is 60%, 30% for getting cod, and only 10% of getting a halibut on the hook." }, { "code": null, "e": 1337, "s": 1289, "text": "halibut: 10% (5)cod: 30% (15)mackerel: 60% (30)" }, { "code": null, "e": 1399, "s": 1337, "text": "Let's make a “fishing simulator” simulating our fishing trip." }, { "code": null, "e": 1747, "s": 1399, "text": "If we got the same probability of getting any kind of fish we could just run a random generator giving us a number between say 1–3 telling what kind of fish we got. Tada! Unfortunately — the world does not work that way. How can we then simulate the fishing experience using the non-uniform probability distribution for cod, halibut, and mackerel?" }, { "code": null, "e": 2023, "s": 1747, "text": "The solution is “aggregated probability”. If you want to win a lottery you buy yourself as many tickets as you can. Because when they call a number you are more likely to be the winner. We are gonna think in the same way picking a random number in a non-uniform distribution!" }, { "code": null, "e": 2144, "s": 2023, "text": "So if we have 10 tickets, the cod will get 1 ticket, the halibut will get 3 tickets and the mackerel will get 6 tickets." }, { "code": null, "e": 2284, "s": 2144, "text": "halibut: 10% (5) - 10 tickets --> ticket #1cod: 30% (15) - 30 tickets --> ticket #2 - #4mackerel: 60% (30) - 60 tickets --> ticket #5 - #10" }, { "code": null, "e": 2525, "s": 2284, "text": "Now, to try our luck we can run a random generator giving us a number between 1 and 10 telling us what fish we got 🎉 Since the mackerel has more tickets (eg has a higher likelihood of being caught) it will have more chances of being picked." }, { "code": null, "e": 2827, "s": 2525, "text": "You maybe have the same problem you want to solve so I put together some different solutions written in different languages. It is just one way of solving it and each language probably has many different neat solutions. If you have a nicer way of solving this — please share with us all in a comment 🙌" }, { "code": null, "e": 3120, "s": 2827, "text": "In Java, you can use a TreeMap to make it easy for you to catch a random fish. Add all fishes with the aggregated probabilities (eg giving out the “tickets”). The TreeMap has a built-in higherEntry that will pick the items aggregated probability strictly greater than the given random number." }, { "code": null, "e": 3271, "s": 3120, "text": "Here, the halibut has the tickets up to 0.1, the cod has the tickets starting from 0.1 to 0.4 and the mackerel has the tickets starting from 0.4 to 1." }, { "code": null, "e": 3534, "s": 3271, "text": "TreeMap<Double, Fish> fishes = new TreeMap<>();movies.put(0.1, new Movie(\"Halibut\")); //0.1movies.put(0.4, new Movie(\"Cod\")); //0.1 + 0.3 --> 0.4movies.put(1.0, new Movie(\"Mackerel\")); //0.4 + 0.6 --> 1Fish catched = fishes.higherEntry(Math.random()).getValue();" }, { "code": null, "e": 3727, "s": 3534, "text": "In javascript, we first assign the fishes their tickets using the map function by aggregate the probability. Then we use find for finding the fish closest to the random aggregated probability." }, { "code": null, "e": 4094, "s": 3727, "text": "const fishes = [ {type: \"halibut\", prob: 0.1}, {type: \"cod\", prob: 0.3}, {type: \"mackerel\", prob: 0.6}];const random = Math.random();let aggregated_probability = 0;const randomFish = fishes.map((fish) => { aggregated_probability += fish.prob; return { type: fish.type, prob: aggregated_probability };}).find((fish) => fish.prob >= random);// outputs random fish" }, { "code": null, "e": 4168, "s": 4094, "text": "When using a map on fishes it will give us a new array looking like this:" }, { "code": null, "e": 4256, "s": 4168, "text": "[{type: \"halibut\", prob: 0.1}, {type: \"cod\", prob: 0.4}, {type: \"mackerel\", prob: 1.0}]" }, { "code": null, "e": 4479, "s": 4256, "text": "The find will look for the fish having the random lottery in their lottery range. For example — if Math.random() results in the number 0.678 the mackerel are caught. If Math.random() results in 0.0923 a halibut are caught." }, { "code": null, "e": 4685, "s": 4479, "text": "For python, NumPy has already solved this for us with the “random choice”. You input your elements fishes, the number of times you want to “draw”/fish (1), and the probability distribution [0.1, 0.3, 0.6]:" }, { "code": null, "e": 4824, "s": 4685, "text": "import numpy as npfish = ['halibut', 'cod', 'mackerel']np.random.choice(fish, 1, p=[0.1, 0.3, 0.6])# outputs random selected fish [<fish>]" } ]
How to add image to the menu item in JavaFX?
A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class. A menu item is an option in the menu it is represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it. The menu item class has a property named graphic, representing the optional graphical element for the menu item. Generally, images are used along with the title of the item. You can set the value to this property using the setGraphic() method, this method accepts an ImageView object as a parameter. Or, You can pass the ImageView object representing the required image, as a parameter to the conductor of the MenuItem class, while instantiating it, along with the name of the menu item (String). To add an image to a menu item − Create an ImageView object using the image object bypassing the path for the required graphic. Create an ImageView object using the image object bypassing the path for the required graphic. Create a menu item by instantiating the MenuItem class by passing the ImageView object and the name of the item as parameters to its constructor. Create a menu item by instantiating the MenuItem class by passing the ImageView object and the name of the item as parameters to its constructor. Create a menu by instantiating the Menu class add the above-created menu item to it. Create a menu by instantiating the Menu class add the above-created menu item to it. Instantiate the MenuBar class bypassing the menus as a parameter to its constructor. Instantiate the MenuBar class bypassing the menus as a parameter to its constructor. Add the MenuBar to the scene. Add the MenuBar to the scene. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.stage.Stage; public class MenuItemAddingImages extends Application { public void start(Stage stage) { //Creating image view files ImageView imgView1 = new ImageView("UIControls/open.png"); imgView1.setFitWidth(20); imgView1.setFitHeight(20); ImageView imgView2 = new ImageView("UIControls/Save.png"); imgView2.setFitWidth(20); imgView2.setFitHeight(20); ImageView imgView3 = new ImageView("UIControls/Exit.png"); imgView3.setFitWidth(20); imgView3.setFitHeight(20); //Creating menu Menu fileMenu = new Menu("File"); //Creating menu Items MenuItem item1 = new MenuItem("Open File", imgView1); MenuItem item2 = new MenuItem("Save file", imgView2); MenuItem item3 = new MenuItem("Exit", imgView3); //Adding all the menu items to the menu fileMenu.getItems().addAll(item1, item2, item3); //Creating a menu bar and adding menu to it. MenuBar menuBar = new MenuBar(fileMenu); menuBar.setTranslateX(200); menuBar.setTranslateY(20); //Setting the stage Group root = new Group(menuBar); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Menu Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1248, "s": 1062, "text": "A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class." }, { "code": null, "e": 1464, "s": 1248, "text": "A menu item is an option in the menu it is represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it." }, { "code": null, "e": 1764, "s": 1464, "text": "The menu item class has a property named graphic, representing the optional graphical element for the menu item. Generally, images are used along with the title of the item. You can set the value to this property using the setGraphic() method, this method accepts an ImageView object as a parameter." }, { "code": null, "e": 1961, "s": 1764, "text": "Or, You can pass the ImageView object representing the required image, as a parameter to the conductor of the MenuItem class, while instantiating it, along with the name of the menu item (String)." }, { "code": null, "e": 1994, "s": 1961, "text": "To add an image to a menu item −" }, { "code": null, "e": 2089, "s": 1994, "text": "Create an ImageView object using the image object bypassing the path for the required graphic." }, { "code": null, "e": 2184, "s": 2089, "text": "Create an ImageView object using the image object bypassing the path for the required graphic." }, { "code": null, "e": 2330, "s": 2184, "text": "Create a menu item by instantiating the MenuItem class by passing the ImageView object and the name of the item as parameters to its constructor." }, { "code": null, "e": 2476, "s": 2330, "text": "Create a menu item by instantiating the MenuItem class by passing the ImageView object and the name of the item as parameters to its constructor." }, { "code": null, "e": 2561, "s": 2476, "text": "Create a menu by instantiating the Menu class add the above-created menu item to it." }, { "code": null, "e": 2646, "s": 2561, "text": "Create a menu by instantiating the Menu class add the above-created menu item to it." }, { "code": null, "e": 2731, "s": 2646, "text": "Instantiate the MenuBar class bypassing the menus as a parameter to its constructor." }, { "code": null, "e": 2816, "s": 2731, "text": "Instantiate the MenuBar class bypassing the menus as a parameter to its constructor." }, { "code": null, "e": 2846, "s": 2816, "text": "Add the MenuBar to the scene." }, { "code": null, "e": 2876, "s": 2846, "text": "Add the MenuBar to the scene." }, { "code": null, "e": 4509, "s": 2876, "text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class MenuItemAddingImages extends Application {\n public void start(Stage stage) {\n //Creating image view files\n ImageView imgView1 = new ImageView(\"UIControls/open.png\");\n imgView1.setFitWidth(20);\n imgView1.setFitHeight(20);\n ImageView imgView2 = new ImageView(\"UIControls/Save.png\");\n imgView2.setFitWidth(20);\n imgView2.setFitHeight(20);\n ImageView imgView3 = new ImageView(\"UIControls/Exit.png\");\n imgView3.setFitWidth(20);\n imgView3.setFitHeight(20);\n //Creating menu\n Menu fileMenu = new Menu(\"File\");\n //Creating menu Items\n MenuItem item1 = new MenuItem(\"Open File\", imgView1);\n MenuItem item2 = new MenuItem(\"Save file\", imgView2);\n MenuItem item3 = new MenuItem(\"Exit\", imgView3);\n //Adding all the menu items to the menu\n fileMenu.getItems().addAll(item1, item2, item3);\n //Creating a menu bar and adding menu to it.\n MenuBar menuBar = new MenuBar(fileMenu);\n menuBar.setTranslateX(200);\n menuBar.setTranslateY(20);\n //Setting the stage\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Menu Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Distinct permutations of a string containing duplicates using HashSet in Java - GeeksforGeeks
19 Sep, 2019 Given a string str that may contain duplicate characters, the task is to print all the distinct permutations of the given string such that no permutation is repeated in the output. Examples: Input: str = “ABA”Output:ABAAABBAA Input: str = “ABC”Output:ABCACBBACBCACBACAB Approach: An approach to generate all the permutations of a given string has been discussed in this article. All the permutations generated by this approach can be stored in a HashSet in order to avoid duplicates. Below is the implementation of the above approach: // Java implementation of the approachimport java.util.HashSet; public class GFG { // To store all the generated permutations public static HashSet<String> h = new HashSet<String>(); public static void permute(char s[], int i, int n) { // If the permutation is complete if (i == n) { // If set doesn't contain // the permutation already if (!(h.contains(String.copyValueOf(s)))) { h.add(String.copyValueOf(s)); // Print the generated permutation System.out.println(s); } } else { // One by one swap the jth // character with the ith for (int j = i; j <= n; j++) { // Swapping a[i] and a[j]; char temp = s[i]; s[i] = s[j]; s[j] = temp; // Revert the swapping permute(s, i + 1, n); temp = s[i]; s[i] = s[j]; s[j] = temp; } } } // Driver code public static void main(String args[]) { char s[] = { 'A', 'B', 'A' }; permute(s, 0, s.length - 1); }} ABA AAB BAA permutation Strings Strings permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 String Coding Problems for Interviews Hill Cipher Naive algorithm for Pattern Searching Vigenère Cipher How to Append a Character to a String in C Convert character array to string in C++ Reverse words in a given String in Python Print all the duplicates in the input string Converting Roman Numerals to Decimal lying between 1 to 3999 Print all subsequences of a string
[ { "code": null, "e": 24772, "s": 24744, "text": "\n19 Sep, 2019" }, { "code": null, "e": 24953, "s": 24772, "text": "Given a string str that may contain duplicate characters, the task is to print all the distinct permutations of the given string such that no permutation is repeated in the output." }, { "code": null, "e": 24963, "s": 24953, "text": "Examples:" }, { "code": null, "e": 24998, "s": 24963, "text": "Input: str = “ABA”Output:ABAAABBAA" }, { "code": null, "e": 25042, "s": 24998, "text": "Input: str = “ABC”Output:ABCACBBACBCACBACAB" }, { "code": null, "e": 25256, "s": 25042, "text": "Approach: An approach to generate all the permutations of a given string has been discussed in this article. All the permutations generated by this approach can be stored in a HashSet in order to avoid duplicates." }, { "code": null, "e": 25307, "s": 25256, "text": "Below is the implementation of the above approach:" }, { "code": "// Java implementation of the approachimport java.util.HashSet; public class GFG { // To store all the generated permutations public static HashSet<String> h = new HashSet<String>(); public static void permute(char s[], int i, int n) { // If the permutation is complete if (i == n) { // If set doesn't contain // the permutation already if (!(h.contains(String.copyValueOf(s)))) { h.add(String.copyValueOf(s)); // Print the generated permutation System.out.println(s); } } else { // One by one swap the jth // character with the ith for (int j = i; j <= n; j++) { // Swapping a[i] and a[j]; char temp = s[i]; s[i] = s[j]; s[j] = temp; // Revert the swapping permute(s, i + 1, n); temp = s[i]; s[i] = s[j]; s[j] = temp; } } } // Driver code public static void main(String args[]) { char s[] = { 'A', 'B', 'A' }; permute(s, 0, s.length - 1); }}", "e": 26519, "s": 25307, "text": null }, { "code": null, "e": 26532, "s": 26519, "text": "ABA\nAAB\nBAA\n" }, { "code": null, "e": 26544, "s": 26532, "text": "permutation" }, { "code": null, "e": 26552, "s": 26544, "text": "Strings" }, { "code": null, "e": 26560, "s": 26552, "text": "Strings" }, { "code": null, "e": 26572, "s": 26560, "text": "permutation" }, { "code": null, "e": 26670, "s": 26572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26679, "s": 26670, "text": "Comments" }, { "code": null, "e": 26692, "s": 26679, "text": "Old Comments" }, { "code": null, "e": 26737, "s": 26692, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 26749, "s": 26737, "text": "Hill Cipher" }, { "code": null, "e": 26787, "s": 26749, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 26804, "s": 26787, "text": "Vigenère Cipher" }, { "code": null, "e": 26847, "s": 26804, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 26888, "s": 26847, "text": "Convert character array to string in C++" }, { "code": null, "e": 26930, "s": 26888, "text": "Reverse words in a given String in Python" }, { "code": null, "e": 26975, "s": 26930, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 27036, "s": 26975, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" } ]
How to give a limit to the input field in HTML?
The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. The max and min attributes are used with number, range, date, datetime, datetime-local, month, time and week input types. You can try to run the following code to give a limit to the input field in HTML − <!DOCTYPE html> <html> <head> <title>HTML input number</title> </head> <body> <form action = "" method = "get"> Mention any number between 1 to 10 <input type="number" name="num" min="1" max="10"><br> <input type="submit" value="Submit"> </form> </body> </html>
[ { "code": null, "e": 1267, "s": 1062, "text": "The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively." }, { "code": null, "e": 1389, "s": 1267, "text": "The max and min attributes are used with number, range, date, datetime, datetime-local, month, time and week input types." }, { "code": null, "e": 1472, "s": 1389, "text": "You can try to run the following code to give a limit to the input field in HTML −" }, { "code": null, "e": 1791, "s": 1472, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML input number</title>\n </head>\n <body>\n <form action = \"\" method = \"get\">\n Mention any number between 1 to 10\n <input type=\"number\" name=\"num\" min=\"1\" max=\"10\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" } ]
PHP mysqli_fetch_field() Function
A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries. The mysqli_fetch_field() function accepts a result object as a parameter and returns the definition information of the next column/field in the form of an object. mysqli_fetch_field($result); result(Mandatory) This is an identifier representing a result object. The PHP mysqli_fetch_field() function returns an object containing the definition information of a field in the given result. This function returns FALSE in case of no information. The object returned contains following properties $minus; name name orgname orgname table table orgtable orgtable max_length max_length length length charsetnr charsetnr flags flags type type decimals decimals This function was first introduced in PHP Version 5 and works works in all the later versions. Following example demonstrates the usage of the mysqli_fetch_field() function (in procedural style) − <?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("Table Created.....\n"); mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); print("Record Inserted.....\n"); //Retrieving the contents of the table $res = mysqli_query($con, "SELECT * FROM myplayers"); //Fetching the fields while($info = mysqli_fetch_field($res)){ //Current field $currentfield = mysqli_field_tell($res); print("Current Field: ".$currentfield."\n"); print("Name: ".$info->name."\n"); print("Type: ".$info->type."\n"); } //Closing the statement mysqli_free_result($res); //Closing the connection mysqli_close($con); ?> This will produce following result − Table Created..... Record Inserted..... Current Field: 1 Name: ID Type: 3 Current Field: 2 Name: First_Name Type: 253 Current Field: 3 Name: Last_Name Type: 253 Current Field: 4 Name: Place_Of_Birth Type: 253 Current Field: 5 Name: Country Type: 253 In object oriented style the syntax of this function is $result->fetch_field; Following is the example of this function in object oriented style $minus; <?php //Creating a connection $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Table Created.....\n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; //Executing the statement $stmt->execute(); //Retrieving the result $result = $stmt->get_result(); //Current Field while($info = $result->fetch_field()){ $field = $result->current_field; print("Current Field: ".$field."\n"); print("Field Name: ".$info->name."\n"); } //Closing the statement $stmt->close(); //Closing the connection $con->close(); ?> This will produce following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2892, "s": 2757, "text": "A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries." }, { "code": null, "e": 3055, "s": 2892, "text": "The mysqli_fetch_field() function accepts a result object as a parameter and returns the definition information of the next column/field in the form of an object." }, { "code": null, "e": 3085, "s": 3055, "text": "mysqli_fetch_field($result);\n" }, { "code": null, "e": 3103, "s": 3085, "text": "result(Mandatory)" }, { "code": null, "e": 3155, "s": 3103, "text": "This is an identifier representing a result object." }, { "code": null, "e": 3336, "s": 3155, "text": "The PHP mysqli_fetch_field() function returns an object containing the definition information of a field in the given result. This function returns FALSE in case of no information." }, { "code": null, "e": 3394, "s": 3336, "text": "The object returned contains following properties $minus;" }, { "code": null, "e": 3399, "s": 3394, "text": "name" }, { "code": null, "e": 3404, "s": 3399, "text": "name" }, { "code": null, "e": 3412, "s": 3404, "text": "orgname" }, { "code": null, "e": 3420, "s": 3412, "text": "orgname" }, { "code": null, "e": 3426, "s": 3420, "text": "table" }, { "code": null, "e": 3432, "s": 3426, "text": "table" }, { "code": null, "e": 3441, "s": 3432, "text": "orgtable" }, { "code": null, "e": 3450, "s": 3441, "text": "orgtable" }, { "code": null, "e": 3461, "s": 3450, "text": "max_length" }, { "code": null, "e": 3472, "s": 3461, "text": "max_length" }, { "code": null, "e": 3479, "s": 3472, "text": "length" }, { "code": null, "e": 3486, "s": 3479, "text": "length" }, { "code": null, "e": 3496, "s": 3486, "text": "charsetnr" }, { "code": null, "e": 3506, "s": 3496, "text": "charsetnr" }, { "code": null, "e": 3512, "s": 3506, "text": "flags" }, { "code": null, "e": 3518, "s": 3512, "text": "flags" }, { "code": null, "e": 3523, "s": 3518, "text": "type" }, { "code": null, "e": 3528, "s": 3523, "text": "type" }, { "code": null, "e": 3537, "s": 3528, "text": "decimals" }, { "code": null, "e": 3546, "s": 3537, "text": "decimals" }, { "code": null, "e": 3641, "s": 3546, "text": "This function was first introduced in PHP Version 5 and works works in all the later versions." }, { "code": null, "e": 3743, "s": 3641, "text": "Following example demonstrates the usage of the mysqli_fetch_field() function (in procedural style) −" }, { "code": null, "e": 4837, "s": 3743, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created.....\\n\");\n mysqli_query($con, \"INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n mysqli_query($con, \"INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')\");\n print(\"Record Inserted.....\\n\");\n\n //Retrieving the contents of the table\n $res = mysqli_query($con, \"SELECT * FROM myplayers\");\n\n //Fetching the fields\n while($info = mysqli_fetch_field($res)){\n //Current field\n $currentfield = mysqli_field_tell($res);\n print(\"Current Field: \".$currentfield.\"\\n\");\n print(\"Name: \".$info->name.\"\\n\");\n print(\"Type: \".$info->type.\"\\n\");\n }\n\n //Closing the statement\n mysqli_free_result($res);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 4874, "s": 4837, "text": "This will produce following result −" }, { "code": null, "e": 5125, "s": 4874, "text": "Table Created.....\nRecord Inserted.....\nCurrent Field: 1\nName: ID\nType: 3\nCurrent Field: 2\nName: First_Name\nType: 253\nCurrent Field: 3\nName: Last_Name\nType: 253\nCurrent Field: 4\nName: Place_Of_Birth\nType: 253\nCurrent Field: 5\nName: Country\nType: 253\n" }, { "code": null, "e": 5278, "s": 5125, "text": "In object oriented style the syntax of this function is $result->fetch_field; Following is the example of this function in object oriented style $minus;" }, { "code": null, "e": 6132, "s": 5278, "text": "<?php\n //Creating a connection\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n $con -> query(\"CREATE TABLE Test(Name VARCHAR(255), AGE INT)\");\n $con -> query(\"insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)\");\n print(\"Table Created.....\\n\");\n\n $stmt = $con -> prepare( \"SELECT * FROM Test WHERE Name in(?, ?)\");\n $stmt -> bind_param(\"ss\", $name1, $name2);\n $name1 = 'Raju';\n $name2 = 'Rahman';\n\n //Executing the statement\n $stmt->execute();\n\n //Retrieving the result\n $result = $stmt->get_result();\n\n //Current Field\n while($info = $result->fetch_field()){\n $field = $result->current_field;\n print(\"Current Field: \".$field.\"\\n\");\n print(\"Field Name: \".$info->name.\"\\n\");\n }\n\n //Closing the statement\n $stmt->close();\n\n //Closing the connection\n $con->close();\n?>" }, { "code": null, "e": 6169, "s": 6132, "text": "This will produce following result −" }, { "code": null, "e": 6205, "s": 6172, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 6221, "s": 6205, "text": " Malhar Lathkar" }, { "code": null, "e": 6254, "s": 6221, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6265, "s": 6254, "text": " Syed Raza" }, { "code": null, "e": 6300, "s": 6265, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6317, "s": 6300, "text": " Frahaan Hussain" }, { "code": null, "e": 6350, "s": 6317, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6365, "s": 6350, "text": " Nivedita Jain" }, { "code": null, "e": 6400, "s": 6365, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 6412, "s": 6400, "text": " Azaz Patel" }, { "code": null, "e": 6447, "s": 6412, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6475, "s": 6447, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6482, "s": 6475, "text": " Print" }, { "code": null, "e": 6493, "s": 6482, "text": " Add Notes" } ]
How to disable Home and other system buttons in Android using Kotlin?
This example demonstrates how to disable Home and other system buttons in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:padding="8dp" android:text="Tutorials Point" android:textColor="@color/colorPrimaryDark" android:textSize="48sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Disabled Home and Other System buttons" android:textAlignment="center" android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) hideNavigationBar() } private fun hideNavigationBar() { val decorView: View = this.window.decorView val uiOptions: Int = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE) val timer = Timer() val task: TimerTask = object : TimerTask() { override fun run() { runOnUiThread { decorView.systemUiVisibility = uiOptions } } } timer.scheduleAtFixedRate(task, 1, 2) } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q1"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1158, "s": 1062, "text": "This example demonstrates how to disable Home and other system buttons in Android using Kotlin." }, { "code": null, "e": 1286, "s": 1158, "text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project." }, { "code": null, "e": 1351, "s": 1286, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2401, "s": 1351, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Disabled Home and Other System buttons\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n </RelativeLayout>" }, { "code": null, "e": 2456, "s": 2401, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3503, "s": 2456, "text": "import android.os.Bundle\nimport android.view.View\nimport androidx.appcompat.app.AppCompatActivity\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n override fun onWindowFocusChanged(hasFocus: Boolean) {\n super.onWindowFocusChanged(hasFocus)\n hideNavigationBar()\n }\n private fun hideNavigationBar() {\n val decorView: View = this.window.decorView\n val uiOptions: Int = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION\n or View.SYSTEM_UI_FLAG_FULLSCREEN\n or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)\n val timer = Timer()\n val task: TimerTask = object : TimerTask() {\n override fun run() {\n runOnUiThread { decorView.systemUiVisibility = uiOptions }\n }\n }\n timer.scheduleAtFixedRate(task, 1, 2)\n }\n}" }, { "code": null, "e": 3558, "s": 3503, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4224, "s": 3558, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"app.com.q1\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4572, "s": 4224, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Form a palindrome | Practice | GeeksforGeeks
Given a string, find the minimum number of characters to be inserted to convert it to palindrome. For Example: ab: Number of insertions required is 1. bab or aba aa: Number of insertions required is 0. aa abcd: Number of insertions required is 3. dcbabcd Example 1: Input: str = "abcd" Output: 3 Explanation: Inserted character marked with bold characters in dcbabcd Example 2: Input: str = "aa" Output: 0 Explanation:"aa" is already a palindrome. Your Task: You don't need to read input or print anything. Your task is to complete the function countMin() which takes the string str as inputs and returns the answer. Expected Time Complexity: O(N2), N = |str| Expected Auxiliary Space: O(N2) Constraints: 1 ≤ |str| ≤ 103 str contains only lower case alphabets. 0 creepypirate2 weeks ago sab aditya verma se hi padh ke aaye h 0 aishwaryadwani97993 weeks ago class Solution { static int getLCS(String x, String y, int n, int m) { int t[][] = new int[n + 1][m + 1]; for (int i = 0; i < n + 1; i++) { for (int j = 0; j < m + 1; j++) { if (i == 0 || j == 0) t[i][j] = 0; } } for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { if (x.charAt(i - 1) == y.charAt(j - 1)) t[i][j] = 1 + t[i - 1][j - 1]; else t[i][j] = Math.max(t[i - 1][j], t[i][j - 1]); } } return t[n][m]; } static int getLPS(String str) { String x = str; String y = ""; for (int i = str.length() - 1; i >= 0; i--) y += x.charAt(i); int lcs = getLCS(x, y, x.length(), y.length()); return lcs; } static int countMin(String str) { int lps = getLPS(str); return str.length() - lps; }} +1 ayushkumar54511 month ago →All credit goes to Aditya Verma :-) int dp[1001][1001]; int plaindrome(string &a,string &b,int n,int m){ for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } } return dp[n][m]; } int countMin(string str){ string b=str; int n=str.size(); int m=b.size(); reverse(str.begin(),str.end()); int res=plaindrome(str,b,n,m); if(str==b){ return 0; } else{ return (n-res); } +1 amonk1 month ago my approach→ first calculate the lcs of the string with it's reverse. Than check if the lcs is 0 it means every we need to insert len(string)-1 characters to make it a palindrome. If the lcs is same as the length of the string than it is already a palindrome so simply return 0; else return len(string)-lcs(string,reverse(string)); 0 geminicode1 month ago my approach in python.. def countMin(self, s): # code here dp = [[0 for i in range(len(s))] for j in range(len(s))] for g in range(len(s)): for i,j in zip(range(0,len(s)-g),range(g,len(s))): if g == 0: dp[i][j] = 0 elif g == 1: if s[i] == s[j]: dp[i][j] = 0 else: dp[i][j] =1 else: if s[i] == s[j]: dp[i][j] = dp[i+1][j-1] else: dp[i][j] = 1 + min(dp[i+1][j],dp[i][j-1]) #print(dp) return dp[0][len(s)-1] 0 amansidd178612 months ago string rev(string s){ string ans =""; for(int i=s.size()-1; i>=0; i--) ans+=s[i]; return ans; } int countMin(string A){ //complete the function here string s2 = rev(A); // vector<vector<int>> dp(A.size()+1,vector<int>(A.size()+1,0)); vector<int> prev(A.size()+1,0),curr(A.size()+1,0); for(int i=0;i<=A.size();i++) prev[i]=0; for(int i=1; i<=A.size();i++){ for(int j=1;j<=A.size();j++){ if(A[i-1]==s2[j-1]){ curr[j] = 1 + prev[j-1]; } else{ curr[j] = max(prev[j],curr[j-1]); } } prev = curr; } return A.size()-prev[A.size()]; }}; 0 aryansinha18182 months ago This is my first code submission on my own on GFG.... int lcs(string x, string y,int n){ int t[n+1][n+1]; for (int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j++) { if (i == 0 || j == 0) { t[i][j] = 0; } } } for (int i = 1; i < n + 1; i++) { for (int j = 1; j < n + 1; j++) { if (x[i - 1] == y[j - 1]) { t[i][j] = 1 + t[i - 1][j - 1]; } else { t[i][j] = max(t[i][j - 1], t[i - 1][j]); } } } return t[n][n]; } int countMin(string str) { //complete the function here int n = str.length(); string b = str; reverse(b.begin(),b.end()); int LCSLen = lcs(str,b,n); if(str == b){ return 0; } else { return (str.length() - LCSLen); } } 0 tirtha19025682 months ago class Solution{ static int countMin(String str) { int n = str.length(); StringBuilder sb = new StringBuilder(str); String t = sb.reverse().toString(); return n - lcs(str,t,n,n); } static int lcs(String a ,String b,int m,int n){ int[][]dp = new int[m+1][n+1]; for(int i=1;i<dp.length;i++){ for(int j=1;j<dp[0].length;j++){ if(a.charAt(i-1) == b.charAt(j-1)){ dp[i][j] = dp[i-1][j-1] + 1; }else{ dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); } } } return dp[m][n]; } } 0 starcode012 months ago // → this problem is same as minimum number of deletion to //form a palindrome same code also my code is in java top-down class Solution{ static int countMin(String str) { StringBuilder sb=new StringBuilder(str); sb.reverse(); int n= str.length(); int m = sb.length(); int dp[][] = new int[n+1][m+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0||j==0) dp[i][j] = 0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(str.charAt(i-1)==sb.charAt(j-1)) dp[i][j] = 1+ dp[i-1][j-1]; else{ dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); } } } return n-dp[m][n]; }} 0 amitanand22 months ago class Solution{ public: int lcs(string x, string y, int n) { int t[n+1][n+1]; for (int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j++) { if (i == 0 || j == 0) { t[i][j] = 0; } } } for (int i = 1; i < n + 1; i++) { for (int j = 1; j < n + 1; j++) { if (x[i - 1] == y[j - 1]) { t[i][j] = 1 + t[i - 1][j - 1]; } else { t[i][j] = max(t[i][j - 1], t[i - 1][j]); } } } return t[n][n]; } int countMin(string str){ //complete the function here string x , y; x = str; y = x; reverse(y.begin() , y.end()); if (x == y) { return 0; } else { int length = lcs(x, y, x.length()); int noOfInsertiton = x.length() - length; return noOfInsertiton; } } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 493, "s": 238, "text": "Given a string, find the minimum number of characters to be inserted to convert it to palindrome.\nFor Example:\nab: Number of insertions required is 1. bab or aba\naa: Number of insertions required is 0. aa\nabcd: Number of insertions required is 3. dcbabcd" }, { "code": null, "e": 505, "s": 493, "text": "\nExample 1:" }, { "code": null, "e": 607, "s": 505, "text": "Input: str = \"abcd\"\nOutput: 3\nExplanation: Inserted character marked\nwith bold characters in dcbabcd\n" }, { "code": null, "e": 618, "s": 607, "text": "Example 2:" }, { "code": null, "e": 688, "s": 618, "text": "Input: str = \"aa\"\nOutput: 0\nExplanation:\"aa\" is already a palindrome." }, { "code": null, "e": 1006, "s": 688, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countMin() which takes the string str as inputs and returns the answer.\n\nExpected Time Complexity: O(N2), N = |str|\nExpected Auxiliary Space: O(N2)\n\nConstraints:\n1 ≤ |str| ≤ 103\nstr contains only lower case alphabets." }, { "code": null, "e": 1008, "s": 1006, "text": "0" }, { "code": null, "e": 1032, "s": 1008, "text": "creepypirate2 weeks ago" }, { "code": null, "e": 1070, "s": 1032, "text": "sab aditya verma se hi padh ke aaye h" }, { "code": null, "e": 1072, "s": 1070, "text": "0" }, { "code": null, "e": 1102, "s": 1072, "text": "aishwaryadwani97993 weeks ago" }, { "code": null, "e": 1387, "s": 1102, "text": "class Solution { static int getLCS(String x, String y, int n, int m) { int t[][] = new int[n + 1][m + 1]; for (int i = 0; i < n + 1; i++) { for (int j = 0; j < m + 1; j++) { if (i == 0 || j == 0) t[i][j] = 0; } }" }, { "code": null, "e": 1678, "s": 1387, "text": " for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { if (x.charAt(i - 1) == y.charAt(j - 1)) t[i][j] = 1 + t[i - 1][j - 1]; else t[i][j] = Math.max(t[i - 1][j], t[i][j - 1]); } }" }, { "code": null, "e": 1705, "s": 1678, "text": " return t[n][m]; }" }, { "code": null, "e": 1861, "s": 1705, "text": " static int getLPS(String str) { String x = str; String y = \"\"; for (int i = str.length() - 1; i >= 0; i--) y += x.charAt(i);" }, { "code": null, "e": 1938, "s": 1861, "text": " int lcs = getLCS(x, y, x.length(), y.length()); return lcs; }" }, { "code": null, "e": 2042, "s": 1938, "text": " static int countMin(String str) { int lps = getLPS(str); return str.length() - lps; }}" }, { "code": null, "e": 2045, "s": 2042, "text": "+1" }, { "code": null, "e": 2071, "s": 2045, "text": "ayushkumar54511 month ago" }, { "code": null, "e": 2108, "s": 2071, "text": "→All credit goes to Aditya Verma :-)" }, { "code": null, "e": 2809, "s": 2108, "text": "int dp[1001][1001]; int plaindrome(string &a,string &b,int n,int m){ for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } } return dp[n][m]; } int countMin(string str){ string b=str; int n=str.size(); int m=b.size(); reverse(str.begin(),str.end()); int res=plaindrome(str,b,n,m); if(str==b){ return 0; } else{ return (n-res); }" }, { "code": null, "e": 2812, "s": 2809, "text": "+1" }, { "code": null, "e": 2829, "s": 2812, "text": "amonk1 month ago" }, { "code": null, "e": 2842, "s": 2829, "text": "my approach→" }, { "code": null, "e": 2901, "s": 2844, "text": "first calculate the lcs of the string with it's reverse." }, { "code": null, "e": 3011, "s": 2901, "text": "Than check if the lcs is 0 it means every we need to insert len(string)-1 characters to make it a palindrome." }, { "code": null, "e": 3112, "s": 3013, "text": "If the lcs is same as the length of the string than it is already a palindrome so simply return 0;" }, { "code": null, "e": 3167, "s": 3114, "text": "else return len(string)-lcs(string,reverse(string));" }, { "code": null, "e": 3171, "s": 3169, "text": "0" }, { "code": null, "e": 3193, "s": 3171, "text": "geminicode1 month ago" }, { "code": null, "e": 3217, "s": 3193, "text": "my approach in python.." }, { "code": null, "e": 3903, "s": 3217, "text": "def countMin(self, s):\n # code here\n \n dp = [[0 for i in range(len(s))] for j in range(len(s))]\n for g in range(len(s)):\n for i,j in zip(range(0,len(s)-g),range(g,len(s))):\n if g == 0:\n dp[i][j] = 0\n elif g == 1:\n if s[i] == s[j]:\n dp[i][j] = 0\n else:\n dp[i][j] =1\n else:\n if s[i] == s[j]:\n dp[i][j] = dp[i+1][j-1]\n else:\n dp[i][j] = 1 + min(dp[i+1][j],dp[i][j-1])\n #print(dp)\n return dp[0][len(s)-1]" }, { "code": null, "e": 3905, "s": 3903, "text": "0" }, { "code": null, "e": 3931, "s": 3905, "text": "amansidd178612 months ago" }, { "code": null, "e": 4659, "s": 3931, "text": " string rev(string s){ string ans =\"\"; for(int i=s.size()-1; i>=0; i--) ans+=s[i]; return ans; } int countMin(string A){ //complete the function here string s2 = rev(A); // vector<vector<int>> dp(A.size()+1,vector<int>(A.size()+1,0)); vector<int> prev(A.size()+1,0),curr(A.size()+1,0); for(int i=0;i<=A.size();i++) prev[i]=0; for(int i=1; i<=A.size();i++){ for(int j=1;j<=A.size();j++){ if(A[i-1]==s2[j-1]){ curr[j] = 1 + prev[j-1]; } else{ curr[j] = max(prev[j],curr[j-1]); } } prev = curr; } return A.size()-prev[A.size()]; }};" }, { "code": null, "e": 4661, "s": 4659, "text": "0" }, { "code": null, "e": 4688, "s": 4661, "text": "aryansinha18182 months ago" }, { "code": null, "e": 4742, "s": 4688, "text": "This is my first code submission on my own on GFG...." }, { "code": null, "e": 5625, "s": 4744, "text": "int lcs(string x, string y,int n){ int t[n+1][n+1]; for (int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j++) { if (i == 0 || j == 0) { t[i][j] = 0; } } } for (int i = 1; i < n + 1; i++) { for (int j = 1; j < n + 1; j++) { if (x[i - 1] == y[j - 1]) { t[i][j] = 1 + t[i - 1][j - 1]; } else { t[i][j] = max(t[i][j - 1], t[i - 1][j]); } } } return t[n][n]; } int countMin(string str) { //complete the function here int n = str.length(); string b = str; reverse(b.begin(),b.end()); int LCSLen = lcs(str,b,n); if(str == b){ return 0; } else { return (str.length() - LCSLen); } }" }, { "code": null, "e": 5627, "s": 5625, "text": "0" }, { "code": null, "e": 5653, "s": 5627, "text": "tirtha19025682 months ago" }, { "code": null, "e": 6310, "s": 5653, "text": "class Solution{\n static int countMin(String str)\n {\n int n = str.length();\n StringBuilder sb = new StringBuilder(str);\n String t = sb.reverse().toString();\n return n - lcs(str,t,n,n);\n }\n \n static int lcs(String a ,String b,int m,int n){\n int[][]dp = new int[m+1][n+1];\n \n for(int i=1;i<dp.length;i++){\n for(int j=1;j<dp[0].length;j++){\n if(a.charAt(i-1) == b.charAt(j-1)){\n dp[i][j] = dp[i-1][j-1] + 1;\n }else{\n dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n }\n return dp[m][n];\n }\n \n}" }, { "code": null, "e": 6312, "s": 6310, "text": "0" }, { "code": null, "e": 6335, "s": 6312, "text": "starcode012 months ago" }, { "code": null, "e": 6457, "s": 6335, "text": "// → this problem is same as minimum number of deletion to //form a palindrome same code also my code is in java top-down" }, { "code": null, "e": 7114, "s": 6457, "text": "class Solution{ static int countMin(String str) { StringBuilder sb=new StringBuilder(str); sb.reverse(); int n= str.length(); int m = sb.length(); int dp[][] = new int[n+1][m+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0||j==0) dp[i][j] = 0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(str.charAt(i-1)==sb.charAt(j-1)) dp[i][j] = 1+ dp[i-1][j-1]; else{ dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); } } } return n-dp[m][n]; }}" }, { "code": null, "e": 7116, "s": 7114, "text": "0" }, { "code": null, "e": 7139, "s": 7116, "text": "amitanand22 months ago" }, { "code": null, "e": 7879, "s": 7139, "text": "class Solution{\n public:\nint lcs(string x, string y, int n) {\nint t[n+1][n+1];\n\tfor (int i = 0; i < n + 1; i++) {\n\t\tfor (int j = 0; j < n + 1; j++) {\n\t\t\tif (i == 0 || j == 0) {\n\t\t\t\tt[i][j] = 0;\n\t\t\t}\n\t\t}\n\n\t}\n\t\tfor (int i = 1; i < n + 1; i++) {\n\t\tfor (int j = 1; j < n + 1; j++) {\n\t\t\tif (x[i - 1] == y[j - 1]) {\n\t\t\t\tt[i][j] = 1 + t[i - 1][j - 1];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tt[i][j] = max(t[i][j - 1], t[i - 1][j]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn t[n][n];\n}\n int countMin(string str){\n //complete the function here\n string x , y;\n x = str;\n y = x;\n reverse(y.begin() , y.end());\n\tif (x == y) {\n\t\treturn 0;\n\t}\n\telse {\n\tint length = lcs(x, y, x.length());\n\tint noOfInsertiton = x.length() - length;\n\t\n\treturn noOfInsertiton;\n\t}\n\n \n }\n};\n" }, { "code": null, "e": 8025, "s": 7879, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8061, "s": 8025, "text": " Login to access your submissions. " }, { "code": null, "e": 8071, "s": 8061, "text": "\nProblem\n" }, { "code": null, "e": 8081, "s": 8071, "text": "\nContest\n" }, { "code": null, "e": 8144, "s": 8081, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8292, "s": 8144, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8500, "s": 8292, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8606, "s": 8500, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]