title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python - tensorflow.expand_dims() - GeeksforGeeks
21 Aug, 2021 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. expand_dims() is used to insert an addition dimension in input Tensor. Syntax: tensorflow.expand_dims( input, axis, name) Parameters: input: It is the input Tensor. axis: It defines the index at which dimension should be inserted. If input has D dimensions then axis must have value in range [-(D+1), D]. name(optional): It defines the name for the operation. Returns: It returns a Tensor with expanded dimension. Example 1: Python3 # Importing the libraryimport tensorflow as tf # Initializing the inputx = tf.constant([[2, 3, 6], [4, 8, 15]]) # Printing the inputprint('x:', x) # Calculating resultres = tf.expand_dims(x, 1) # Printing the resultprint('res: ', res) Output: x: tf.Tensor( [[ 2 3 6] [ 4 8 15]], shape=(2, 3), dtype=int32) res: tf.Tensor( [[[ 2 3 6]] [[ 4 8 15]]], shape=(2, 1, 3), dtype=int32) # shape has changed from (2, 3) to (2, 1, 3) Example 2: Python3 # Importing the libraryimport tensorflow as tf # Initializing the inputx = tf.constant([[2, 3, 6], [4, 8, 15]]) # Printing the inputprint('x:', x) # Calculating resultres = tf.expand_dims(x, 0) # Printing the resultprint('res: ', res) Output: x: tf.Tensor( [[ 2 3 6] [ 4 8 15]], shape=(2, 3), dtype=int32) res: tf.Tensor( [[[ 2 3 6] [ 4 8 15]]], shape=(1, 2, 3), dtype=int32) # shape has changed from (2, 3) to (1, 2, 3) ruhelaa48 Python-Tensorflow Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n21 Aug, 2021" }, { "code": null, "e": 25669, "s": 25537, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. " }, { "code": null, "e": 25740, "s": 25669, "text": "expand_dims() is used to insert an addition dimension in input Tensor." }, { "code": null, "e": 25791, "s": 25740, "text": "Syntax: tensorflow.expand_dims( input, axis, name)" }, { "code": null, "e": 25803, "s": 25791, "text": "Parameters:" }, { "code": null, "e": 25834, "s": 25803, "text": "input: It is the input Tensor." }, { "code": null, "e": 25975, "s": 25834, "text": "axis: It defines the index at which dimension should be inserted. If input has D dimensions then axis must have value in range [-(D+1), D]." }, { "code": null, "e": 26030, "s": 25975, "text": "name(optional): It defines the name for the operation." }, { "code": null, "e": 26084, "s": 26030, "text": "Returns: It returns a Tensor with expanded dimension." }, { "code": null, "e": 26095, "s": 26084, "text": "Example 1:" }, { "code": null, "e": 26103, "s": 26095, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the inputx = tf.constant([[2, 3, 6], [4, 8, 15]]) # Printing the inputprint('x:', x) # Calculating resultres = tf.expand_dims(x, 1) # Printing the resultprint('res: ', res)", "e": 26338, "s": 26103, "text": null }, { "code": null, "e": 26346, "s": 26338, "text": "Output:" }, { "code": null, "e": 26537, "s": 26346, "text": "x: tf.Tensor(\n[[ 2 3 6]\n [ 4 8 15]], shape=(2, 3), dtype=int32)\nres: tf.Tensor(\n[[[ 2 3 6]]\n\n [[ 4 8 15]]], shape=(2, 1, 3), dtype=int32)\n\n# shape has changed from (2, 3) to (2, 1, 3)" }, { "code": null, "e": 26548, "s": 26537, "text": "Example 2:" }, { "code": null, "e": 26556, "s": 26548, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the inputx = tf.constant([[2, 3, 6], [4, 8, 15]]) # Printing the inputprint('x:', x) # Calculating resultres = tf.expand_dims(x, 0) # Printing the resultprint('res: ', res)", "e": 26791, "s": 26556, "text": null }, { "code": null, "e": 26799, "s": 26791, "text": "Output:" }, { "code": null, "e": 26990, "s": 26799, "text": "x: tf.Tensor(\n[[ 2 3 6]\n [ 4 8 15]], shape=(2, 3), dtype=int32)\nres: tf.Tensor(\n[[[ 2 3 6]\n [ 4 8 15]]], shape=(1, 2, 3), dtype=int32)\n \n# shape has changed from (2, 3) to (1, 2, 3)" }, { "code": null, "e": 27000, "s": 26990, "text": "ruhelaa48" }, { "code": null, "e": 27018, "s": 27000, "text": "Python-Tensorflow" }, { "code": null, "e": 27029, "s": 27018, "text": "Tensorflow" }, { "code": null, "e": 27036, "s": 27029, "text": "Python" }, { "code": null, "e": 27134, "s": 27036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27166, "s": 27134, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27208, "s": 27166, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27250, "s": 27208, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27306, "s": 27250, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27333, "s": 27306, "text": "Python Classes and Objects" }, { "code": null, "e": 27364, "s": 27333, "text": "Python | os.path.join() method" }, { "code": null, "e": 27403, "s": 27364, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27432, "s": 27403, "text": "Create a directory in Python" }, { "code": null, "e": 27454, "s": 27432, "text": "Defaultdict in Python" } ]
Matplotlib legend in subplot - GeeksforGeeks
28 Nov, 2021 In this article, we will discuss how Matplotlib can be employed to add legends in subplots. We can add the legend after making the plot by using legend() function Syntax: axes[position].legend(loc='best') where, loc is the location and the ‘best’ places the legend at the location Approach: Use subplots() method to create subplots in a bigger plot. Use legend() method to add label to the curves. Then show the plots using show() method. Example 1: In this example, the scatter graph is plot with subplots of sine and cos. Python3 # importing modulesfrom matplotlib import pyplotimport numpy # assign value to x axisx_axis = numpy.arange(1, 20, 0.5) # get the value of log10y_axis_log10 = numpy.log10(x_axis) # get the value of expy_axix_exp = numpy.exp(x_axis) # create subplots using subplot() methodfig, axes = pyplot.subplots(2) # depicting the visualizationaxes[0].plot(x_axis, y_axis_log10, color='green', label="log10")axes[1].plot(x_axis, y_axix_exp, color='blue', label="exp") # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best') # display the plotpyplot.show() Output: Example 2: In this example, the scatter graph is plot with subplots of (y=x^2) and (y=x^3). Python3 # importing modulesfrom matplotlib import pyplotimport numpy # assign value to x axisx_axis = numpy.arange(-2, 2, 0.1) # get the value of siney_axis_sine = numpy.sin(x_axis) # get the value of cosy_axix_cose = numpy.cos(x_axis) # create subplots using subplot() methodfig, axes = pyplot.subplots(2) # depicting the visualization(scatter)axes[0].scatter(x_axis, y_axis_sine, color='green', marker='*', label="sine")axes[1].scatter(x_axis, y_axix_cose, color='blue', marker='*', label="cos") # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best') # display the plotpyplot.show() Output: Example 3: Python3 # importing modulesfrom matplotlib import pyplot # assign value to x axisx_axis = list(range(-10, 10)) # get the value of x*xy_axis1 = [x*x for x in x_axis] # get the value of x*x*xy_axix2 = [x*x*x for x in x_axis] # create subplots using subplot() methodfig, axes = pyplot.subplots(2) # depicting the visualizationaxes[0].scatter(x_axis, y_axis1, color='green', marker='*', label="y=x^2")axes[1].scatter(x_axis, y_axix2, color='red', marker='*', label="y=x^3") # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best') # display the plotpyplot.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25701, "s": 25537, "text": "In this article, we will discuss how Matplotlib can be employed to add legends in subplots. We can add the legend after making the plot by using legend() function" }, { "code": null, "e": 25709, "s": 25701, "text": "Syntax:" }, { "code": null, "e": 25743, "s": 25709, "text": "axes[position].legend(loc='best')" }, { "code": null, "e": 25820, "s": 25743, "text": "where, loc is the location and the ‘best’ places the legend at the location" }, { "code": null, "e": 25830, "s": 25820, "text": "Approach:" }, { "code": null, "e": 25889, "s": 25830, "text": "Use subplots() method to create subplots in a bigger plot." }, { "code": null, "e": 25937, "s": 25889, "text": "Use legend() method to add label to the curves." }, { "code": null, "e": 25978, "s": 25937, "text": "Then show the plots using show() method." }, { "code": null, "e": 25989, "s": 25978, "text": "Example 1:" }, { "code": null, "e": 26064, "s": 25989, "text": "In this example, the scatter graph is plot with subplots of sine and cos." }, { "code": null, "e": 26072, "s": 26064, "text": "Python3" }, { "code": "# importing modulesfrom matplotlib import pyplotimport numpy # assign value to x axisx_axis = numpy.arange(1, 20, 0.5) # get the value of log10y_axis_log10 = numpy.log10(x_axis) # get the value of expy_axix_exp = numpy.exp(x_axis) # create subplots using subplot() methodfig, axes = pyplot.subplots(2) # depicting the visualizationaxes[0].plot(x_axis, y_axis_log10, color='green', label=\"log10\")axes[1].plot(x_axis, y_axix_exp, color='blue', label=\"exp\") # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best') # display the plotpyplot.show()", "e": 26657, "s": 26072, "text": null }, { "code": null, "e": 26665, "s": 26657, "text": "Output:" }, { "code": null, "e": 26676, "s": 26665, "text": "Example 2:" }, { "code": null, "e": 26757, "s": 26676, "text": "In this example, the scatter graph is plot with subplots of (y=x^2) and (y=x^3)." }, { "code": null, "e": 26765, "s": 26757, "text": "Python3" }, { "code": "# importing modulesfrom matplotlib import pyplotimport numpy # assign value to x axisx_axis = numpy.arange(-2, 2, 0.1) # get the value of siney_axis_sine = numpy.sin(x_axis) # get the value of cosy_axix_cose = numpy.cos(x_axis) # create subplots using subplot() methodfig, axes = pyplot.subplots(2) # depicting the visualization(scatter)axes[0].scatter(x_axis, y_axis_sine, color='green', marker='*', label=\"sine\")axes[1].scatter(x_axis, y_axix_cose, color='blue', marker='*', label=\"cos\") # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best') # display the plotpyplot.show()", "e": 27385, "s": 26765, "text": null }, { "code": null, "e": 27394, "s": 27385, "text": "Output: " }, { "code": null, "e": 27405, "s": 27394, "text": "Example 3:" }, { "code": null, "e": 27413, "s": 27405, "text": "Python3" }, { "code": "# importing modulesfrom matplotlib import pyplot # assign value to x axisx_axis = list(range(-10, 10)) # get the value of x*xy_axis1 = [x*x for x in x_axis] # get the value of x*x*xy_axix2 = [x*x*x for x in x_axis] # create subplots using subplot() methodfig, axes = pyplot.subplots(2) # depicting the visualizationaxes[0].scatter(x_axis, y_axis1, color='green', marker='*', label=\"y=x^2\")axes[1].scatter(x_axis, y_axix2, color='red', marker='*', label=\"y=x^3\") # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best') # display the plotpyplot.show()", "e": 28005, "s": 27413, "text": null }, { "code": null, "e": 28013, "s": 28005, "text": "Output:" }, { "code": null, "e": 28020, "s": 28013, "text": "Picked" }, { "code": null, "e": 28038, "s": 28020, "text": "Python-matplotlib" }, { "code": null, "e": 28045, "s": 28038, "text": "Python" }, { "code": null, "e": 28143, "s": 28045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28175, "s": 28143, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28217, "s": 28175, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28259, "s": 28217, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28315, "s": 28259, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28342, "s": 28315, "text": "Python Classes and Objects" }, { "code": null, "e": 28381, "s": 28342, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28412, "s": 28381, "text": "Python | os.path.join() method" }, { "code": null, "e": 28434, "s": 28412, "text": "Defaultdict in Python" }, { "code": null, "e": 28463, "s": 28434, "text": "Create a directory in Python" } ]
Lodash _.matches() Method - GeeksforGeeks
14 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 _.matches method creates a function that performs a partial deep comparison between a given object and source, returning true if the given object has equivalent property values, else false. Syntax: _.matches(source) Parameters: This method accepts one parameter as mentioned above and described below: source: The object of property values to match. Returns: [Function] It Returns the new spec function. Example 1: // Requiring the lodash library const _ = require("lodash"); // Using _.matches() methodvar geek = [ {'java' : 3, 'python' : 5, 'js' : 7},{'java' : 4, 'python' : 2, 'js' : 6}]; let gfg = _.filter(geek, _.matches({'java' : 3, 'js' : 7 })); // Storing the Resultconsole.log(gfg) Note: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. Output: [Object {java: 3, js: 7, python: 5}] Example 2: // Requiring the lodash library const _ = require("lodash"); // Using _.matches() methodvar objects = [ { 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }, { 'a': 8, 'b': 7, 'c': 9 }]; gfg= _.filter(objects, _.matches({ 'a': 8}));// => [{ 'a': 4, 'b': 5, 'c': 6 }] // Storing the Resultconsole.log(gfg) Note: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. Output: [Object {a: 8, b: 7, c: 9}] JavaScript-Lodash JavaScript 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 Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? Hide or show elements in HTML using display property How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 38679, "s": 38651, "text": "\n14 Sep, 2020" }, { "code": null, "e": 39013, "s": 38679, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.matches method creates a function that performs a partial deep comparison between a given object and source, returning true if the given object has equivalent property values, else false." }, { "code": null, "e": 39021, "s": 39013, "text": "Syntax:" }, { "code": null, "e": 39039, "s": 39021, "text": "_.matches(source)" }, { "code": null, "e": 39125, "s": 39039, "text": "Parameters: This method accepts one parameter as mentioned above and described below:" }, { "code": null, "e": 39173, "s": 39125, "text": "source: The object of property values to match." }, { "code": null, "e": 39228, "s": 39173, "text": "Returns: [Function] It Returns the new spec function." }, { "code": null, "e": 39239, "s": 39228, "text": "Example 1:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Using _.matches() methodvar geek = [ {'java' : 3, 'python' : 5, 'js' : 7},{'java' : 4, 'python' : 2, 'js' : 6}]; let gfg = _.filter(geek, _.matches({'java' : 3, 'js' : 7 })); // Storing the Resultconsole.log(gfg)", "e": 39524, "s": 39239, "text": null }, { "code": null, "e": 39614, "s": 39524, "text": "Note: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": null, "e": 39622, "s": 39614, "text": "Output:" }, { "code": null, "e": 39659, "s": 39622, "text": "[Object {java: 3, js: 7, python: 5}]" }, { "code": null, "e": 39670, "s": 39659, "text": "Example 2:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Using _.matches() methodvar objects = [ { 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }, { 'a': 8, 'b': 7, 'c': 9 }]; gfg= _.filter(objects, _.matches({ 'a': 8}));// => [{ 'a': 4, 'b': 5, 'c': 6 }] // Storing the Resultconsole.log(gfg)", "e": 39990, "s": 39670, "text": null }, { "code": null, "e": 40080, "s": 39990, "text": "Note: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": null, "e": 40088, "s": 40080, "text": "Output:" }, { "code": null, "e": 40116, "s": 40088, "text": "[Object {a: 8, b: 7, c: 9}]" }, { "code": null, "e": 40134, "s": 40116, "text": "JavaScript-Lodash" }, { "code": null, "e": 40145, "s": 40134, "text": "JavaScript" }, { "code": null, "e": 40243, "s": 40145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40283, "s": 40243, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40328, "s": 40283, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40389, "s": 40328, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40461, "s": 40389, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40530, "s": 40461, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40557, "s": 40530, "text": "File uploading in React.js" }, { "code": null, "e": 40609, "s": 40557, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 40662, "s": 40609, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 40708, "s": 40662, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Error handling during file operations in C/C++ - GeeksforGeeks
10 Jan, 2022 It is quite common that errors may occur while reading data from a file in C++ or writing data to a file. For example, an error may arise due to the following: When trying to read a file beyond indicator. When trying to read a file that does not exist. When trying to use a file that has not been opened. When trying to use a file in an inappropriate mode i.e., writing data to a file that has been opened for reading. When writing to a file that is write-protected i.e., trying to write to a read-only file. Failure to check for errors then the program may behave abnormally therefore an unchecked error may result in premature termination for the program or incorrect output. Below are some Error handling functions during file operations in C/C++: In C/C++, the library function ferror() is used to check for the error in the stream. Its prototype is written as: int ferror (FILE *stream); The ferror() function checks for any error in the stream. It returns a value zero if no error has occurred and a non-zero value if there is an error. The error indication will last until the file is closed unless it is cleared by the clearerr() function. Below is the program to implement the use of ferror(): C C++ // C program to illustrate the// use of ferror()#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ FILE* fp; // If a file is opened which does // not exist, then it will be an // error and corresponding errno // value will be set char feedback[100]; int i; fp = fopen("GeeksForGeeks.TXT", "w"); if (fp == NULL) { printf("\n The file could " "not be opened"); exit(1); } printf("\n Provide feedback on " "this article: "); fgets(feedback, 100, stdin); for (i = 0; i < feedback[i]; i++) fputc(feedback[i], fp); // Error writing file if (ferror(fp)) { printf("\n Error writing in file"); exit(1); } // Close the file pointer fclose(fp);} // C++ program to illustrate the// use of ferror()#include <bits/stdc++.h> // Driver Codeint main(){ FILE* fp; // If a file is opened which does // not exist, then it will be an // error and corresponding errno // value will be set char feedback[100]; int i; fp = fopen("GeeksForGeeks.TXT", "w"); if (fp == NULL) { printf("\n The file could " "not be opened"); exit(1); } printf("\n Provide feedback on " "this article: "); fgets(feedback, 100, stdin); for (i = 0; i < feedback[i]; i++) fputc(feedback[i], fp); // Error writing file if (ferror(fp)) { printf("\n Error writing in file"); exit(1); } // Close the file pointer fclose(fp);} Output: Explanation: After executing this code “Provide feedback on this article:“ will be displayed on the screen and after giving some feedback “Process exited after some seconds with return value 0′′ will be displayed on the screen. The function clearerr() is used to clear the end-of-file and error indicators for the stream. Its prototype can be given as: void clearerr(FILE *stream); The clearerr() clears the error for the stream pointed by the stream. The function is used because error indicators are not automatically cleared. Once the error indicator for a specific stream is set, operations on the stream continue to return an error value until clearerr(), fseek(), fsetpos(), or rewind() is called. Below is the program to implement the use of clearerr(): C C++ // C program to illustrate the// use of clearerr()#include <errno.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ FILE* fp; char feedback[100]; char c; fp = fopen("file.txt", "w"); c = fgetc(fp); if (ferror(fp)) { printf("Error in reading from" " file : file.txt\n"); } clearerr(fp); if (ferror(fp)) { printf("Error in reading from " "file : file.txt\n"); } // close the file fclose(fp);} // C++ program to illustrate the// use of clearerr()#include <bits/stdc++.h> // Driver Codeint main(){ FILE* fp; char feedback[100]; char c; fp = fopen("file.txt", "w"); c = fgetc(fp); if (ferror(fp)) { printf("Error in reading from" " file : file.txt\n"); } clearerr(fp); if (ferror(fp)) { printf("Error in reading from " "file : file.txt\n"); } // close the file fclose(fp);} Output: The function perror() stands for print error. In case of an error, the programmer can determine the type of error that has occurred using the perror() function. When perror() is called, then it displays a message describing the most recent error that occurred during a library function call or system call. Its prototype can be given as: void perror (char*msg); The perror() takes one argument which points to an optional user-defined message the message is printed first followed by a colon and the implementation-defined message that describes the most recent error. If a call to perror() is made when no error has actually occurred then ‘No error’ will be displayed. The most important thing to remember is that a call to perror() and nothing is done to deal with the error condition, then it is entirely up to the program to take action. For example, the program may prompt the user to do something such as terminate the program. Usually, the program’s activities will be determined by checking the value of errno and the nature of the error. In order to use the external constant errno, you must include the header file ERRNO.H Below is the program given below illustrates the use of perror(). Here, assume that the file “file.txt” does not exist. C C++ // C program to illustrate the// use of perror()#include <errno.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ FILE* fp; // First rename if there is any file rename("file.txt", "newfile.txt"); // Now try to open same file fp = fopen("file.txt", "r"); if (fp == NULL) { perror("Error: "); return (-1); } // Close the file pointer fclose(fp); return (0);} // C++ program to illustrate the// use of perror()#include <bits/stdc++.h>#include <errno.h> // Driver Codeint main(){ FILE* fp; // First rename if there is any file rename("file.txt", "newfile.txt"); // Now try to open same file fp = fopen("file.txt", "r"); if (fp == NULL) { perror("Error: "); return (-1); } // Close the file pointer fclose(fp); return (0);} Output: shapnesht C-File Handling cpp-file-handling File Handling C Language C Programs C++ C++ Programs File Handling CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25478, "s": 25450, "text": "\n10 Jan, 2022" }, { "code": null, "e": 25638, "s": 25478, "text": "It is quite common that errors may occur while reading data from a file in C++ or writing data to a file. For example, an error may arise due to the following:" }, { "code": null, "e": 25683, "s": 25638, "text": "When trying to read a file beyond indicator." }, { "code": null, "e": 25731, "s": 25683, "text": "When trying to read a file that does not exist." }, { "code": null, "e": 25783, "s": 25731, "text": "When trying to use a file that has not been opened." }, { "code": null, "e": 25897, "s": 25783, "text": "When trying to use a file in an inappropriate mode i.e., writing data to a file that has been opened for reading." }, { "code": null, "e": 25987, "s": 25897, "text": "When writing to a file that is write-protected i.e., trying to write to a read-only file." }, { "code": null, "e": 26156, "s": 25987, "text": "Failure to check for errors then the program may behave abnormally therefore an unchecked error may result in premature termination for the program or incorrect output." }, { "code": null, "e": 26229, "s": 26156, "text": "Below are some Error handling functions during file operations in C/C++:" }, { "code": null, "e": 26344, "s": 26229, "text": "In C/C++, the library function ferror() is used to check for the error in the stream. Its prototype is written as:" }, { "code": null, "e": 26372, "s": 26344, "text": " int ferror (FILE *stream);" }, { "code": null, "e": 26628, "s": 26372, "text": "The ferror() function checks for any error in the stream. It returns a value zero if no error has occurred and a non-zero value if there is an error. The error indication will last until the file is closed unless it is cleared by the clearerr() function. " }, { "code": null, "e": 26683, "s": 26628, "text": "Below is the program to implement the use of ferror():" }, { "code": null, "e": 26685, "s": 26683, "text": "C" }, { "code": null, "e": 26689, "s": 26685, "text": "C++" }, { "code": "// C program to illustrate the// use of ferror()#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ FILE* fp; // If a file is opened which does // not exist, then it will be an // error and corresponding errno // value will be set char feedback[100]; int i; fp = fopen(\"GeeksForGeeks.TXT\", \"w\"); if (fp == NULL) { printf(\"\\n The file could \" \"not be opened\"); exit(1); } printf(\"\\n Provide feedback on \" \"this article: \"); fgets(feedback, 100, stdin); for (i = 0; i < feedback[i]; i++) fputc(feedback[i], fp); // Error writing file if (ferror(fp)) { printf(\"\\n Error writing in file\"); exit(1); } // Close the file pointer fclose(fp);}", "e": 27465, "s": 26689, "text": null }, { "code": "// C++ program to illustrate the// use of ferror()#include <bits/stdc++.h> // Driver Codeint main(){ FILE* fp; // If a file is opened which does // not exist, then it will be an // error and corresponding errno // value will be set char feedback[100]; int i; fp = fopen(\"GeeksForGeeks.TXT\", \"w\"); if (fp == NULL) { printf(\"\\n The file could \" \"not be opened\"); exit(1); } printf(\"\\n Provide feedback on \" \"this article: \"); fgets(feedback, 100, stdin); for (i = 0; i < feedback[i]; i++) fputc(feedback[i], fp); // Error writing file if (ferror(fp)) { printf(\"\\n Error writing in file\"); exit(1); } // Close the file pointer fclose(fp);}", "e": 28230, "s": 27465, "text": null }, { "code": null, "e": 28238, "s": 28230, "text": "Output:" }, { "code": null, "e": 28466, "s": 28238, "text": "Explanation: After executing this code “Provide feedback on this article:“ will be displayed on the screen and after giving some feedback “Process exited after some seconds with return value 0′′ will be displayed on the screen." }, { "code": null, "e": 28591, "s": 28466, "text": "The function clearerr() is used to clear the end-of-file and error indicators for the stream. Its prototype can be given as:" }, { "code": null, "e": 28620, "s": 28591, "text": "void clearerr(FILE *stream);" }, { "code": null, "e": 28942, "s": 28620, "text": "The clearerr() clears the error for the stream pointed by the stream. The function is used because error indicators are not automatically cleared. Once the error indicator for a specific stream is set, operations on the stream continue to return an error value until clearerr(), fseek(), fsetpos(), or rewind() is called." }, { "code": null, "e": 28999, "s": 28942, "text": "Below is the program to implement the use of clearerr():" }, { "code": null, "e": 29001, "s": 28999, "text": "C" }, { "code": null, "e": 29005, "s": 29001, "text": "C++" }, { "code": "// C program to illustrate the// use of clearerr()#include <errno.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ FILE* fp; char feedback[100]; char c; fp = fopen(\"file.txt\", \"w\"); c = fgetc(fp); if (ferror(fp)) { printf(\"Error in reading from\" \" file : file.txt\\n\"); } clearerr(fp); if (ferror(fp)) { printf(\"Error in reading from \" \"file : file.txt\\n\"); } // close the file fclose(fp);}", "e": 29501, "s": 29005, "text": null }, { "code": "// C++ program to illustrate the// use of clearerr()#include <bits/stdc++.h> // Driver Codeint main(){ FILE* fp; char feedback[100]; char c; fp = fopen(\"file.txt\", \"w\"); c = fgetc(fp); if (ferror(fp)) { printf(\"Error in reading from\" \" file : file.txt\\n\"); } clearerr(fp); if (ferror(fp)) { printf(\"Error in reading from \" \"file : file.txt\\n\"); } // close the file fclose(fp);}", "e": 29968, "s": 29501, "text": null }, { "code": null, "e": 29976, "s": 29968, "text": "Output:" }, { "code": null, "e": 30314, "s": 29976, "text": "The function perror() stands for print error. In case of an error, the programmer can determine the type of error that has occurred using the perror() function. When perror() is called, then it displays a message describing the most recent error that occurred during a library function call or system call. Its prototype can be given as:" }, { "code": null, "e": 30338, "s": 30314, "text": "void perror (char*msg);" }, { "code": null, "e": 30545, "s": 30338, "text": "The perror() takes one argument which points to an optional user-defined message the message is printed first followed by a colon and the implementation-defined message that describes the most recent error." }, { "code": null, "e": 30646, "s": 30545, "text": "If a call to perror() is made when no error has actually occurred then ‘No error’ will be displayed." }, { "code": null, "e": 30910, "s": 30646, "text": "The most important thing to remember is that a call to perror() and nothing is done to deal with the error condition, then it is entirely up to the program to take action. For example, the program may prompt the user to do something such as terminate the program." }, { "code": null, "e": 31023, "s": 30910, "text": "Usually, the program’s activities will be determined by checking the value of errno and the nature of the error." }, { "code": null, "e": 31109, "s": 31023, "text": "In order to use the external constant errno, you must include the header file ERRNO.H" }, { "code": null, "e": 31229, "s": 31109, "text": "Below is the program given below illustrates the use of perror(). Here, assume that the file “file.txt” does not exist." }, { "code": null, "e": 31231, "s": 31229, "text": "C" }, { "code": null, "e": 31235, "s": 31231, "text": "C++" }, { "code": "// C program to illustrate the// use of perror()#include <errno.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ FILE* fp; // First rename if there is any file rename(\"file.txt\", \"newfile.txt\"); // Now try to open same file fp = fopen(\"file.txt\", \"r\"); if (fp == NULL) { perror(\"Error: \"); return (-1); } // Close the file pointer fclose(fp); return (0);}", "e": 31665, "s": 31235, "text": null }, { "code": "// C++ program to illustrate the// use of perror()#include <bits/stdc++.h>#include <errno.h> // Driver Codeint main(){ FILE* fp; // First rename if there is any file rename(\"file.txt\", \"newfile.txt\"); // Now try to open same file fp = fopen(\"file.txt\", \"r\"); if (fp == NULL) { perror(\"Error: \"); return (-1); } // Close the file pointer fclose(fp); return (0);}", "e": 32084, "s": 31665, "text": null }, { "code": null, "e": 32092, "s": 32084, "text": "Output:" }, { "code": null, "e": 32102, "s": 32092, "text": "shapnesht" }, { "code": null, "e": 32118, "s": 32102, "text": "C-File Handling" }, { "code": null, "e": 32136, "s": 32118, "text": "cpp-file-handling" }, { "code": null, "e": 32150, "s": 32136, "text": "File Handling" }, { "code": null, "e": 32161, "s": 32150, "text": "C Language" }, { "code": null, "e": 32172, "s": 32161, "text": "C Programs" }, { "code": null, "e": 32176, "s": 32172, "text": "C++" }, { "code": null, "e": 32189, "s": 32176, "text": "C++ Programs" }, { "code": null, "e": 32203, "s": 32189, "text": "File Handling" }, { "code": null, "e": 32207, "s": 32203, "text": "CPP" }, { "code": null, "e": 32305, "s": 32207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32343, "s": 32305, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 32369, "s": 32343, "text": "Exception Handling in C++" }, { "code": null, "e": 32389, "s": 32369, "text": "Multithreading in C" }, { "code": null, "e": 32411, "s": 32389, "text": "'this' pointer in C++" }, { "code": null, "e": 32452, "s": 32411, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32465, "s": 32452, "text": "Strings in C" }, { "code": null, "e": 32506, "s": 32465, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32547, "s": 32506, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 32582, "s": 32547, "text": "Header files in C/C++ and its uses" } ]
Scala String matches() method with example - GeeksforGeeks
03 Oct, 2019 The matches() method is used to check if the string stated matches the specified regular expression in the argument or not. Method Definition: Boolean matches(String regex)Return Type: It returns true if the string matches the regular expression else it returns false. Example #1: // Scala program of int matches()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying matches method val result = "Preeti".matches(".*i") // Displays output println(result) }} true So, here the regular expression matches the string stated. So, it returns true.Example #2: // Scala program of int matches()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying matches method val result = "Preeti".matches(".i.*") // Displays output println(result) }} false Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala Constructors Scala String substring() method with example Scala | Arrays How to get the first element of List in Scala Scala String replace() method with example
[ { "code": null, "e": 25285, "s": 25257, "text": "\n03 Oct, 2019" }, { "code": null, "e": 25409, "s": 25285, "text": "The matches() method is used to check if the string stated matches the specified regular expression in the argument or not." }, { "code": null, "e": 25554, "s": 25409, "text": "Method Definition: Boolean matches(String regex)Return Type: It returns true if the string matches the regular expression else it returns false." }, { "code": null, "e": 25566, "s": 25554, "text": "Example #1:" }, { "code": "// Scala program of int matches()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying matches method val result = \"Preeti\".matches(\".*i\") // Displays output println(result) }} ", "e": 25858, "s": 25566, "text": null }, { "code": null, "e": 25864, "s": 25858, "text": "true\n" }, { "code": null, "e": 25955, "s": 25864, "text": "So, here the regular expression matches the string stated. So, it returns true.Example #2:" }, { "code": "// Scala program of int matches()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying matches method val result = \"Preeti\".matches(\".i.*\") // Displays output println(result) }} ", "e": 26244, "s": 25955, "text": null }, { "code": null, "e": 26251, "s": 26244, "text": "false\n" }, { "code": null, "e": 26257, "s": 26251, "text": "Scala" }, { "code": null, "e": 26270, "s": 26257, "text": "Scala-Method" }, { "code": null, "e": 26284, "s": 26270, "text": "Scala-Strings" }, { "code": null, "e": 26290, "s": 26284, "text": "Scala" }, { "code": null, "e": 26388, "s": 26290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26410, "s": 26388, "text": "Type Casting in Scala" }, { "code": null, "e": 26436, "s": 26410, "text": "Class and Object in Scala" }, { "code": null, "e": 26448, "s": 26436, "text": "Scala Lists" }, { "code": null, "e": 26501, "s": 26448, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 26520, "s": 26501, "text": "Operators in Scala" }, { "code": null, "e": 26539, "s": 26520, "text": "Scala Constructors" }, { "code": null, "e": 26584, "s": 26539, "text": "Scala String substring() method with example" }, { "code": null, "e": 26599, "s": 26584, "text": "Scala | Arrays" }, { "code": null, "e": 26645, "s": 26599, "text": "How to get the first element of List in Scala" } ]
Autocomplete input suggestion using Python and Flask - GeeksforGeeks
09 Apr, 2021 In this article, we will learn how to give features like auto-completion to the data that is passed from Flask. Autocomplete basically means predicting the rest of the word when the user types something. This way human interaction also increases with every correct prediction. Let’s see how to do the same. We will be using jquery for autocompletion. To install flask type the below command in the terminal. pip install flask First, create a new directory for the project. Inside that create a new file and name it app.py. app.py Python3 from flask import Flask, request, render_template app = Flask(__name__) @app.route("/", methods=["POST", "GET"])def home(): if request.method == "GET": languages = ["C++", "Python", "PHP", "Java", "C", "Ruby", "R", "C#", "Dart", "Fortran", "Pascal", "Javascript"] return render_template("index.html", languages=languages) if __name__ == '__main__': app.run(debug=True) Then, create a new directory inside the project to hold all the HTML files and name them templates. In this file, we have an input field where the user will type a string and the jquery function will provide the suggestions. index.html HTML <!DOCTYPE html><html><head> <title>AutoComplete</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"> </script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" /> </head><body> <h1>Welcome to GFG</h1> <input type="text" id="tags"> <script> $( function() { var availableTags = [ {% for language in languages %} "{{language}}", {% endfor %} ]; $( "#tags" ).autocomplete({ source: availableTags }); } ); </script> </body></html> To run this app open cmd or terminal and run the below command. python app.py Output: Python Flask 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25863, "s": 25835, "text": "\n09 Apr, 2021" }, { "code": null, "e": 26170, "s": 25863, "text": "In this article, we will learn how to give features like auto-completion to the data that is passed from Flask. Autocomplete basically means predicting the rest of the word when the user types something. This way human interaction also increases with every correct prediction. Let’s see how to do the same." }, { "code": null, "e": 26214, "s": 26170, "text": "We will be using jquery for autocompletion." }, { "code": null, "e": 26271, "s": 26214, "text": "To install flask type the below command in the terminal." }, { "code": null, "e": 26289, "s": 26271, "text": "pip install flask" }, { "code": null, "e": 26386, "s": 26289, "text": "First, create a new directory for the project. Inside that create a new file and name it app.py." }, { "code": null, "e": 26393, "s": 26386, "text": "app.py" }, { "code": null, "e": 26401, "s": 26393, "text": "Python3" }, { "code": "from flask import Flask, request, render_template app = Flask(__name__) @app.route(\"/\", methods=[\"POST\", \"GET\"])def home(): if request.method == \"GET\": languages = [\"C++\", \"Python\", \"PHP\", \"Java\", \"C\", \"Ruby\", \"R\", \"C#\", \"Dart\", \"Fortran\", \"Pascal\", \"Javascript\"] return render_template(\"index.html\", languages=languages) if __name__ == '__main__': app.run(debug=True)", "e": 26829, "s": 26401, "text": null }, { "code": null, "e": 27054, "s": 26829, "text": "Then, create a new directory inside the project to hold all the HTML files and name them templates. In this file, we have an input field where the user will type a string and the jquery function will provide the suggestions." }, { "code": null, "e": 27065, "s": 27054, "text": "index.html" }, { "code": null, "e": 27070, "s": 27065, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>AutoComplete</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js\"> </script> <link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\" /> </head><body> <h1>Welcome to GFG</h1> <input type=\"text\" id=\"tags\"> <script> $( function() { var availableTags = [ {% for language in languages %} \"{{language}}\", {% endfor %} ]; $( \"#tags\" ).autocomplete({ source: availableTags }); } ); </script> </body></html>", "e": 27806, "s": 27070, "text": null }, { "code": null, "e": 27870, "s": 27806, "text": "To run this app open cmd or terminal and run the below command." }, { "code": null, "e": 27884, "s": 27870, "text": "python app.py" }, { "code": null, "e": 27892, "s": 27884, "text": "Output:" }, { "code": null, "e": 27905, "s": 27892, "text": "Python Flask" }, { "code": null, "e": 27912, "s": 27905, "text": "Python" }, { "code": null, "e": 28010, "s": 27912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28028, "s": 28010, "text": "Python Dictionary" }, { "code": null, "e": 28063, "s": 28028, "text": "Read a file line by line in Python" }, { "code": null, "e": 28095, "s": 28063, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28117, "s": 28095, "text": "Enumerate() in Python" }, { "code": null, "e": 28159, "s": 28117, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28189, "s": 28159, "text": "Iterate over a list in Python" }, { "code": null, "e": 28215, "s": 28189, "text": "Python String | replace()" }, { "code": null, "e": 28244, "s": 28215, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28288, "s": 28244, "text": "Reading and Writing to text files in Python" } ]
Double Layered Text Effect using CSS - GeeksforGeeks
18 Jun, 2020 The double-layered text effect feature is very new in the world of text-animation targeting animated websites and its users as the audience. The feature basically has two layers for every word and the upper layer can be manipulated by various events such as hover events. The rotation of the upper layer is performed at some certain angle to make a hinge kind of effect. It will look like the upper layer is hinged to the lower layer from a single point. Approach: The approach is to first create two layers using the before selector and then use hover selector to rotate it on mouse hover. HTML Code: In this section, we have wrapped each alphabet in a span with a data-title attribute having the same value as of the alphabet. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Double Layered Text</title><body> <div class="geeks"> <span data-title="G">G</span> <span data-title="E">E</span> <span data-title="E">E</span> <span data-title="K">K</span> <span data-title="S">S</span> <span data-title="F">F</span> <span data-title="O">O</span> <span data-title="R">R</span> <span data-title="G">G</span> <span data-title="E">E</span> <span data-title="E">E</span> <span data-title="K">K</span> <span data-title="S">S</span> </div></body> </html> CSS Code: Step 1: Perform some basic styling like a background, font-family, font-size and adjusting text to center. Step 2: Now use before selector with the content set as the data-title used in the span tag. This will create the second layer of the text. Make sure to provide a different color from the color given to the first layer. Step 3: Now use some transitions to give smooth animation. Step 4: At last, use hover selector to change perspective or in simple words rotate the second layer. Note: Choose your degree rotation and values for transitions carefully. You can use the browser console to get the perfect values. <style> body { background: black; } .geeks { text-align: center; margin: 200px auto 0; font-family: Arial, Helvetica, sans-serif; } .geeks span { font-size: 80px; font-weight: 700; color: green; position: relative; text-shadow: -1px 0 0 rgba(0, 0, 0, .2); } .geeks span::before { content: attr(data-title); position: absolute; top: 0; left: 0; transform-origin: left; color: #fff; transition: .5s cubic-bezier(0.175, 0.885, 0.32, 1.275); transform: rotateY(25deg); } .geeks span:hover::before { transform: perspective(1000px) rotate(-67deg); }</style> Complete Code: It is the combination of the above two sections of the code. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Double Layered Text</title> <style> body { background: black; } .geeks { text-align: center; margin: 200px auto 0; font-family: Arial, Helvetica, sans-serif; } .geeks span { font-size: 80px; font-weight: 700; color: green; position: relative; text-shadow: -1px 0 0 rgba(0, 0, 0, .2); } .geeks span::before { content: attr(data-title); position: absolute; top: 0; left: 0; transform-origin: left; color: #fff; transition: .5s cubic-bezier( 0.175, 0.885, 0.32, 1.275); transform: rotateY(25deg); } .geeks span:hover::before { transform: perspective(1000px) rotate(-67deg); } </style></head> <body> <div class="geeks"> <span data-title="G">G</span> <span data-title="E">E</span> <span data-title="E">E</span> <span data-title="K">K</span> <span data-title="S">S</span> <span data-title="F">F</span> <span data-title="O">O</span> <span data-title="R">R</span> <span data-title="G">G</span> <span data-title="E">E</span> <span data-title="E">E</span> <span data-title="K">K</span> <span data-title="S">S</span> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Design a web page using HTML and CSS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 25981, "s": 25953, "text": "\n18 Jun, 2020" }, { "code": null, "e": 26436, "s": 25981, "text": "The double-layered text effect feature is very new in the world of text-animation targeting animated websites and its users as the audience. The feature basically has two layers for every word and the upper layer can be manipulated by various events such as hover events. The rotation of the upper layer is performed at some certain angle to make a hinge kind of effect. It will look like the upper layer is hinged to the lower layer from a single point." }, { "code": null, "e": 26572, "s": 26436, "text": "Approach: The approach is to first create two layers using the before selector and then use hover selector to rotate it on mouse hover." }, { "code": null, "e": 26710, "s": 26572, "text": "HTML Code: In this section, we have wrapped each alphabet in a span with a data-title attribute having the same value as of the alphabet." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Double Layered Text</title><body> <div class=\"geeks\"> <span data-title=\"G\">G</span> <span data-title=\"E\">E</span> <span data-title=\"E\">E</span> <span data-title=\"K\">K</span> <span data-title=\"S\">S</span> <span data-title=\"F\">F</span> <span data-title=\"O\">O</span> <span data-title=\"R\">R</span> <span data-title=\"G\">G</span> <span data-title=\"E\">E</span> <span data-title=\"E\">E</span> <span data-title=\"K\">K</span> <span data-title=\"S\">S</span> </div></body> </html>", "e": 27410, "s": 26710, "text": null }, { "code": null, "e": 27420, "s": 27410, "text": "CSS Code:" }, { "code": null, "e": 27527, "s": 27420, "text": "Step 1: Perform some basic styling like a background, font-family, font-size and adjusting text to center." }, { "code": null, "e": 27747, "s": 27527, "text": "Step 2: Now use before selector with the content set as the data-title used in the span tag. This will create the second layer of the text. Make sure to provide a different color from the color given to the first layer." }, { "code": null, "e": 27806, "s": 27747, "text": "Step 3: Now use some transitions to give smooth animation." }, { "code": null, "e": 27908, "s": 27806, "text": "Step 4: At last, use hover selector to change perspective or in simple words rotate the second layer." }, { "code": null, "e": 28039, "s": 27908, "text": "Note: Choose your degree rotation and values for transitions carefully. You can use the browser console to get the perfect values." }, { "code": "<style> body { background: black; } .geeks { text-align: center; margin: 200px auto 0; font-family: Arial, Helvetica, sans-serif; } .geeks span { font-size: 80px; font-weight: 700; color: green; position: relative; text-shadow: -1px 0 0 rgba(0, 0, 0, .2); } .geeks span::before { content: attr(data-title); position: absolute; top: 0; left: 0; transform-origin: left; color: #fff; transition: .5s cubic-bezier(0.175, 0.885, 0.32, 1.275); transform: rotateY(25deg); } .geeks span:hover::before { transform: perspective(1000px) rotate(-67deg); }</style>", "e": 28757, "s": 28039, "text": null }, { "code": null, "e": 28833, "s": 28757, "text": "Complete Code: It is the combination of the above two sections of the code." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Double Layered Text</title> <style> body { background: black; } .geeks { text-align: center; margin: 200px auto 0; font-family: Arial, Helvetica, sans-serif; } .geeks span { font-size: 80px; font-weight: 700; color: green; position: relative; text-shadow: -1px 0 0 rgba(0, 0, 0, .2); } .geeks span::before { content: attr(data-title); position: absolute; top: 0; left: 0; transform-origin: left; color: #fff; transition: .5s cubic-bezier( 0.175, 0.885, 0.32, 1.275); transform: rotateY(25deg); } .geeks span:hover::before { transform: perspective(1000px) rotate(-67deg); } </style></head> <body> <div class=\"geeks\"> <span data-title=\"G\">G</span> <span data-title=\"E\">E</span> <span data-title=\"E\">E</span> <span data-title=\"K\">K</span> <span data-title=\"S\">S</span> <span data-title=\"F\">F</span> <span data-title=\"O\">O</span> <span data-title=\"R\">R</span> <span data-title=\"G\">G</span> <span data-title=\"E\">E</span> <span data-title=\"E\">E</span> <span data-title=\"K\">K</span> <span data-title=\"S\">S</span> </div></body> </html>", "e": 30423, "s": 28833, "text": null }, { "code": null, "e": 30431, "s": 30423, "text": "Output:" }, { "code": null, "e": 30568, "s": 30431, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 30577, "s": 30568, "text": "CSS-Misc" }, { "code": null, "e": 30587, "s": 30577, "text": "HTML-Misc" }, { "code": null, "e": 30591, "s": 30587, "text": "CSS" }, { "code": null, "e": 30596, "s": 30591, "text": "HTML" }, { "code": null, "e": 30613, "s": 30596, "text": "Web Technologies" }, { "code": null, "e": 30640, "s": 30613, "text": "Web technologies Questions" }, { "code": null, "e": 30645, "s": 30640, "text": "HTML" }, { "code": null, "e": 30743, "s": 30645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30798, "s": 30743, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30862, "s": 30798, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 30901, "s": 30862, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30962, "s": 30901, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 30999, "s": 30962, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31059, "s": 30999, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31112, "s": 31059, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31173, "s": 31112, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31197, "s": 31173, "text": "REST API (Introduction)" } ]
Python | Sort list according to other list order - GeeksforGeeks
11 Jun, 2021 Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let’s discuss certain ways to sort list according to other list order.Method #1 : Using List comprehension List comprehension can be used to achieve this particular task. In this, we just check for each element in list 2 matches with the current tuple, and append accordingly, in a sorted manner. Python3 # Python3 code to demonstrate# to sort according to other list# using list comprehension # initializing list of tuplestest_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)] # initializing sort ordersort_order = ['d', 'c', 'a', 'b'] # printing original listprint ("The original list is : " + str(test_list)) # printing sort order listprint ("The sort order list is : " + str(sort_order)) # using list comprehension# to sort according to other listres = [tuple for x in sort_order for tuple in test_list if tuple[0] == x] # printing resultprint ("The sorted list is : " + str(res)) The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)] The sort order list is : ['d', 'c', 'a', 'b'] The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)] Method #2 : Using sort() + lambda + index() The shorthand to perform this particular operation, sort function can be used along with lambda with key to specify the function execution for each pair of tuple, and list order of other list is maintained using index function. Python3 # Python code to demonstrate# to sort according to other list# using sort() + lambda + index() # initializing list of tuplestest_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)] # initializing sort ordersort_order = ['d', 'c', 'a', 'b'] # printing original listprint ("The original list is : " + str(test_list)) # printing sort order listprint ("The sort order list is : " + str(sort_order)) # using sort() + lambda + index()# to sort according to other list# test_list.sort(key = lambda(i, j): sort_order.index(i)) # works in python 2test_list.sort(key = lambda i: sort_order.index(i[0])) # works in python 3 # printing resultprint ("The sorted list is : " + str(test_list)) The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)] The sort order list is : ['d', 'c', 'a', 'b'] The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)] Kiran Kotari varshagumber28 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26141, "s": 26113, "text": "\n11 Jun, 2021" }, { "code": null, "e": 26695, "s": 26141, "text": "Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let’s discuss certain ways to sort list according to other list order.Method #1 : Using List comprehension List comprehension can be used to achieve this particular task. In this, we just check for each element in list 2 matches with the current tuple, and append accordingly, in a sorted manner. " }, { "code": null, "e": 26703, "s": 26695, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to sort according to other list# using list comprehension # initializing list of tuplestest_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)] # initializing sort ordersort_order = ['d', 'c', 'a', 'b'] # printing original listprint (\"The original list is : \" + str(test_list)) # printing sort order listprint (\"The sort order list is : \" + str(sort_order)) # using list comprehension# to sort according to other listres = [tuple for x in sort_order for tuple in test_list if tuple[0] == x] # printing resultprint (\"The sorted list is : \" + str(res))", "e": 27282, "s": 26703, "text": null }, { "code": null, "e": 27454, "s": 27282, "text": "The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\nThe sort order list is : ['d', 'c', 'a', 'b']\nThe sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]" }, { "code": null, "e": 27732, "s": 27456, "text": " Method #2 : Using sort() + lambda + index() The shorthand to perform this particular operation, sort function can be used along with lambda with key to specify the function execution for each pair of tuple, and list order of other list is maintained using index function. " }, { "code": null, "e": 27740, "s": 27732, "text": "Python3" }, { "code": "# Python code to demonstrate# to sort according to other list# using sort() + lambda + index() # initializing list of tuplestest_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)] # initializing sort ordersort_order = ['d', 'c', 'a', 'b'] # printing original listprint (\"The original list is : \" + str(test_list)) # printing sort order listprint (\"The sort order list is : \" + str(sort_order)) # using sort() + lambda + index()# to sort according to other list# test_list.sort(key = lambda(i, j): sort_order.index(i)) # works in python 2test_list.sort(key = lambda i: sort_order.index(i[0])) # works in python 3 # printing resultprint (\"The sorted list is : \" + str(test_list))", "e": 28416, "s": 27740, "text": null }, { "code": null, "e": 28588, "s": 28416, "text": "The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\nThe sort order list is : ['d', 'c', 'a', 'b']\nThe sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]" }, { "code": null, "e": 28603, "s": 28590, "text": "Kiran Kotari" }, { "code": null, "e": 28618, "s": 28603, "text": "varshagumber28" }, { "code": null, "e": 28639, "s": 28618, "text": "Python list-programs" }, { "code": null, "e": 28651, "s": 28639, "text": "python-list" }, { "code": null, "e": 28658, "s": 28651, "text": "Python" }, { "code": null, "e": 28670, "s": 28658, "text": "python-list" }, { "code": null, "e": 28768, "s": 28670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28786, "s": 28768, "text": "Python Dictionary" }, { "code": null, "e": 28818, "s": 28786, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28853, "s": 28818, "text": "Read a file line by line in Python" }, { "code": null, "e": 28875, "s": 28853, "text": "Enumerate() in Python" }, { "code": null, "e": 28917, "s": 28875, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28947, "s": 28917, "text": "Iterate over a list in Python" }, { "code": null, "e": 28973, "s": 28947, "text": "Python String | replace()" }, { "code": null, "e": 29017, "s": 28973, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29046, "s": 29017, "text": "*args and **kwargs in Python" } ]
Python | Pandas Index.contains() - GeeksforGeeks
16 Oct, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.contains() function return a boolean indicating whether the provided key is in the index. If the input value is present in the Index then it returns True else it returns False indicating that the input value is not present in the Index. Syntax: Index.contains(key) Parameters :Key : Object Returns : boolean Example #1: Use Index.contains() function to check if the given date is present in the Index. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03', '2016-02-08', '2017-05-05']) # Print the Indexidx Output : Let’s check if ‘2016-02-08’ is present in the Index or not. # Check if input date in present or not.idx.contains('2016-02-08') Output :As we can see in the output, the function has returned True indicating that the value is present in the Index. Example #2: Use Index.contains() function to check if the input month is present in the Index or not. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx Output : Let’s check if ‘May’ is present in the Index or not # to check if the input month is# part of the Index or not.idx.contains('May') Output : Akanksha_Rai Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Oct, 2019" }, { "code": null, "e": 25751, "s": 25537, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26001, "s": 25751, "text": "Pandas Index.contains() function return a boolean indicating whether the provided key is in the index. If the input value is present in the Index then it returns True else it returns False indicating that the input value is not present in the Index." }, { "code": null, "e": 26029, "s": 26001, "text": "Syntax: Index.contains(key)" }, { "code": null, "e": 26054, "s": 26029, "text": "Parameters :Key : Object" }, { "code": null, "e": 26072, "s": 26054, "text": "Returns : boolean" }, { "code": null, "e": 26166, "s": 26072, "text": "Example #1: Use Index.contains() function to check if the given date is present in the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03', '2016-02-08', '2017-05-05']) # Print the Indexidx", "e": 26367, "s": 26166, "text": null }, { "code": null, "e": 26376, "s": 26367, "text": "Output :" }, { "code": null, "e": 26436, "s": 26376, "text": "Let’s check if ‘2016-02-08’ is present in the Index or not." }, { "code": "# Check if input date in present or not.idx.contains('2016-02-08')", "e": 26503, "s": 26436, "text": null }, { "code": null, "e": 26724, "s": 26503, "text": "Output :As we can see in the output, the function has returned True indicating that the value is present in the Index. Example #2: Use Index.contains() function to check if the input month is present in the Index or not." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx", "e": 26926, "s": 26724, "text": null }, { "code": null, "e": 26935, "s": 26926, "text": "Output :" }, { "code": null, "e": 26987, "s": 26935, "text": "Let’s check if ‘May’ is present in the Index or not" }, { "code": "# to check if the input month is# part of the Index or not.idx.contains('May')", "e": 27066, "s": 26987, "text": null }, { "code": null, "e": 27075, "s": 27066, "text": "Output :" }, { "code": null, "e": 27088, "s": 27075, "text": "Akanksha_Rai" }, { "code": null, "e": 27111, "s": 27088, "text": "Python pandas-indexing" }, { "code": null, "e": 27125, "s": 27111, "text": "Python-pandas" }, { "code": null, "e": 27132, "s": 27125, "text": "Python" }, { "code": null, "e": 27230, "s": 27132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27262, "s": 27230, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27304, "s": 27262, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27346, "s": 27304, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27373, "s": 27346, "text": "Python Classes and Objects" }, { "code": null, "e": 27429, "s": 27373, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27468, "s": 27429, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27490, "s": 27468, "text": "Defaultdict in Python" }, { "code": null, "e": 27521, "s": 27490, "text": "Python | os.path.join() method" }, { "code": null, "e": 27550, "s": 27521, "text": "Create a directory in Python" } ]
Transform the Scaled Matrix to its Original Form in R Programming - Using Matrix Computations - GeeksforGeeks
18 Jan, 2022 In R programming, a matrix can be scaled and centered using scale() function. But, there is no in-built function to transform the scaled matrix back to the original matrix. In this article, we’ll learn to transform the scaled matrix back to the original matrix using some simple computations. Attributes of the scaled matrix can be used to unscale the matrix back to its original matrix. R # Create matrixmt <- matrix(c(1:20), ncol = 5) # Print original matrixcat("Original matrix:\n")print(mt) # Scale the matrixscaled.mt <- scale(mt) # Print Scaled matrixcat("Scaled matrix:\n")print(scaled.mt) # Unscale the matrixunscaled.mt <- t(apply(scaled.mt, 1, function(r) r * attr(scaled.mt, 'scaled:scale') + attr(scaled.mt, 'scaled:center'))) # Print Unscaled matrixcat("Unscaled matrix:\n")print(unscaled.mt) Output: Original matrix: [, 1] [, 2] [, 3] [, 4] [, 5] [1, ] 1 5 9 13 17 [2, ] 2 6 10 14 18 [3, ] 3 7 11 15 19 [4, ] 4 8 12 16 20 Scaled matrix: [, 1] [, 2] [, 3] [, 4] [, 5] [1, ] -1.1618950 -1.1618950 -1.1618950 -1.1618950 -1.1618950 [2, ] -0.3872983 -0.3872983 -0.3872983 -0.3872983 -0.3872983 [3, ] 0.3872983 0.3872983 0.3872983 0.3872983 0.3872983 [4, ] 1.1618950 1.1618950 1.1618950 1.1618950 1.1618950 attr(, "scaled:center") [1] 2.5 6.5 10.5 14.5 18.5 attr(, "scaled:scale") [1] 1.290994 1.290994 1.290994 1.290994 1.290994 Unscaled matrix: [, 1] [, 2] [, 3] [, 4] [, 5] [1, ] 1 5 9 13 17 [2, ] 2 6 10 14 18 [3, ] 3 7 11 15 19 [4, ] 4 8 12 16 20 In this example, we’ll unscale the scaled matrix using mean and standard deviation of the original matrix. R # Create matrixa <- rnorm(5, 5, 2)b <- rnorm(5, 7, 5) mt <- cbind(a, b) # get center and scaling values m <- apply(df, 2, mean)s <- apply(df, 2, sd) # Print original matrixcat("Original matrix:\n")print(mt) # Scale the matrixscaled.mt <- scale(mt, center = m, scale = s) # Print Scaled matrixcat("Scaled matrix:\n")print(scaled.mt) # Unscale the matrixunscaled.mt <- t((t(scaled.mt) * s) + m) # Print Unscaled matrixcat("Unscaled matrix:\n")print(unscaled.mt) Original matrix: a b [1, ] 5.552301 1.9865159 [2, ] 3.936486 17.5327829 [3, ] 5.379720 15.0981877 [4, ] 3.546333 0.5230305 [5, ] 5.043194 2.0930855 Scaled matrix: a b [1, ] 0.01543556 -2.062174 [2, ] -0.69057233 5.252016 [3, ] -0.05997146 4.106591 [4, ] -0.86104456 -2.750713 [5, ] -0.20701146 -2.012036 attr(, "scaled:center") a b 5.516974 6.369655 attr(, "scaled:scale") a b 2.288663 2.125494 Unscaled matrix: a b [1, ] 5.552301 1.9865159 [2, ] 3.936486 17.5327829 [3, ] 5.379720 15.0981877 [4, ] 3.546333 0.5230305 [5, ] 5.043194 2.0930855 attr(, "scaled:center") a b 5.516974 6.369655 attr(, "scaled:scale") a b 2.288663 2.125494 gabaa406 R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n18 Jan, 2022" }, { "code": null, "e": 26780, "s": 26487, "text": "In R programming, a matrix can be scaled and centered using scale() function. But, there is no in-built function to transform the scaled matrix back to the original matrix. In this article, we’ll learn to transform the scaled matrix back to the original matrix using some simple computations." }, { "code": null, "e": 26875, "s": 26780, "text": "Attributes of the scaled matrix can be used to unscale the matrix back to its original matrix." }, { "code": null, "e": 26877, "s": 26875, "text": "R" }, { "code": "# Create matrixmt <- matrix(c(1:20), ncol = 5) # Print original matrixcat(\"Original matrix:\\n\")print(mt) # Scale the matrixscaled.mt <- scale(mt) # Print Scaled matrixcat(\"Scaled matrix:\\n\")print(scaled.mt) # Unscale the matrixunscaled.mt <- t(apply(scaled.mt, 1, function(r) r * attr(scaled.mt, 'scaled:scale') + attr(scaled.mt, 'scaled:center'))) # Print Unscaled matrixcat(\"Unscaled matrix:\\n\")print(unscaled.mt)", "e": 27346, "s": 26877, "text": null }, { "code": null, "e": 27354, "s": 27346, "text": "Output:" }, { "code": null, "e": 28156, "s": 27354, "text": "Original matrix:\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] 1 5 9 13 17\n[2, ] 2 6 10 14 18\n[3, ] 3 7 11 15 19\n[4, ] 4 8 12 16 20\nScaled matrix:\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] -1.1618950 -1.1618950 -1.1618950 -1.1618950 -1.1618950\n[2, ] -0.3872983 -0.3872983 -0.3872983 -0.3872983 -0.3872983\n[3, ] 0.3872983 0.3872983 0.3872983 0.3872983 0.3872983\n[4, ] 1.1618950 1.1618950 1.1618950 1.1618950 1.1618950\nattr(, \"scaled:center\")\n[1] 2.5 6.5 10.5 14.5 18.5\nattr(, \"scaled:scale\")\n[1] 1.290994 1.290994 1.290994 1.290994 1.290994\nUnscaled matrix:\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] 1 5 9 13 17\n[2, ] 2 6 10 14 18\n[3, ] 3 7 11 15 19\n[4, ] 4 8 12 16 20\n" }, { "code": null, "e": 28263, "s": 28156, "text": "In this example, we’ll unscale the scaled matrix using mean and standard deviation of the original matrix." }, { "code": null, "e": 28265, "s": 28263, "text": "R" }, { "code": "# Create matrixa <- rnorm(5, 5, 2)b <- rnorm(5, 7, 5) mt <- cbind(a, b) # get center and scaling values m <- apply(df, 2, mean)s <- apply(df, 2, sd) # Print original matrixcat(\"Original matrix:\\n\")print(mt) # Scale the matrixscaled.mt <- scale(mt, center = m, scale = s) # Print Scaled matrixcat(\"Scaled matrix:\\n\")print(scaled.mt) # Unscale the matrixunscaled.mt <- t((t(scaled.mt) * s) + m) # Print Unscaled matrixcat(\"Unscaled matrix:\\n\")print(unscaled.mt)", "e": 28733, "s": 28265, "text": null }, { "code": null, "e": 29508, "s": 28733, "text": "Original matrix:\n a b\n[1, ] 5.552301 1.9865159\n[2, ] 3.936486 17.5327829\n[3, ] 5.379720 15.0981877\n[4, ] 3.546333 0.5230305\n[5, ] 5.043194 2.0930855\n\nScaled matrix:\n a b\n[1, ] 0.01543556 -2.062174\n[2, ] -0.69057233 5.252016\n[3, ] -0.05997146 4.106591\n[4, ] -0.86104456 -2.750713\n[5, ] -0.20701146 -2.012036\nattr(, \"scaled:center\")\n a b \n5.516974 6.369655 \nattr(, \"scaled:scale\")\n a b \n2.288663 2.125494 \n\nUnscaled matrix:\n a b\n[1, ] 5.552301 1.9865159\n[2, ] 3.936486 17.5327829\n[3, ] 5.379720 15.0981877\n[4, ] 3.546333 0.5230305\n[5, ] 5.043194 2.0930855\nattr(, \"scaled:center\")\n a b \n5.516974 6.369655 \nattr(, \"scaled:scale\")\n a b \n2.288663 2.125494 \n" }, { "code": null, "e": 29517, "s": 29508, "text": "gabaa406" }, { "code": null, "e": 29535, "s": 29517, "text": "R Matrix-Function" }, { "code": null, "e": 29546, "s": 29535, "text": "R Language" }, { "code": null, "e": 29644, "s": 29546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29696, "s": 29644, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29731, "s": 29696, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29769, "s": 29731, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29827, "s": 29769, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29870, "s": 29827, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29907, "s": 29870, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29956, "s": 29907, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29982, "s": 29956, "text": "Time Series Analysis in R" }, { "code": null, "e": 29999, "s": 29982, "text": "R - if statement" } ]
Java Program for Sum of squares of first n natural numbers - GeeksforGeeks
11 May, 2022 Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2.Examples: Input : N = 4 Output : 30 12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30 Input : N = 5 Output : 55 Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum. Java // Java Program to find sum of// square of first n natural numbersimport java.io.*; class GFG { // Return the sum of square of first n natural numbers static int squaresum(int n) { // Iterate i from 1 and n // finding square of i and add to sum. int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driven Program public static void main(String args[]) throws IOException { int n = 4; System.out.println(squaresum(n)); }} /*This code is contributed by Nikita Tiwari.*/ 30 Method 2: O(1) Proof: We know, (k + 1)3 = k3 + 3 * k2 + 3 * k + 1 We can write the above identity for k from 1 to n: 23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1) 33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2) 43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3) 53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4) ... n3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1) (n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n) Putting equation (n - 1) in equation n, (n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1 = (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1 By putting all equation, we get (n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1 n3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n n3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n n3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2 n * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2 n * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2 n * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2 n * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2 n * (n + 1) * (2 * n + 1)/6 = Σ k2 Java // Java Program to find sum// of square of first n// natural numbersimport java.io.*; class GFG { // Return the sum of square // of first n natural numbers static int squaresum(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driven Program public static void main(String args[]) throws IOException { int n = 4; System.out.println(squaresum(n)); }} /*This code is contributed by Nikita Tiwari.*/ 30 Avoiding early overflow: For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2. Java // Java Program to find sum of square of first// n natural numbers. This program avoids// overflow upto some extent for large value// of n. import java.io.*;import java.util.*; class GFG { // Return the sum of square of first n natural // numbers public static int squaresum(int n) { return (n * (n + 1) / 2) * (2 * n + 1) / 3; } public static void main(String[] args) { int n = 4; System.out.println(squaresum(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)> 30 Please refer complete article on Sum of squares of first n natural numbers for more details! singghakshay surinderdawra388 Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Iterate HashMap in Java? Program to print ASCII Value of a character Iterate through List in Java Java Program to Remove Duplicate Elements From the Array Java program to count the occurrence of each character in a string using Hashmap Factory method design pattern in Java Min Heap in Java Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Remove first and last character of a string in Java
[ { "code": null, "e": 26223, "s": 26195, "text": "\n11 May, 2022" }, { "code": null, "e": 26308, "s": 26223, "text": "Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2.Examples: " }, { "code": null, "e": 26401, "s": 26308, "text": "Input : N = 4\nOutput : 30\n12 + 22 + 32 + 42\n= 1 + 4 + 9 + 16\n= 30\n\nInput : N = 5\nOutput : 55" }, { "code": null, "e": 26500, "s": 26401, "text": "Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum. " }, { "code": null, "e": 26505, "s": 26500, "text": "Java" }, { "code": "// Java Program to find sum of// square of first n natural numbersimport java.io.*; class GFG { // Return the sum of square of first n natural numbers static int squaresum(int n) { // Iterate i from 1 and n // finding square of i and add to sum. int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driven Program public static void main(String args[]) throws IOException { int n = 4; System.out.println(squaresum(n)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 27082, "s": 26505, "text": null }, { "code": null, "e": 27085, "s": 27082, "text": "30" }, { "code": null, "e": 27103, "s": 27087, "text": "Method 2: O(1) " }, { "code": null, "e": 27111, "s": 27103, "text": "Proof: " }, { "code": null, "e": 28156, "s": 27111, "text": "We know,\n(k + 1)3 = k3 + 3 * k2 + 3 * k + 1\nWe can write the above identity for k from 1 to n:\n23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)\n33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)\n43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)\n53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)\n...\nn3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)\n(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)\n\nPutting equation (n - 1) in equation n,\n(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1\n = (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1\n\nBy putting all equation, we get\n(n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1\nn3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n\nn3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n\nn3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2\nn * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2\nn * (n + 1) * (2 * n + 1)/6 = Σ k2" }, { "code": null, "e": 28161, "s": 28156, "text": "Java" }, { "code": "// Java Program to find sum// of square of first n// natural numbersimport java.io.*; class GFG { // Return the sum of square // of first n natural numbers static int squaresum(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driven Program public static void main(String args[]) throws IOException { int n = 4; System.out.println(squaresum(n)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 28619, "s": 28161, "text": null }, { "code": null, "e": 28622, "s": 28619, "text": "30" }, { "code": null, "e": 28811, "s": 28624, "text": "Avoiding early overflow: For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2." }, { "code": null, "e": 28816, "s": 28811, "text": "Java" }, { "code": "// Java Program to find sum of square of first// n natural numbers. This program avoids// overflow upto some extent for large value// of n. import java.io.*;import java.util.*; class GFG { // Return the sum of square of first n natural // numbers public static int squaresum(int n) { return (n * (n + 1) / 2) * (2 * n + 1) / 3; } public static void main(String[] args) { int n = 4; System.out.println(squaresum(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 29328, "s": 28816, "text": null }, { "code": null, "e": 29331, "s": 29328, "text": "30" }, { "code": null, "e": 29426, "s": 29333, "text": "Please refer complete article on Sum of squares of first n natural numbers for more details!" }, { "code": null, "e": 29439, "s": 29426, "text": "singghakshay" }, { "code": null, "e": 29456, "s": 29439, "text": "surinderdawra388" }, { "code": null, "e": 29470, "s": 29456, "text": "Java Programs" }, { "code": null, "e": 29568, "s": 29470, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29600, "s": 29568, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 29644, "s": 29600, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 29673, "s": 29644, "text": "Iterate through List in Java" }, { "code": null, "e": 29730, "s": 29673, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 29811, "s": 29730, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 29849, "s": 29811, "text": "Factory method design pattern in Java" }, { "code": null, "e": 29866, "s": 29849, "text": "Min Heap in Java" }, { "code": null, "e": 29914, "s": 29866, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 29965, "s": 29914, "text": "How to Get Elements By Index from HashSet in Java?" } ]
Write a program to Calculate Size of a tree | Recursion - GeeksforGeeks
13 Jan, 2022 Size of a tree is the number of elements present in the tree. Size of the below tree is 5. Size() function recursively calculates the size of a tree. It works as follows:Size of a tree = Size of left subtree + 1 + Size of right subtree. Algorithm: size(tree) 1. If tree is empty then return 0 2. Else (a) Get the size of left subtree recursively i.e., call size( tree->left-subtree) (a) Get the size of right subtree recursively i.e., call size( tree->right-subtree) (c) Calculate size of the tree as following: tree_size = size(left-subtree) + size(right- subtree) + 1 (d) Return tree_size C++ C Java Python3 C# Javascript // A recursive C++ program to// calculate the size of the tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Computes the number of nodes in a tree. */int size(node* node){ if (node == NULL) return 0; else return(size(node->left) + 1 + size(node->right));} /* Driver code*/int main(){ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Size of the tree is " << size(root); return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Computes the number of nodes in a tree. */int size(struct node* node){ if (node==NULL) return 0; else return(size(node->left) + 1 + size(node->right)); } /* Driver program to test size function*/ int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Size of the tree is %d", size(root)); getchar(); return 0;} // A recursive Java program to calculate the size of the tree /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to find size of Binary Tree */class BinaryTree{ Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ int size() { return size(root); } /* computes number of nodes in tree */ int size(Node node) { if (node == null) return 0; else return(size(node.left) + 1 + size(node.right)); } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("The size of binary tree is : " + tree.size()); }} # Python Program to find the size of binary tree # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Computes the number of nodes in treedef size(node): if node is None: return 0 else: return (size(node.left)+ 1 + size(node.right)) # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print("Size of the tree is %d" %(size(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // A recursive C# program to calculate the size of the tree /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to find size of Binary Tree */public class BinaryTree{ public Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ public virtual int size() { return size(root); } /* computes number of nodes in tree */ public virtual int size(Node node) { if (node == null) { return 0; } else { return (size(node.left) + 1 + size(node.right)); } } public static void Main(string[] args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine("The size of binary tree is : " + tree.size()); }} // This code is contributed by Shrikant13 <script> // A recursive JavaScript program to // calculate the size of the tree /* Class containing left and right child of current node and key value*/ class Node { constructor(item) { this.data = item; this.left = null; this.right = null; } } /* Class to find size of Binary Tree */ class BinaryTree { constructor() { this.root = null; } /* computes number of nodes in tree */ size(node = this.root) { if (node == null) { return 0; } else { return this.size(node.left) + 1 + this.size(node.right); } } } /* creating a binary tree and entering the nodes */ var tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); document.write("Size of the tree is " + tree.size() + "<br>"); </script> Output: Size of the tree is 5 Time & Space Complexities: Since this program is similar to traversal of tree, time and space complexities will be same as Tree traversal (Please see our Tree Traversal post for details) YouTubeGeeksforGeeks507K subscribersSize of a Binary Tree | GeeksforGeeksWatch 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:000:00 / 4:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Pivw7bIEB3I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk shrikanth13 rathbhupendra rdtank amartyaghoshgfg Size of a Tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Deletion in a Binary Tree Binary Tree (Array implementation) BFS vs DFS for Binary Tree
[ { "code": null, "e": 26201, "s": 26173, "text": "\n13 Jan, 2022" }, { "code": null, "e": 26294, "s": 26201, "text": "Size of a tree is the number of elements present in the tree. Size of the below tree is 5. " }, { "code": null, "e": 26441, "s": 26294, "text": "Size() function recursively calculates the size of a tree. It works as follows:Size of a tree = Size of left subtree + 1 + Size of right subtree. " }, { "code": null, "e": 26454, "s": 26441, "text": "Algorithm: " }, { "code": null, "e": 26886, "s": 26454, "text": "size(tree)\n1. If tree is empty then return 0\n2. Else\n (a) Get the size of left subtree recursively i.e., call \n size( tree->left-subtree)\n (a) Get the size of right subtree recursively i.e., call \n size( tree->right-subtree)\n (c) Calculate size of the tree as following:\n tree_size = size(left-subtree) + size(right-\n subtree) + 1\n (d) Return tree_size" }, { "code": null, "e": 26892, "s": 26888, "text": "C++" }, { "code": null, "e": 26894, "s": 26892, "text": "C" }, { "code": null, "e": 26899, "s": 26894, "text": "Java" }, { "code": null, "e": 26907, "s": 26899, "text": "Python3" }, { "code": null, "e": 26910, "s": 26907, "text": "C#" }, { "code": null, "e": 26921, "s": 26910, "text": "Javascript" }, { "code": "// A recursive C++ program to// calculate the size of the tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Computes the number of nodes in a tree. */int size(node* node){ if (node == NULL) return 0; else return(size(node->left) + 1 + size(node->right));} /* Driver code*/int main(){ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << \"Size of the tree is \" << size(root); return 0;} // This code is contributed by rathbhupendra", "e": 27894, "s": 26921, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Computes the number of nodes in a tree. */int size(struct node* node){ if (node==NULL) return 0; else return(size(node->left) + 1 + size(node->right)); } /* Driver program to test size function*/ int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(\"Size of the tree is %d\", size(root)); getchar(); return 0;}", "e": 28860, "s": 27894, "text": null }, { "code": "// A recursive Java program to calculate the size of the tree /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to find size of Binary Tree */class BinaryTree{ Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ int size() { return size(root); } /* computes number of nodes in tree */ int size(Node node) { if (node == null) return 0; else return(size(node.left) + 1 + size(node.right)); } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println(\"The size of binary tree is : \" + tree.size()); }}", "e": 29994, "s": 28860, "text": null }, { "code": "# Python Program to find the size of binary tree # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Computes the number of nodes in treedef size(node): if node is None: return 0 else: return (size(node.left)+ 1 + size(node.right)) # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print(\"Size of the tree is %d\" %(size(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 30622, "s": 29994, "text": null }, { "code": "using System; // A recursive C# program to calculate the size of the tree /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to find size of Binary Tree */public class BinaryTree{ public Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ public virtual int size() { return size(root); } /* computes number of nodes in tree */ public virtual int size(Node node) { if (node == null) { return 0; } else { return (size(node.left) + 1 + size(node.right)); } } public static void Main(string[] args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine(\"The size of binary tree is : \" + tree.size()); }} // This code is contributed by Shrikant13", "e": 31887, "s": 30622, "text": null }, { "code": "<script> // A recursive JavaScript program to // calculate the size of the tree /* Class containing left and right child of current node and key value*/ class Node { constructor(item) { this.data = item; this.left = null; this.right = null; } } /* Class to find size of Binary Tree */ class BinaryTree { constructor() { this.root = null; } /* computes number of nodes in tree */ size(node = this.root) { if (node == null) { return 0; } else { return this.size(node.left) + 1 + this.size(node.right); } } } /* creating a binary tree and entering the nodes */ var tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); document.write(\"Size of the tree is \" + tree.size() + \"<br>\"); </script>", "e": 32936, "s": 31887, "text": null }, { "code": null, "e": 32946, "s": 32936, "text": "Output: " }, { "code": null, "e": 32968, "s": 32946, "text": "Size of the tree is 5" }, { "code": null, "e": 33157, "s": 32968, "text": "Time & Space Complexities: Since this program is similar to traversal of tree, time and space complexities will be same as Tree traversal (Please see our Tree Traversal post for details) " }, { "code": null, "e": 33977, "s": 33157, "text": "YouTubeGeeksforGeeks507K subscribersSize of a Binary Tree | GeeksforGeeksWatch 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:000:00 / 4:46•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Pivw7bIEB3I\" 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": 34019, "s": 33977, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 34031, "s": 34019, "text": "shrikanth13" }, { "code": null, "e": 34045, "s": 34031, "text": "rathbhupendra" }, { "code": null, "e": 34052, "s": 34045, "text": "rdtank" }, { "code": null, "e": 34068, "s": 34052, "text": "amartyaghoshgfg" }, { "code": null, "e": 34083, "s": 34068, "text": "Size of a Tree" }, { "code": null, "e": 34088, "s": 34083, "text": "Tree" }, { "code": null, "e": 34093, "s": 34088, "text": "Tree" }, { "code": null, "e": 34191, "s": 34093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34234, "s": 34191, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 34267, "s": 34234, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 34281, "s": 34267, "text": "Decision Tree" }, { "code": null, "e": 34317, "s": 34281, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 34365, "s": 34317, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 34448, "s": 34365, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 34464, "s": 34448, "text": "Expression Tree" }, { "code": null, "e": 34490, "s": 34464, "text": "Deletion in a Binary Tree" }, { "code": null, "e": 34525, "s": 34490, "text": "Binary Tree (Array implementation)" } ]
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) - GeeksforGeeks
10 May, 2022 Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in A[] whose sum is exactly x. Examples: Input: arr[] = {0, -1, 2, -3, 1} x= -2Output: Pair with a given sum -2 is (-3, 1) Valid pair existsExplanation: If we calculate the sum of the output,1 + (-3) = -2 Input: arr[] = {1, -2, 1, 0, 5} x = 0Output: No valid pair exists for 0 Method: Using simple logic by calculating the array’s elements themselves. C++ C Java Python3 C# Javascript Go // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find and print pairbool chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { cout << "Pair with a given sum " << x << " is (" << A[i] << ", " << A[j] << ")" << endl; return 1; } } } return 0;} int main() { int A[] = {0, -1, 2, -3, 1}; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { cout << "Valid pair exists" << endl; } else { cout << "No valid pair exists for " << x << endl; } return 0;} // This code is contributed by Samim Hossain Mondal. /* * This C program tells if there exists a pair in array whose sum results in x. */ #include <stdio.h> // Function to find and print pairint chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { printf("Pair with a given sum %d is (%d, %d)\n", x, A[i], A[j]); return 1; } } } return 0;} int main(void) { int A[] = {0, -1, 2, -3, 1}; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { printf("Valid pair exists\n"); } else { printf("No valid pair exists for %d\n", x); } return 0;}// This code is contributed by Manish Kumar (mkumar2789) // Java program to check if there exists a pair// in array whose sum results in x.class GFG{ // Function to find and print pair static boolean chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { System.out.println("Pair with a given sum " + x + " is (" + A[i] + ", " + A[j] + ")"); return true; } } } return false; } public static void main(String [] args) { int A[] = {0, -1, 2, -3, 1}; int x = -2; int size = A.length; if (chkPair(A, size, x)) { System.out.println("Valid pair exists"); } else { System.out.println("No valid pair exists for " + x ); } }} // This code is contributed by umadevi9616 # This python program tells if there exists a pair in array whose sum results in x. # Function to find and print pairdef chkPair(A, size, x): for i in range(0, size - 1): for j in range(i + 1, size): if (A[i] + A[j] == x): print(f"Pair with a given sum {x} is ({A[i]},{A[j]})") return 1 return 0 if __name__ == "__main__": A = [0, -1, 2, -3, 1] x = -2 size = len(A) if (chkPair(A, size, x)): print("Valid pair exists") else: print(f"No valid pair exists for {x}") # This code is contributed by rakeshsahni // C# program to check if there exists a pair// in array whose sum results in x.using System;class GFG{ // Function to find and print pair static bool chkPair(int [] A, int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { Console.WriteLine("Pair with a given sum " + x + " is (" + A[i] + ", " + A[j] + ")"); return true; } } } return false; } public static void Main() { int [] A = {0, -1, 2, -3, 1}; int x = -2; int size = A.Length; if (chkPair(A, size, x)) { Console.WriteLine("Valid pair exists"); } else { Console.WriteLine("No valid pair exists for " + x ); } }} // This code is contributed by Samim Hossain Mondal. <script> // Javascript program to check if there exists a pair// in array whose sum results in x. // Function to find and print pair function chkPair(A , size , x) { for (i = 0; i < (size - 1); i++) { for (j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { document.write("Pair with a given sum " + x + " is (" + A[i] + ", " + A[j] + ")"); return true; } } } return false; } let A = [ 0, -1, 2, -3, 1 ]; let x = -2; let size = A.length; if (chkPair(A, size, x)) { document.write("<br/>Valid pair exists"); } else { document.write("<br/>No valid pair exists for " + x); } // This code is contributed by Samim Hossain Mondal.</script> package mainimport ("fmt") func twoSum(nums [5]int, target int) { var flag bool = false result:=make([]int,2) for i:=0;i<len(nums)-1;i++{ for j:=i+1;j<len(nums);j++{ if nums[i]+nums[j]==target{ result[0]=nums[i] result[1]=nums[j] flag = true; } } } if(flag == false){ fmt.Println("No valid pair exists for " , target) }else { fmt.Printf( "Pair with a given sum " , target , " is (" , result[0], ", " , result[1] , ")") } } func main() { arr2 := [5]int{0, -1, 2, -3, 1} var x int = -2 twoSum(arr2, x)}// This code is contributed by NITUGAUR Pair with a given sum -2 is (-3, 1) Valid pair exists Time Complexity: O(n2)Auxiliary Space: O(1) Method 1: Sorting and Two-Pointers technique. Approach: A tricky approach to solve this problem can be to use the two-pointer technique. But for using two pointer technique, the array must be sorted. Once the array is sorted the two pointers can be taken which mark the beginning and end of the array respectively. If the sum is greater than the sum of those two elements, shift the right pointer to decrease the value of the required sum and if the sum is lesser than the required value, shift the left pointer to increase the value of the required sum. Let’s understand this using an example. Let an array be {1, 4, 45, 6, 10, -8} and sum to find be 16After sorting the array A = {-8, 1, 4, 6, 10, 45}Now, increment ‘l’ when the sum of the pair is less than the required sum and decrement ‘r’ when the sum of the pair is more than the required sum. This is because when the sum is less than the required sum then to get the number which could increase the sum of pair, start moving from left to right(also sort the array) thus “l++” and vice versa.Initialize l = 0, r = 5 A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 4 A[l] + A[r] ( -8 + 10) increment l. Now l = 1 A[l] + A[r] ( 1 + 10) increment l. Now l = 2 A[l] + A[r] ( 4 + 10) increment l. Now l = 3 A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1) Note: If there is more than one pair having the given sum then this algorithm reports only one. Can be easily extended for this though. Algorithm: hasArrayTwoCandidates (A[], ar_size, sum)Sort the array in non-decreasing order.Initialize two index variables to find the candidate elements in the sorted array. Initialize first to the leftmost index: l = 0Initialize second the rightmost index: r = ar_size-1Loop while l < r. If (A[l] + A[r] == sum) then return 1Else if( A[l] + A[r] < sum ) then l++Else r–No candidates in the whole array – return 0 hasArrayTwoCandidates (A[], ar_size, sum) Sort the array in non-decreasing order. Initialize two index variables to find the candidate elements in the sorted array. Initialize first to the leftmost index: l = 0Initialize second the rightmost index: r = ar_size-1 Initialize first to the leftmost index: l = 0Initialize second the rightmost index: r = ar_size-1 Initialize first to the leftmost index: l = 0 Initialize second the rightmost index: r = ar_size-1 Loop while l < r. If (A[l] + A[r] == sum) then return 1Else if( A[l] + A[r] < sum ) then l++Else r– If (A[l] + A[r] == sum) then return 1Else if( A[l] + A[r] < sum ) then l++Else r– If (A[l] + A[r] == sum) then return 1 Else if( A[l] + A[r] < sum ) then l++ Else r– No candidates in the whole array – return 0 Below is the implementation of the above approach: C++ C Java Python C# PHP Javascript // C++ program to check if given array// has 2 elements whose sum is equal// to the given value #include <bits/stdc++.h>using namespace std; // Function to check if array has 2 elements// whose sum is equal to the given valuebool hasArrayTwoCandidates(int A[], int arr_size, int sum){ int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return 0;} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) cout << "Array has two elements" " with given sum"; else cout << "Array doesn't have two" " elements with given sum"; return 0;} // C program to check if given array// has 2 elements whose sum is equal// to the given value #include <stdio.h>#define bool int void quickSort(int*, int, int); bool hasArrayTwoCandidates( int A[], int arr_size, int sum){ int l, r; /* Sort the elements */ quickSort(A, 0, arr_size - 1); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return 0;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int A[], int si, int ei){ int x = A[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if (A[j] <= x) { i++; exchange(&A[i], &A[j]); } } exchange(&A[i + 1], &A[ei]); return (i + 1);} /* Implementation of Quick SortA[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int A[], int si, int ei){ int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); }} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = 6; if (hasArrayTwoCandidates(A, arr_size, n)) printf("Array has two elements with given sum"); else printf("Array doesn't have two elements with given sum"); getchar(); return 0;} // Java program to check if given array// has 2 elements whose sum is equal// to the given valueimport java.util.*; class GFG { // Function to check if array has 2 elements // whose sum is equal to the given value static boolean hasArrayTwoCandidates( int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ Arrays.sort(A); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return true; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return false; } // Driver code public static void main(String args[]) { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = A.length; // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) System.out.println("Array has two " + "elements with given sum"); else System.out.println("Array doesn't have " + "two elements with given sum"); }} # Python program to check for the sum# condition to be satisfied def hasArrayTwoCandidates(A, arr_size, sum): # sort the array quickSort(A, 0, arr_size-1) l = 0 r = arr_size-1 # traverse the array for the two elements while l<r: if (A[l] + A[r] == sum): return 1 elif (A[l] + A[r] < sum): l += 1 else: r -= 1 return 0 # Implementation of Quick Sort# A[] --> Array to be sorted# si --> Starting index# ei --> Ending indexdef quickSort(A, si, ei): if si < ei: pi = partition(A, si, ei) quickSort(A, si, pi-1) quickSort(A, pi + 1, ei) # Utility function for partitioning# the array(used in quick sort)def partition(A, si, ei): x = A[ei] i = (si-1) for j in range(si, ei): if A[j] <= x: i += 1 # This operation is used to swap # two variables is python A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return i + 1 # Driver program to test the functionsA = [1, 4, 45, 6, 10, -8]n = 16if (hasArrayTwoCandidates(A, len(A), n)): print("Array has two elements with the given sum")else: print("Array doesn't have two elements with the given sum") ## This code is contributed by __Devesh Agrawal__ // C# program to check for pair// in A[] with sum as x using System; class GFG { static bool hasArrayTwoCandidates(int[] A, int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, 0, arr_size - 1); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return true; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return false; } /* Below functions are only to sort the array using QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi - 1); sort(arr, pi + 1, high); } } // Driver code public static void Main() { int[] A = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = 6; if (hasArrayTwoCandidates(A, arr_size, n)) Console.Write("Array has two elements" + " with given sum"); else Console.Write("Array doesn't have " + "two elements with given sum"); }} // This code is contributed by Sam007 <?php// PHP program to check if given// array has 2 elements whose sum// is equal to the given value // Function to check if array has// 2 elements whose sum is equal// to the given valuefunction hasArrayTwoCandidates($A, $arr_size, $sum){ $l; $r; /* Sort the elements */ //sort($A, A + arr_size); sort($A); /* Now look for the two candidates in the sorted array*/ $l = 0; $r = $arr_size - 1; while ($l < $r) { if($A[$l] + $A[$r] == $sum) return 1; else if($A[$l] + $A[$r] < $sum) $l++; else // A[i] + A[j] > sum $r--; } return 0;} // Driver Code$A = array (1, 4, 45, 6, 10, -8);$n = 16;$arr_size = sizeof($A); // Function callingif(hasArrayTwoCandidates($A, $arr_size, $n)) echo "Array has two elements " . "with given sum";else echo "Array doesn't have two " . "elements with given sum"; // This code is contributed by m_kit?> <script> // Javascript program to check if given array// has 2 elements whose sum is equal// to the given value // Function to check if array has 2 elements// whose sum is equal to the given valuefunction hasArrayTwoCandidates(A, arr_size, sum){ var l, r; /* Sort the elements */ A.sort(); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return 0;} /* Driver program to test above function */var A = [ 1, 4, 45, 6, 10, -8 ]var n = 16;var arr_size = A.length;// Function callingif (hasArrayTwoCandidates(A, arr_size, n)) document.write("Array has two elements" + " with the given sum");else document.write("Array doesn't have two" + " elements with the given sum"); </script> Array has two elements with given sum Complexity Analysis: Time Complexity: Depends on what sorting algorithm we use. If Merge Sort or Heap Sort is used then (-)(nlogn) in the worst case.If Quick Sort is used then O(n^2) in the worst case. If Merge Sort or Heap Sort is used then (-)(nlogn) in the worst case. If Quick Sort is used then O(n^2) in the worst case. Auxiliary Space: This too depends on sorting algorithm. The auxiliary space is O(n) for merge sort and O(1) for Heap Sort. Method 2: Hashing. Approach: This problem can be solved efficiently by using the technique of hashing. Use a hash_map to check for the current array value x(let), if there exists a value target_sum-x which on adding to the former gives target_sum. This can be done in constant time. Let’s look at the following example. arr[] = {0, -1, 2, -3, 1} sum = -2 Now start traversing: Step 1: For ‘0’ there is no valid number ‘-2’ so store ‘0’ in hash_map. Step 2: For ‘-1’ there is no valid number ‘-1’ so store ‘-1’ in hash_map. Step 3: For ‘2’ there is no valid number ‘-4’ so store ‘2’ in hash_map. Step 4: For ‘-3’ there is no valid number ‘1’ so store ‘-3’ in hash_map. Step 5: For ‘1’ there is a valid number ‘-3’ so answer is 1, -3 Algorithm: Initialize an empty hash table s.Do following for each element A[i] in A[] If s[x – A[i]] is set then print the pair (A[i], x – A[i])Insert A[i] into s. Initialize an empty hash table s. Do following for each element A[i] in A[] If s[x – A[i]] is set then print the pair (A[i], x – A[i])Insert A[i] into s. If s[x – A[i]] is set then print the pair (A[i], x – A[i])Insert A[i] into s. If s[x – A[i]] is set then print the pair (A[i], x – A[i]) Insert A[i] into s. Pseudo Code : unordered_set s for(i=0 to end) if(s.find(target_sum - arr[i]) == s.end) insert(arr[i] into s) else print arr[i], target-arr[i] C++ C Java Python3 C# Javascript // C++ program to check if given array// has 2 elements whose sum is equal// to the given value#include <bits/stdc++.h> using namespace std; void printPairs(int arr[], int arr_size, int sum){ unordered_set<int> s; for (int i = 0; i < arr_size; i++) { int temp = sum - arr[i]; if (s.find(temp) != s.end()) cout << "Pair with given sum " << sum << " is (" << arr[i] << "," << temp << ")" << endl; s.insert(arr[i]); }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0;} // C program to check if given array// has 2 elements whose sum is equal// to the given value // Works only if range elements is limited#include <stdio.h>#define MAX 100000 void printPairs(int arr[], int arr_size, int sum){ int i, temp; /*initialize hash set as 0*/ bool s[MAX] = { 0 }; for (i = 0; i < arr_size; i++) { temp = sum - arr[i]; if (s[temp] == 1) printf( "Pair with given sum %d is (%d, %d) n", sum, arr[i], temp); s[arr[i]] = 1; }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); printPairs(A, arr_size, n); getchar(); return 0;} // Java implementation using Hashingimport java.io.*;import java.util.HashSet; class PairSum { static void printpairs(int arr[], int sum) { HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < arr.length; ++i) { int temp = sum - arr[i]; // checking for condition if (s.contains(temp)) { System.out.println( "Pair with given sum " + sum + " is (" + arr[i] + ", " + temp + ")"); } s.add(arr[i]); } } // Driver Code public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; printpairs(A, n); }} // This article is contributed by Aakash Hasija # Python program to find if there are# two elements wtih given sum # function to check for the given sum# in the arraydef printPairs(arr, arr_size, sum): # Create an empty hash map # using an hashmap allows us to store the indices hashmap = {} for i in range(0, arr_size): temp = sum-arr[i] if (temp in hashmap): print (f'Pair with given sum {sum} is ({temp},{arr[i]}) at indices ({hashmap[temp]},{i})') hashmap[arr[i]] = i # driver codeA = [1, 4, 45, 6, 10, 8]n = 16printPairs(A, len(A), n) # This code will also work in case the array has the same number twice# and target is the sum of those numbers# Eg: Array = [4,6,4] Target = 8 # This code is contributed by __Achyut Upadhyay__ // C# implementation using Hashingusing System;using System.Collections.Generic; class GFG { static void printpairs(int[] arr, int sum) { HashSet<int> s = new HashSet<int>(); for (int i = 0; i < arr.Length; ++i) { int temp = sum - arr[i]; // checking for condition if (s.Contains(temp)) { Console.Write("Pair with given sum " + sum + " is (" + arr[i] + ", " + temp + ")"); } s.Add(arr[i]); } } // Driver Code static void Main() { int[] A = new int[] { 1, 4, 45, 6, 10, 8 }; int n = 16; printpairs(A, n); }} // This code is contributed by// Manish Shaw(manishshaw1) <script> // JavaScript program to check if given array// has 2 elements whose sum is equal// to the given value // Javascript implementation using Hashing function printpairs(arr, sum) { let s = new Set(); for (let i = 0; i < arr.length; ++i) { let temp = sum - arr[i]; // checking for condition if (s.has(temp)) { document.write( "Pair with given sum " + sum + " is (" + arr[i] + ", " + temp + ")"); } s.add(arr[i]); } } // Driver Code let A = [ 1, 4, 45, 6, 10, 8 ]; let n = 16; printpairs(A, n); </script> Pair with given sum 16 is (10,6) Complexity Analysis: Time Complexity: O(n). As the whole array is needed to be traversed only once. Auxiliary Space: O(n). A hash map has been used to store array elements. Note: The solution will work even if the range of numbers includes negative numbers + if the pair is formed by numbers recurring twice in array eg: array = [3,4,3]; pair = (3,3); target sum = 6. Method 3: Using remainders of the elements less than x. Approach: The idea is to count the elements with remainders when divided by x, i.e 0 to x-1, each remainder separately. Suppose we have x as 6, then the numbers which are less than 6 and have remainders which add up to 6 gives sum as 6 when added. For example, we have elements, 2,4 in the array and 2%6 = 2 and 4%6 =4, and these remainders add up to give 6. Like that we have to check for pairs with remainders (1,5),(2,4),(3,3). if we have one or more elements with remainder 1 and one or more elements with remainder 5, then surely we get a sum as 6. Here we do not consider (0,6) as the elements for the resultant pair should be less than 6. when it comes to (3,3) we have to check if we have two elements with remainder 3, then we can say that “There exists a pair whose sum is x”. Algorithm: 1. Create an array with size x. 2. Initialize all rem elements to zero. 3. Traverse the given array Do the following if arr[i] is less than x:r=arr[i]%x which is done to get the remainder.rem[r]=rem[r]+1 i.e. increasing the count of elements that have remainder r when divided with x. r=arr[i]%x which is done to get the remainder. rem[r]=rem[r]+1 i.e. increasing the count of elements that have remainder r when divided with x. 4. Now, traverse the rem array from 1 to x/2. If(rem[i]> 0 and rem[x-i]>0) then print “YES” and come out of the loop. This means that we have a pair that results in x upon doing. 5. Now when we reach at x/2 in the above loop If x is even, for getting a pair we should have two elements with remainder x/2.If rem[x/2]>1 then print “YES” else print “NO” If rem[x/2]>1 then print “YES” else print “NO” If it is not satisfied that is x is odd, it will have a separate pair with x-x/2.If rem[x/2]>1 and rem[x-x/2]>1 , then print “Yes” else, print”No”; If rem[x/2]>1 and rem[x-x/2]>1 , then print “Yes” else, print”No”; Implementation of the above algorithm: C++ C Java Python3 C# Javascript // Code in cpp to tell if there exists a pair in array whose// sum results in x.#include <iostream>using namespace std; // Function to print pairsvoid printPairs(int a[], int n, int x){ int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. cout << "Yes\n"; break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print "No". if (rem[x / 2] > 1) cout << "Yes\n"; else cout << "No\n"; } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) cout << "Yes\n"; else cout << "No\n"; } }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Code in c to tell if there exists a pair in array whose// sum results in x.#include <stdio.h> // Function to print pairsvoid printPairs(int a[], int n, int x){ int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. printf("Yes\n"); break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print "No". if (rem[x / 2] > 1) printf("Yes\n"); else printf("No\n"); } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) printf("Yes\n"); else printf("No\n"); } }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Code in Java to tell if there exists a pair in array// whose sum results in x.import java.util.*; class GFG { // Function to print pairs static void printPairs(int a[], int n, int x) { int i; int[] rem = new int[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if // the element is x, as numbers greater than // x can't be used to get a sum x. Updating // the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to // middle to find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i // will result to a sum of x. Once we get // two elements which add up to x , we print // x and break. System.out.println("Yes"); break; } } // Once we reach middle of remainder array, we have // to do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 // elements with remainder x/2, then we // will have two distinct elements which // add up to x. if we dont have more // than 1 element, print "No". if (rem[x / 2] > 1) System.out.println("Yes"); else System.out.println("No"); } else { // When x is odd we continue the same // process which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) System.out.println("Yes"); else System.out.println("No"); } } } /* Driver Code */ public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = A.length; // Function calling printPairs(A, arr_size, n); }} // This code is contributed by Aditya Kumar (adityakumar129) # Code in Python3 to tell if there# exists a pair in array whose# sum results in x. # Function to print pairsdef printPairs(a, n, x): rem = [] for i in range(x): # Initializing the rem # values with 0's. rem.append(0) for i in range(n): if (a[i] < x): # Perform the remainder operation # only if the element is x, as # numbers greater than x can't # be used to get a sum x.Updating # the count of remainders. rem[a[i] % x] += 1 # Traversing the remainder list from # start to middle to find pairs for i in range(1, x // 2): if (rem[i] > 0 and rem[x - i] > 0): # The elements with remainders # i and x-i will result to a # sum of x. Once we get two # elements which add up to x, # we print x and break. print("Yes") break # Once we reach middle of # remainder array, we have to # do operations based on x. if (i >= x // 2): if (x % 2 == 0): if (rem[x // 2] > 1): # If x is even and we have more # than 1 elements with remainder # x/2, then we will have two # distinct elements which add up # to x. if we dont have than 1 # element, print "No". print("Yes") else: print("No") else: # When x is odd we continue # the same process which we # did in previous loop. if (rem[x // 2] > 0 and rem[x - x // 2] > 0): print("Yes") else: print("No") # Driver CodeA = [ 1, 4, 45, 6, 10, 8 ]n = 16arr_size = len(A) # Function callingprintPairs(A, arr_size, n) # This code is contributed by subhammahato348 // C# Code in C# to tell if there// exists a pair in array whose// sum results in x.using System;class GFG{ // Function to print pairsstatic void printPairs(int []a, int n, int x){ int i; int []rem = new int[x]; for (i = 0; i < x; i++) { // initializing the rem // values with 0's. rem[i] = 0; } for (i = 0; i < n; i++) { if (a[i] < x) { // Perform the remainder // operation only if the // element is x, as numbers // greater than x can't // be used to get a sum x. // Updating the count of remainders. rem[a[i] % x]++; } } // Traversing the remainder list // from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders // i and x-i will // result to a sum of x. // Once we get two // elements which add up to x , // we print x and // break. Console.Write("Yes" + "\n"); break; } } // Once we reach middle of // remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { if (rem[x / 2] > 1) { // if x is even and // we have more than 1 // elements with remainder // x/2, then we will // have two distinct elements // which add up // to x. if we dont have //more than 1 // element, print "No". Console.Write("Yes" + "\n"); } else { Console.Write("No" + "\n"); } } else { // When x is odd we continue // the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) { Console.Write("Yes" + "\n"); } else { Console.WriteLine("No" + "\n"); } } }} /* Driver Code */public static void Main(string[] args){ int[] A = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = A.Length; // Function calling printPairs(A, arr_size, n);}} // This code is contributed by SoumikMondal <script> // Code in Javascript to tell if there// exists a pair in array whose// sum results in x. // Function to print pairsfunction printPairs(a, n, x){ let i; let rem = new Array(x); for(i = 0; i < x; i++) { // Initializing the rem // values with 0's. rem[i] = 0; } for(i = 0; i < n; i++) { if (a[i] < x) { // Perform the remainder // operation only if the // element is x, as numbers // greater than x can't // be used to get a sum x. // Updating the count of remainders. rem[a[i] % x]++; } } // Traversing the remainder list // from start to middle to // find pairs for(i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders // i and x-i will // result to a sum of x. // Once we get two // elements which add up to x , // we print x and // break. document.write("Yes" + "</br>"); break; } } // Once we reach middle of // remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { if (rem[x / 2] > 1) { // If x is even and // we have more than 1 // elements with remainder // x/2, then we will // have two distinct elements // which add up // to x. if we dont have //more than 1 // element, print "No". document.write("Yes" + "</br>"); } else { document.write("No" + "</br>"); } } else { // When x is odd we continue // the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) { document.write("Yes" + "</br>"); } else { document.write("No" + "</br>"); } } }} // Driver code let A = [ 1, 4, 45, 6, 10, 8 ];let n = 16;let arr_size = A.length; // Function callingprintPairs(A, arr_size, n); // This code is contributed by suresh07 </script> Yes Time Complexity: O(n+x)Auxiliary Space: O(x) Similarly, the indices of a pair that add up to a given sum can also be calculated by an unordered map. The only change here is that we also have to store indices of elements as values for each element as key. C++14 Python3 Javascript #include <bits/stdc++.h>using namespace std; pair<int,int> findSum(int *arr,int& n,int& target){ int i,findElement; unordered_map<int,int>mp; pair<int,int>result; for(i=0;i<n;i++) { findElement=target-arr[i]; if(mp[findElement]) { result.first=i-1; result.second=mp[findElement]-1; break; } else mp.insert({arr[i],i}); } return result;} int main(){ int arr[]={1,5,4,3,7,9,2}; int n=sizeof(arr)/sizeof(arr[0]); int search=7; pair<int,int>ans=findSum(arr,n,search); cout<<min(ans.first,ans.second)<<" "<<max(ans.first,ans.second); return 0;} def findSum(arr, n, target): mp = {} result = [0]*2 for i in range(n): findElement = target-arr[i] if(findElement in mp): result[0] = i - 1 result[1] = mp[findElement] - 1 break else: mp[arr[i]] = i return result # driver codearr = [1,5,4,3,7,9,2]n = len(arr)search = 7ans = findSum(arr,n,search)print(f"{min(ans[0], ans[1])} {max(ans[0], ans[1])}") # This code is contributed by shinjanpatra <script>function findSum(arr,n,target){ let i,findElement; let mp = new Map(); let result = []; for(i = 0; i < n; i++) { findElement = target-arr[i]; if(mp.has(findElement)) { result[0] = i - 1; result[1] = mp.get(findElement) - 1; break; } else mp.set(arr[i],i); } return result;} // driver code let arr = [1,5,4,3,7,9,2];let n = arr.length;let search = 7;let ans = findSum(arr,n,search);document.write(Math.min(ans[0], ans[1]) + " " +Math.max(ans[0], ans[1])); // This code is contributed by shinjanpatra </script> 1 2 Time Complexity: O(n)Auxiliary Space: O(n) Related Problems: Given two unsorted arrays, find all pairs whose sum is x Count pairs with given sum Count all distinct pairs with difference equal to k YouTubeGeeksforGeeks507K subscribersGiven an array A[] and a number x, check for pair in A[] with sum as x | GeeksforGeeksWatch 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:000:00 / 10:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=I7Nz1XzzPYc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. jit_t manishshaw1 Mayuri Gupta 4 hellokoding salonitayal bidibaaz123 SaiSanjanaGudla idkravitz aashish1995 SoumikMondal subhammahato348 shrey3108 suresh07 rrrtnx sg275527109 sanjoy_62 rajeev0719singh mdtauseef123 mkumar2789 AR_Gaurav umadevi9616 rakeshsahni surinderdawra388 samim2000 kk9826225 bml8ngqtq8nb1h971tf2wo5m68l4m0nmykp8nxmq prophet1999 shinjanpatra NITUGAUR harendrakumar123 avtarkumar719 germanshephered48 adityakumar129 ABCO Accolite Amazon Amazon-Question CarWale CarWale-Question FactSet Flipkart Hike Infosys Microsoft Morgan Stanley SAP Labs Wipro Zoho Arrays Backtracking Hash Recursion Infosys Zoho Flipkart Morgan Stanley Accolite Amazon Microsoft FactSet Hike ABCO Wipro SAP Labs CarWale Arrays Hash Recursion Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Linear Search N Queen Problem | Backtracking-3 Write a program to print all permutations of a given string Backtracking | Introduction Rat in a Maze | Backtracking-2 The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 39003, "s": 38975, "text": "\n10 May, 2022" }, { "code": null, "e": 39162, "s": 39003, "text": "Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in A[] whose sum is exactly x. " }, { "code": null, "e": 39173, "s": 39162, "text": "Examples: " }, { "code": null, "e": 39358, "s": 39173, "text": "Input: arr[] = {0, -1, 2, -3, 1} x= -2Output: Pair with a given sum -2 is (-3, 1) Valid pair existsExplanation: If we calculate the sum of the output,1 + (-3) = -2" }, { "code": null, "e": 39436, "s": 39358, "text": "Input: arr[] = {1, -2, 1, 0, 5} x = 0Output: No valid pair exists for 0" }, { "code": null, "e": 39511, "s": 39436, "text": "Method: Using simple logic by calculating the array’s elements themselves." }, { "code": null, "e": 39515, "s": 39511, "text": "C++" }, { "code": null, "e": 39517, "s": 39515, "text": "C" }, { "code": null, "e": 39522, "s": 39517, "text": "Java" }, { "code": null, "e": 39530, "s": 39522, "text": "Python3" }, { "code": null, "e": 39533, "s": 39530, "text": "C#" }, { "code": null, "e": 39544, "s": 39533, "text": "Javascript" }, { "code": null, "e": 39547, "s": 39544, "text": "Go" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find and print pairbool chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { cout << \"Pair with a given sum \" << x << \" is (\" << A[i] << \", \" << A[j] << \")\" << endl; return 1; } } } return 0;} int main() { int A[] = {0, -1, 2, -3, 1}; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { cout << \"Valid pair exists\" << endl; } else { cout << \"No valid pair exists for \" << x << endl; } return 0;} // This code is contributed by Samim Hossain Mondal.", "e": 40336, "s": 39547, "text": null }, { "code": "/* * This C program tells if there exists a pair in array whose sum results in x. */ #include <stdio.h> // Function to find and print pairint chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { printf(\"Pair with a given sum %d is (%d, %d)\\n\", x, A[i], A[j]); return 1; } } } return 0;} int main(void) { int A[] = {0, -1, 2, -3, 1}; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { printf(\"Valid pair exists\\n\"); } else { printf(\"No valid pair exists for %d\\n\", x); } return 0;}// This code is contributed by Manish Kumar (mkumar2789)", "e": 41102, "s": 40336, "text": null }, { "code": "// Java program to check if there exists a pair// in array whose sum results in x.class GFG{ // Function to find and print pair static boolean chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { System.out.println(\"Pair with a given sum \" + x + \" is (\" + A[i] + \", \" + A[j] + \")\"); return true; } } } return false; } public static void main(String [] args) { int A[] = {0, -1, 2, -3, 1}; int x = -2; int size = A.length; if (chkPair(A, size, x)) { System.out.println(\"Valid pair exists\"); } else { System.out.println(\"No valid pair exists for \" + x ); } }} // This code is contributed by umadevi9616", "e": 41987, "s": 41102, "text": null }, { "code": "# This python program tells if there exists a pair in array whose sum results in x. # Function to find and print pairdef chkPair(A, size, x): for i in range(0, size - 1): for j in range(i + 1, size): if (A[i] + A[j] == x): print(f\"Pair with a given sum {x} is ({A[i]},{A[j]})\") return 1 return 0 if __name__ == \"__main__\": A = [0, -1, 2, -3, 1] x = -2 size = len(A) if (chkPair(A, size, x)): print(\"Valid pair exists\") else: print(f\"No valid pair exists for {x}\") # This code is contributed by rakeshsahni", "e": 42583, "s": 41987, "text": null }, { "code": "// C# program to check if there exists a pair// in array whose sum results in x.using System;class GFG{ // Function to find and print pair static bool chkPair(int [] A, int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { Console.WriteLine(\"Pair with a given sum \" + x + \" is (\" + A[i] + \", \" + A[j] + \")\"); return true; } } } return false; } public static void Main() { int [] A = {0, -1, 2, -3, 1}; int x = -2; int size = A.Length; if (chkPair(A, size, x)) { Console.WriteLine(\"Valid pair exists\"); } else { Console.WriteLine(\"No valid pair exists for \" + x ); } }} // This code is contributed by Samim Hossain Mondal.", "e": 43469, "s": 42583, "text": null }, { "code": "<script> // Javascript program to check if there exists a pair// in array whose sum results in x. // Function to find and print pair function chkPair(A , size , x) { for (i = 0; i < (size - 1); i++) { for (j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { document.write(\"Pair with a given sum \" + x + \" is (\" + A[i] + \", \" + A[j] + \")\"); return true; } } } return false; } let A = [ 0, -1, 2, -3, 1 ]; let x = -2; let size = A.length; if (chkPair(A, size, x)) { document.write(\"<br/>Valid pair exists\"); } else { document.write(\"<br/>No valid pair exists for \" + x); } // This code is contributed by Samim Hossain Mondal.</script>", "e": 44309, "s": 43469, "text": null }, { "code": "package mainimport (\"fmt\") func twoSum(nums [5]int, target int) { var flag bool = false result:=make([]int,2) for i:=0;i<len(nums)-1;i++{ for j:=i+1;j<len(nums);j++{ if nums[i]+nums[j]==target{ result[0]=nums[i] result[1]=nums[j] flag = true; } } } if(flag == false){ fmt.Println(\"No valid pair exists for \" , target) }else { fmt.Printf( \"Pair with a given sum \" , target , \" is (\" , result[0], \", \" , result[1] , \")\") } } func main() { arr2 := [5]int{0, -1, 2, -3, 1} var x int = -2 twoSum(arr2, x)}// This code is contributed by NITUGAUR", "e": 44979, "s": 44309, "text": null }, { "code": null, "e": 45033, "s": 44979, "text": "Pair with a given sum -2 is (-3, 1)\nValid pair exists" }, { "code": null, "e": 45077, "s": 45033, "text": "Time Complexity: O(n2)Auxiliary Space: O(1)" }, { "code": null, "e": 45123, "s": 45077, "text": "Method 1: Sorting and Two-Pointers technique." }, { "code": null, "e": 45672, "s": 45123, "text": "Approach: A tricky approach to solve this problem can be to use the two-pointer technique. But for using two pointer technique, the array must be sorted. Once the array is sorted the two pointers can be taken which mark the beginning and end of the array respectively. If the sum is greater than the sum of those two elements, shift the right pointer to decrease the value of the required sum and if the sum is lesser than the required value, shift the left pointer to increase the value of the required sum. Let’s understand this using an example." }, { "code": null, "e": 46400, "s": 45672, "text": "Let an array be {1, 4, 45, 6, 10, -8} and sum to find be 16After sorting the array A = {-8, 1, 4, 6, 10, 45}Now, increment ‘l’ when the sum of the pair is less than the required sum and decrement ‘r’ when the sum of the pair is more than the required sum. This is because when the sum is less than the required sum then to get the number which could increase the sum of pair, start moving from left to right(also sort the array) thus “l++” and vice versa.Initialize l = 0, r = 5 A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 4 A[l] + A[r] ( -8 + 10) increment l. Now l = 1 A[l] + A[r] ( 1 + 10) increment l. Now l = 2 A[l] + A[r] ( 4 + 10) increment l. Now l = 3 A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1)" }, { "code": null, "e": 46537, "s": 46400, "text": "Note: If there is more than one pair having the given sum then this algorithm reports only one. Can be easily extended for this though. " }, { "code": null, "e": 46549, "s": 46537, "text": "Algorithm: " }, { "code": null, "e": 46952, "s": 46549, "text": "hasArrayTwoCandidates (A[], ar_size, sum)Sort the array in non-decreasing order.Initialize two index variables to find the candidate elements in the sorted array. Initialize first to the leftmost index: l = 0Initialize second the rightmost index: r = ar_size-1Loop while l < r. If (A[l] + A[r] == sum) then return 1Else if( A[l] + A[r] < sum ) then l++Else r–No candidates in the whole array – return 0" }, { "code": null, "e": 46994, "s": 46952, "text": "hasArrayTwoCandidates (A[], ar_size, sum)" }, { "code": null, "e": 47034, "s": 46994, "text": "Sort the array in non-decreasing order." }, { "code": null, "e": 47215, "s": 47034, "text": "Initialize two index variables to find the candidate elements in the sorted array. Initialize first to the leftmost index: l = 0Initialize second the rightmost index: r = ar_size-1" }, { "code": null, "e": 47313, "s": 47215, "text": "Initialize first to the leftmost index: l = 0Initialize second the rightmost index: r = ar_size-1" }, { "code": null, "e": 47359, "s": 47313, "text": "Initialize first to the leftmost index: l = 0" }, { "code": null, "e": 47412, "s": 47359, "text": "Initialize second the rightmost index: r = ar_size-1" }, { "code": null, "e": 47512, "s": 47412, "text": "Loop while l < r. If (A[l] + A[r] == sum) then return 1Else if( A[l] + A[r] < sum ) then l++Else r–" }, { "code": null, "e": 47594, "s": 47512, "text": "If (A[l] + A[r] == sum) then return 1Else if( A[l] + A[r] < sum ) then l++Else r–" }, { "code": null, "e": 47632, "s": 47594, "text": "If (A[l] + A[r] == sum) then return 1" }, { "code": null, "e": 47670, "s": 47632, "text": "Else if( A[l] + A[r] < sum ) then l++" }, { "code": null, "e": 47678, "s": 47670, "text": "Else r–" }, { "code": null, "e": 47722, "s": 47678, "text": "No candidates in the whole array – return 0" }, { "code": null, "e": 47773, "s": 47722, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 47777, "s": 47773, "text": "C++" }, { "code": null, "e": 47779, "s": 47777, "text": "C" }, { "code": null, "e": 47784, "s": 47779, "text": "Java" }, { "code": null, "e": 47791, "s": 47784, "text": "Python" }, { "code": null, "e": 47794, "s": 47791, "text": "C#" }, { "code": null, "e": 47798, "s": 47794, "text": "PHP" }, { "code": null, "e": 47809, "s": 47798, "text": "Javascript" }, { "code": "// C++ program to check if given array// has 2 elements whose sum is equal// to the given value #include <bits/stdc++.h>using namespace std; // Function to check if array has 2 elements// whose sum is equal to the given valuebool hasArrayTwoCandidates(int A[], int arr_size, int sum){ int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return 0;} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) cout << \"Array has two elements\" \" with given sum\"; else cout << \"Array doesn't have two\" \" elements with given sum\"; return 0;}", "e": 48877, "s": 47809, "text": null }, { "code": "// C program to check if given array// has 2 elements whose sum is equal// to the given value #include <stdio.h>#define bool int void quickSort(int*, int, int); bool hasArrayTwoCandidates( int A[], int arr_size, int sum){ int l, r; /* Sort the elements */ quickSort(A, 0, arr_size - 1); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return 0;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int A[], int si, int ei){ int x = A[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if (A[j] <= x) { i++; exchange(&A[i], &A[j]); } } exchange(&A[i + 1], &A[ei]); return (i + 1);} /* Implementation of Quick SortA[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int A[], int si, int ei){ int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); }} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = 6; if (hasArrayTwoCandidates(A, arr_size, n)) printf(\"Array has two elements with given sum\"); else printf(\"Array doesn't have two elements with given sum\"); getchar(); return 0;}", "e": 50510, "s": 48877, "text": null }, { "code": "// Java program to check if given array// has 2 elements whose sum is equal// to the given valueimport java.util.*; class GFG { // Function to check if array has 2 elements // whose sum is equal to the given value static boolean hasArrayTwoCandidates( int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ Arrays.sort(A); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return true; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return false; } // Driver code public static void main(String args[]) { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = A.length; // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) System.out.println(\"Array has two \" + \"elements with given sum\"); else System.out.println(\"Array doesn't have \" + \"two elements with given sum\"); }}", "e": 51720, "s": 50510, "text": null }, { "code": "# Python program to check for the sum# condition to be satisfied def hasArrayTwoCandidates(A, arr_size, sum): # sort the array quickSort(A, 0, arr_size-1) l = 0 r = arr_size-1 # traverse the array for the two elements while l<r: if (A[l] + A[r] == sum): return 1 elif (A[l] + A[r] < sum): l += 1 else: r -= 1 return 0 # Implementation of Quick Sort# A[] --> Array to be sorted# si --> Starting index# ei --> Ending indexdef quickSort(A, si, ei): if si < ei: pi = partition(A, si, ei) quickSort(A, si, pi-1) quickSort(A, pi + 1, ei) # Utility function for partitioning# the array(used in quick sort)def partition(A, si, ei): x = A[ei] i = (si-1) for j in range(si, ei): if A[j] <= x: i += 1 # This operation is used to swap # two variables is python A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return i + 1 # Driver program to test the functionsA = [1, 4, 45, 6, 10, -8]n = 16if (hasArrayTwoCandidates(A, len(A), n)): print(\"Array has two elements with the given sum\")else: print(\"Array doesn't have two elements with the given sum\") ## This code is contributed by __Devesh Agrawal__", "e": 53065, "s": 51720, "text": null }, { "code": "// C# program to check for pair// in A[] with sum as x using System; class GFG { static bool hasArrayTwoCandidates(int[] A, int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, 0, arr_size - 1); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return true; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return false; } /* Below functions are only to sort the array using QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { int pivot = arr[high]; // index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi - 1); sort(arr, pi + 1, high); } } // Driver code public static void Main() { int[] A = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = 6; if (hasArrayTwoCandidates(A, arr_size, n)) Console.Write(\"Array has two elements\" + \" with given sum\"); else Console.Write(\"Array doesn't have \" + \"two elements with given sum\"); }} // This code is contributed by Sam007", "e": 55621, "s": 53065, "text": null }, { "code": "<?php// PHP program to check if given// array has 2 elements whose sum// is equal to the given value // Function to check if array has// 2 elements whose sum is equal// to the given valuefunction hasArrayTwoCandidates($A, $arr_size, $sum){ $l; $r; /* Sort the elements */ //sort($A, A + arr_size); sort($A); /* Now look for the two candidates in the sorted array*/ $l = 0; $r = $arr_size - 1; while ($l < $r) { if($A[$l] + $A[$r] == $sum) return 1; else if($A[$l] + $A[$r] < $sum) $l++; else // A[i] + A[j] > sum $r--; } return 0;} // Driver Code$A = array (1, 4, 45, 6, 10, -8);$n = 16;$arr_size = sizeof($A); // Function callingif(hasArrayTwoCandidates($A, $arr_size, $n)) echo \"Array has two elements \" . \"with given sum\";else echo \"Array doesn't have two \" . \"elements with given sum\"; // This code is contributed by m_kit?>", "e": 56618, "s": 55621, "text": null }, { "code": "<script> // Javascript program to check if given array// has 2 elements whose sum is equal// to the given value // Function to check if array has 2 elements// whose sum is equal to the given valuefunction hasArrayTwoCandidates(A, arr_size, sum){ var l, r; /* Sort the elements */ A.sort(); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[i] + A[j] > sum r--; } return 0;} /* Driver program to test above function */var A = [ 1, 4, 45, 6, 10, -8 ]var n = 16;var arr_size = A.length;// Function callingif (hasArrayTwoCandidates(A, arr_size, n)) document.write(\"Array has two elements\" + \" with the given sum\");else document.write(\"Array doesn't have two\" + \" elements with the given sum\"); </script>", "e": 57557, "s": 56618, "text": null }, { "code": null, "e": 57595, "s": 57557, "text": "Array has two elements with given sum" }, { "code": null, "e": 57618, "s": 57595, "text": "Complexity Analysis: " }, { "code": null, "e": 57799, "s": 57618, "text": "Time Complexity: Depends on what sorting algorithm we use. If Merge Sort or Heap Sort is used then (-)(nlogn) in the worst case.If Quick Sort is used then O(n^2) in the worst case." }, { "code": null, "e": 57869, "s": 57799, "text": "If Merge Sort or Heap Sort is used then (-)(nlogn) in the worst case." }, { "code": null, "e": 57922, "s": 57869, "text": "If Quick Sort is used then O(n^2) in the worst case." }, { "code": null, "e": 58045, "s": 57922, "text": "Auxiliary Space: This too depends on sorting algorithm. The auxiliary space is O(n) for merge sort and O(1) for Heap Sort." }, { "code": null, "e": 58064, "s": 58045, "text": "Method 2: Hashing." }, { "code": null, "e": 58366, "s": 58064, "text": "Approach: This problem can be solved efficiently by using the technique of hashing. Use a hash_map to check for the current array value x(let), if there exists a value target_sum-x which on adding to the former gives target_sum. This can be done in constant time. Let’s look at the following example. " }, { "code": null, "e": 58779, "s": 58366, "text": "arr[] = {0, -1, 2, -3, 1} sum = -2 Now start traversing: Step 1: For ‘0’ there is no valid number ‘-2’ so store ‘0’ in hash_map. Step 2: For ‘-1’ there is no valid number ‘-1’ so store ‘-1’ in hash_map. Step 3: For ‘2’ there is no valid number ‘-4’ so store ‘2’ in hash_map. Step 4: For ‘-3’ there is no valid number ‘1’ so store ‘-3’ in hash_map. Step 5: For ‘1’ there is a valid number ‘-3’ so answer is 1, -3 " }, { "code": null, "e": 58792, "s": 58779, "text": "Algorithm: " }, { "code": null, "e": 58945, "s": 58792, "text": "Initialize an empty hash table s.Do following for each element A[i] in A[] If s[x – A[i]] is set then print the pair (A[i], x – A[i])Insert A[i] into s." }, { "code": null, "e": 58979, "s": 58945, "text": "Initialize an empty hash table s." }, { "code": null, "e": 59099, "s": 58979, "text": "Do following for each element A[i] in A[] If s[x – A[i]] is set then print the pair (A[i], x – A[i])Insert A[i] into s." }, { "code": null, "e": 59177, "s": 59099, "text": "If s[x – A[i]] is set then print the pair (A[i], x – A[i])Insert A[i] into s." }, { "code": null, "e": 59236, "s": 59177, "text": "If s[x – A[i]] is set then print the pair (A[i], x – A[i])" }, { "code": null, "e": 59256, "s": 59236, "text": "Insert A[i] into s." }, { "code": null, "e": 59272, "s": 59256, "text": "Pseudo Code : " }, { "code": null, "e": 59413, "s": 59272, "text": "unordered_set s\nfor(i=0 to end)\n if(s.find(target_sum - arr[i]) == s.end)\n insert(arr[i] into s)\n else \n print arr[i], target-arr[i]" }, { "code": null, "e": 59417, "s": 59413, "text": "C++" }, { "code": null, "e": 59419, "s": 59417, "text": "C" }, { "code": null, "e": 59424, "s": 59419, "text": "Java" }, { "code": null, "e": 59432, "s": 59424, "text": "Python3" }, { "code": null, "e": 59435, "s": 59432, "text": "C#" }, { "code": null, "e": 59446, "s": 59435, "text": "Javascript" }, { "code": "// C++ program to check if given array// has 2 elements whose sum is equal// to the given value#include <bits/stdc++.h> using namespace std; void printPairs(int arr[], int arr_size, int sum){ unordered_set<int> s; for (int i = 0; i < arr_size; i++) { int temp = sum - arr[i]; if (s.find(temp) != s.end()) cout << \"Pair with given sum \" << sum << \" is (\" << arr[i] << \",\" << temp << \")\" << endl; s.insert(arr[i]); }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0;}", "e": 60138, "s": 59446, "text": null }, { "code": "// C program to check if given array// has 2 elements whose sum is equal// to the given value // Works only if range elements is limited#include <stdio.h>#define MAX 100000 void printPairs(int arr[], int arr_size, int sum){ int i, temp; /*initialize hash set as 0*/ bool s[MAX] = { 0 }; for (i = 0; i < arr_size; i++) { temp = sum - arr[i]; if (s[temp] == 1) printf( \"Pair with given sum %d is (%d, %d) n\", sum, arr[i], temp); s[arr[i]] = 1; }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); printPairs(A, arr_size, n); getchar(); return 0;}", "e": 60851, "s": 60138, "text": null }, { "code": "// Java implementation using Hashingimport java.io.*;import java.util.HashSet; class PairSum { static void printpairs(int arr[], int sum) { HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < arr.length; ++i) { int temp = sum - arr[i]; // checking for condition if (s.contains(temp)) { System.out.println( \"Pair with given sum \" + sum + \" is (\" + arr[i] + \", \" + temp + \")\"); } s.add(arr[i]); } } // Driver Code public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; printpairs(A, n); }} // This article is contributed by Aakash Hasija", "e": 61631, "s": 60851, "text": null }, { "code": "# Python program to find if there are# two elements wtih given sum # function to check for the given sum# in the arraydef printPairs(arr, arr_size, sum): # Create an empty hash map # using an hashmap allows us to store the indices hashmap = {} for i in range(0, arr_size): temp = sum-arr[i] if (temp in hashmap): print (f'Pair with given sum {sum} is ({temp},{arr[i]}) at indices ({hashmap[temp]},{i})') hashmap[arr[i]] = i # driver codeA = [1, 4, 45, 6, 10, 8]n = 16printPairs(A, len(A), n) # This code will also work in case the array has the same number twice# and target is the sum of those numbers# Eg: Array = [4,6,4] Target = 8 # This code is contributed by __Achyut Upadhyay__", "e": 62370, "s": 61631, "text": null }, { "code": "// C# implementation using Hashingusing System;using System.Collections.Generic; class GFG { static void printpairs(int[] arr, int sum) { HashSet<int> s = new HashSet<int>(); for (int i = 0; i < arr.Length; ++i) { int temp = sum - arr[i]; // checking for condition if (s.Contains(temp)) { Console.Write(\"Pair with given sum \" + sum + \" is (\" + arr[i] + \", \" + temp + \")\"); } s.Add(arr[i]); } } // Driver Code static void Main() { int[] A = new int[] { 1, 4, 45, 6, 10, 8 }; int n = 16; printpairs(A, n); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 63142, "s": 62370, "text": null }, { "code": "<script> // JavaScript program to check if given array// has 2 elements whose sum is equal// to the given value // Javascript implementation using Hashing function printpairs(arr, sum) { let s = new Set(); for (let i = 0; i < arr.length; ++i) { let temp = sum - arr[i]; // checking for condition if (s.has(temp)) { document.write( \"Pair with given sum \" + sum + \" is (\" + arr[i] + \", \" + temp + \")\"); } s.add(arr[i]); } } // Driver Code let A = [ 1, 4, 45, 6, 10, 8 ]; let n = 16; printpairs(A, n); </script>", "e": 63840, "s": 63142, "text": null }, { "code": null, "e": 63873, "s": 63840, "text": "Pair with given sum 16 is (10,6)" }, { "code": null, "e": 63896, "s": 63873, "text": "Complexity Analysis: " }, { "code": null, "e": 63975, "s": 63896, "text": "Time Complexity: O(n). As the whole array is needed to be traversed only once." }, { "code": null, "e": 64048, "s": 63975, "text": "Auxiliary Space: O(n). A hash map has been used to store array elements." }, { "code": null, "e": 64243, "s": 64048, "text": "Note: The solution will work even if the range of numbers includes negative numbers + if the pair is formed by numbers recurring twice in array eg: array = [3,4,3]; pair = (3,3); target sum = 6." }, { "code": null, "e": 64300, "s": 64243, "text": "Method 3: Using remainders of the elements less than x. " }, { "code": null, "e": 65088, "s": 64300, "text": "Approach: The idea is to count the elements with remainders when divided by x, i.e 0 to x-1, each remainder separately. Suppose we have x as 6, then the numbers which are less than 6 and have remainders which add up to 6 gives sum as 6 when added. For example, we have elements, 2,4 in the array and 2%6 = 2 and 4%6 =4, and these remainders add up to give 6. Like that we have to check for pairs with remainders (1,5),(2,4),(3,3). if we have one or more elements with remainder 1 and one or more elements with remainder 5, then surely we get a sum as 6. Here we do not consider (0,6) as the elements for the resultant pair should be less than 6. when it comes to (3,3) we have to check if we have two elements with remainder 3, then we can say that “There exists a pair whose sum is x”. " }, { "code": null, "e": 65101, "s": 65088, "text": "Algorithm: " }, { "code": null, "e": 65134, "s": 65101, "text": "1. Create an array with size x. " }, { "code": null, "e": 65174, "s": 65134, "text": "2. Initialize all rem elements to zero." }, { "code": null, "e": 65202, "s": 65174, "text": "3. Traverse the given array" }, { "code": null, "e": 65387, "s": 65202, "text": "Do the following if arr[i] is less than x:r=arr[i]%x which is done to get the remainder.rem[r]=rem[r]+1 i.e. increasing the count of elements that have remainder r when divided with x." }, { "code": null, "e": 65434, "s": 65387, "text": "r=arr[i]%x which is done to get the remainder." }, { "code": null, "e": 65531, "s": 65434, "text": "rem[r]=rem[r]+1 i.e. increasing the count of elements that have remainder r when divided with x." }, { "code": null, "e": 65580, "s": 65531, "text": "4. Now, traverse the rem array from 1 to x/2. " }, { "code": null, "e": 65713, "s": 65580, "text": "If(rem[i]> 0 and rem[x-i]>0) then print “YES” and come out of the loop. This means that we have a pair that results in x upon doing." }, { "code": null, "e": 65762, "s": 65713, "text": "5. Now when we reach at x/2 in the above loop " }, { "code": null, "e": 65889, "s": 65762, "text": "If x is even, for getting a pair we should have two elements with remainder x/2.If rem[x/2]>1 then print “YES” else print “NO”" }, { "code": null, "e": 65936, "s": 65889, "text": "If rem[x/2]>1 then print “YES” else print “NO”" }, { "code": null, "e": 66084, "s": 65936, "text": "If it is not satisfied that is x is odd, it will have a separate pair with x-x/2.If rem[x/2]>1 and rem[x-x/2]>1 , then print “Yes” else, print”No”;" }, { "code": null, "e": 66151, "s": 66084, "text": "If rem[x/2]>1 and rem[x-x/2]>1 , then print “Yes” else, print”No”;" }, { "code": null, "e": 66191, "s": 66151, "text": "Implementation of the above algorithm: " }, { "code": null, "e": 66195, "s": 66191, "text": "C++" }, { "code": null, "e": 66197, "s": 66195, "text": "C" }, { "code": null, "e": 66202, "s": 66197, "text": "Java" }, { "code": null, "e": 66210, "s": 66202, "text": "Python3" }, { "code": null, "e": 66213, "s": 66210, "text": "C#" }, { "code": null, "e": 66224, "s": 66213, "text": "Javascript" }, { "code": "// Code in cpp to tell if there exists a pair in array whose// sum results in x.#include <iostream>using namespace std; // Function to print pairsvoid printPairs(int a[], int n, int x){ int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. cout << \"Yes\\n\"; break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print \"No\". if (rem[x / 2] > 1) cout << \"Yes\\n\"; else cout << \"No\\n\"; } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) cout << \"Yes\\n\"; else cout << \"No\\n\"; } }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 68175, "s": 66224, "text": null }, { "code": "// Code in c to tell if there exists a pair in array whose// sum results in x.#include <stdio.h> // Function to print pairsvoid printPairs(int a[], int n, int x){ int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. printf(\"Yes\\n\"); break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print \"No\". if (rem[x / 2] > 1) printf(\"Yes\\n\"); else printf(\"No\\n\"); } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) printf(\"Yes\\n\"); else printf(\"No\\n\"); } }} /* Driver Code */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 70103, "s": 68175, "text": null }, { "code": "// Code in Java to tell if there exists a pair in array// whose sum results in x.import java.util.*; class GFG { // Function to print pairs static void printPairs(int a[], int n, int x) { int i; int[] rem = new int[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if // the element is x, as numbers greater than // x can't be used to get a sum x. Updating // the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to // middle to find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i // will result to a sum of x. Once we get // two elements which add up to x , we print // x and break. System.out.println(\"Yes\"); break; } } // Once we reach middle of remainder array, we have // to do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 // elements with remainder x/2, then we // will have two distinct elements which // add up to x. if we dont have more // than 1 element, print \"No\". if (rem[x / 2] > 1) System.out.println(\"Yes\"); else System.out.println(\"No\"); } else { // When x is odd we continue the same // process which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) System.out.println(\"Yes\"); else System.out.println(\"No\"); } } } /* Driver Code */ public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = A.length; // Function calling printPairs(A, arr_size, n); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 72376, "s": 70103, "text": null }, { "code": "# Code in Python3 to tell if there# exists a pair in array whose# sum results in x. # Function to print pairsdef printPairs(a, n, x): rem = [] for i in range(x): # Initializing the rem # values with 0's. rem.append(0) for i in range(n): if (a[i] < x): # Perform the remainder operation # only if the element is x, as # numbers greater than x can't # be used to get a sum x.Updating # the count of remainders. rem[a[i] % x] += 1 # Traversing the remainder list from # start to middle to find pairs for i in range(1, x // 2): if (rem[i] > 0 and rem[x - i] > 0): # The elements with remainders # i and x-i will result to a # sum of x. Once we get two # elements which add up to x, # we print x and break. print(\"Yes\") break # Once we reach middle of # remainder array, we have to # do operations based on x. if (i >= x // 2): if (x % 2 == 0): if (rem[x // 2] > 1): # If x is even and we have more # than 1 elements with remainder # x/2, then we will have two # distinct elements which add up # to x. if we dont have than 1 # element, print \"No\". print(\"Yes\") else: print(\"No\") else: # When x is odd we continue # the same process which we # did in previous loop. if (rem[x // 2] > 0 and rem[x - x // 2] > 0): print(\"Yes\") else: print(\"No\") # Driver CodeA = [ 1, 4, 45, 6, 10, 8 ]n = 16arr_size = len(A) # Function callingprintPairs(A, arr_size, n) # This code is contributed by subhammahato348", "e": 74249, "s": 72376, "text": null }, { "code": "// C# Code in C# to tell if there// exists a pair in array whose// sum results in x.using System;class GFG{ // Function to print pairsstatic void printPairs(int []a, int n, int x){ int i; int []rem = new int[x]; for (i = 0; i < x; i++) { // initializing the rem // values with 0's. rem[i] = 0; } for (i = 0; i < n; i++) { if (a[i] < x) { // Perform the remainder // operation only if the // element is x, as numbers // greater than x can't // be used to get a sum x. // Updating the count of remainders. rem[a[i] % x]++; } } // Traversing the remainder list // from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders // i and x-i will // result to a sum of x. // Once we get two // elements which add up to x , // we print x and // break. Console.Write(\"Yes\" + \"\\n\"); break; } } // Once we reach middle of // remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { if (rem[x / 2] > 1) { // if x is even and // we have more than 1 // elements with remainder // x/2, then we will // have two distinct elements // which add up // to x. if we dont have //more than 1 // element, print \"No\". Console.Write(\"Yes\" + \"\\n\"); } else { Console.Write(\"No\" + \"\\n\"); } } else { // When x is odd we continue // the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) { Console.Write(\"Yes\" + \"\\n\"); } else { Console.WriteLine(\"No\" + \"\\n\"); } } }} /* Driver Code */public static void Main(string[] args){ int[] A = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = A.Length; // Function calling printPairs(A, arr_size, n);}} // This code is contributed by SoumikMondal", "e": 76377, "s": 74249, "text": null }, { "code": "<script> // Code in Javascript to tell if there// exists a pair in array whose// sum results in x. // Function to print pairsfunction printPairs(a, n, x){ let i; let rem = new Array(x); for(i = 0; i < x; i++) { // Initializing the rem // values with 0's. rem[i] = 0; } for(i = 0; i < n; i++) { if (a[i] < x) { // Perform the remainder // operation only if the // element is x, as numbers // greater than x can't // be used to get a sum x. // Updating the count of remainders. rem[a[i] % x]++; } } // Traversing the remainder list // from start to middle to // find pairs for(i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders // i and x-i will // result to a sum of x. // Once we get two // elements which add up to x , // we print x and // break. document.write(\"Yes\" + \"</br>\"); break; } } // Once we reach middle of // remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { if (rem[x / 2] > 1) { // If x is even and // we have more than 1 // elements with remainder // x/2, then we will // have two distinct elements // which add up // to x. if we dont have //more than 1 // element, print \"No\". document.write(\"Yes\" + \"</br>\"); } else { document.write(\"No\" + \"</br>\"); } } else { // When x is odd we continue // the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) { document.write(\"Yes\" + \"</br>\"); } else { document.write(\"No\" + \"</br>\"); } } }} // Driver code let A = [ 1, 4, 45, 6, 10, 8 ];let n = 16;let arr_size = A.length; // Function callingprintPairs(A, arr_size, n); // This code is contributed by suresh07 </script>", "e": 78807, "s": 76377, "text": null }, { "code": null, "e": 78811, "s": 78807, "text": "Yes" }, { "code": null, "e": 78856, "s": 78811, "text": "Time Complexity: O(n+x)Auxiliary Space: O(x)" }, { "code": null, "e": 79066, "s": 78856, "text": "Similarly, the indices of a pair that add up to a given sum can also be calculated by an unordered map. The only change here is that we also have to store indices of elements as values for each element as key." }, { "code": null, "e": 79072, "s": 79066, "text": "C++14" }, { "code": null, "e": 79080, "s": 79072, "text": "Python3" }, { "code": null, "e": 79091, "s": 79080, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; pair<int,int> findSum(int *arr,int& n,int& target){ int i,findElement; unordered_map<int,int>mp; pair<int,int>result; for(i=0;i<n;i++) { findElement=target-arr[i]; if(mp[findElement]) { result.first=i-1; result.second=mp[findElement]-1; break; } else mp.insert({arr[i],i}); } return result;} int main(){ int arr[]={1,5,4,3,7,9,2}; int n=sizeof(arr)/sizeof(arr[0]); int search=7; pair<int,int>ans=findSum(arr,n,search); cout<<min(ans.first,ans.second)<<\" \"<<max(ans.first,ans.second); return 0;}", "e": 79736, "s": 79091, "text": null }, { "code": "def findSum(arr, n, target): mp = {} result = [0]*2 for i in range(n): findElement = target-arr[i] if(findElement in mp): result[0] = i - 1 result[1] = mp[findElement] - 1 break else: mp[arr[i]] = i return result # driver codearr = [1,5,4,3,7,9,2]n = len(arr)search = 7ans = findSum(arr,n,search)print(f\"{min(ans[0], ans[1])} {max(ans[0], ans[1])}\") # This code is contributed by shinjanpatra", "e": 80209, "s": 79736, "text": null }, { "code": "<script>function findSum(arr,n,target){ let i,findElement; let mp = new Map(); let result = []; for(i = 0; i < n; i++) { findElement = target-arr[i]; if(mp.has(findElement)) { result[0] = i - 1; result[1] = mp.get(findElement) - 1; break; } else mp.set(arr[i],i); } return result;} // driver code let arr = [1,5,4,3,7,9,2];let n = arr.length;let search = 7;let ans = findSum(arr,n,search);document.write(Math.min(ans[0], ans[1]) + \" \" +Math.max(ans[0], ans[1])); // This code is contributed by shinjanpatra </script>", "e": 80815, "s": 80209, "text": null }, { "code": null, "e": 80819, "s": 80815, "text": "1 2" }, { "code": null, "e": 80862, "s": 80819, "text": "Time Complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 80882, "s": 80862, "text": "Related Problems: " }, { "code": null, "e": 80939, "s": 80882, "text": "Given two unsorted arrays, find all pairs whose sum is x" }, { "code": null, "e": 80966, "s": 80939, "text": "Count pairs with given sum" }, { "code": null, "e": 81018, "s": 80966, "text": "Count all distinct pairs with difference equal to k" }, { "code": null, "e": 81888, "s": 81018, "text": "YouTubeGeeksforGeeks507K subscribersGiven an array A[] and a number x, check for pair in A[] with sum as x | GeeksforGeeksWatch 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:000:00 / 10:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=I7Nz1XzzPYc\" 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": 82014, "s": 81888, "text": "Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 82020, "s": 82014, "text": "jit_t" }, { "code": null, "e": 82032, "s": 82020, "text": "manishshaw1" }, { "code": null, "e": 82047, "s": 82032, "text": "Mayuri Gupta 4" }, { "code": null, "e": 82059, "s": 82047, "text": "hellokoding" }, { "code": null, "e": 82071, "s": 82059, "text": "salonitayal" }, { "code": null, "e": 82083, "s": 82071, "text": "bidibaaz123" }, { "code": null, "e": 82099, "s": 82083, "text": "SaiSanjanaGudla" }, { "code": null, "e": 82109, "s": 82099, "text": "idkravitz" }, { "code": null, "e": 82121, "s": 82109, "text": "aashish1995" }, { "code": null, "e": 82134, "s": 82121, "text": "SoumikMondal" }, { "code": null, "e": 82150, "s": 82134, "text": "subhammahato348" }, { "code": null, "e": 82160, "s": 82150, "text": "shrey3108" }, { "code": null, "e": 82169, "s": 82160, "text": "suresh07" }, { "code": null, "e": 82176, "s": 82169, "text": "rrrtnx" }, { "code": null, "e": 82188, "s": 82176, "text": "sg275527109" }, { "code": null, "e": 82198, "s": 82188, "text": "sanjoy_62" }, { "code": null, "e": 82214, "s": 82198, "text": "rajeev0719singh" }, { "code": null, "e": 82227, "s": 82214, "text": "mdtauseef123" }, { "code": null, "e": 82238, "s": 82227, "text": "mkumar2789" }, { "code": null, "e": 82248, "s": 82238, "text": "AR_Gaurav" }, { "code": null, "e": 82260, "s": 82248, "text": "umadevi9616" }, { "code": null, "e": 82272, "s": 82260, "text": "rakeshsahni" }, { "code": null, "e": 82289, "s": 82272, "text": "surinderdawra388" }, { "code": null, "e": 82299, "s": 82289, "text": "samim2000" }, { "code": null, "e": 82309, "s": 82299, "text": "kk9826225" }, { "code": null, "e": 82350, "s": 82309, "text": "bml8ngqtq8nb1h971tf2wo5m68l4m0nmykp8nxmq" }, { "code": null, "e": 82362, "s": 82350, "text": "prophet1999" }, { "code": null, "e": 82375, "s": 82362, "text": "shinjanpatra" }, { "code": null, "e": 82384, "s": 82375, "text": "NITUGAUR" }, { "code": null, "e": 82401, "s": 82384, "text": "harendrakumar123" }, { "code": null, "e": 82415, "s": 82401, "text": "avtarkumar719" }, { "code": null, "e": 82433, "s": 82415, "text": "germanshephered48" }, { "code": null, "e": 82448, "s": 82433, "text": "adityakumar129" }, { "code": null, "e": 82453, "s": 82448, "text": "ABCO" }, { "code": null, "e": 82462, "s": 82453, "text": "Accolite" }, { "code": null, "e": 82469, "s": 82462, "text": "Amazon" }, { "code": null, "e": 82485, "s": 82469, "text": "Amazon-Question" }, { "code": null, "e": 82493, "s": 82485, "text": "CarWale" }, { "code": null, "e": 82510, "s": 82493, "text": "CarWale-Question" }, { "code": null, "e": 82518, "s": 82510, "text": "FactSet" }, { "code": null, "e": 82527, "s": 82518, "text": "Flipkart" }, { "code": null, "e": 82532, "s": 82527, "text": "Hike" }, { "code": null, "e": 82540, "s": 82532, "text": "Infosys" }, { "code": null, "e": 82550, "s": 82540, "text": "Microsoft" }, { "code": null, "e": 82565, "s": 82550, "text": "Morgan Stanley" }, { "code": null, "e": 82574, "s": 82565, "text": "SAP Labs" }, { "code": null, "e": 82580, "s": 82574, "text": "Wipro" }, { "code": null, "e": 82585, "s": 82580, "text": "Zoho" }, { "code": null, "e": 82592, "s": 82585, "text": "Arrays" }, { "code": null, "e": 82605, "s": 82592, "text": "Backtracking" }, { "code": null, "e": 82610, "s": 82605, "text": "Hash" }, { "code": null, "e": 82620, "s": 82610, "text": "Recursion" }, { "code": null, "e": 82628, "s": 82620, "text": "Infosys" }, { "code": null, "e": 82633, "s": 82628, "text": "Zoho" }, { "code": null, "e": 82642, "s": 82633, "text": "Flipkart" }, { "code": null, "e": 82657, "s": 82642, "text": "Morgan Stanley" }, { "code": null, "e": 82666, "s": 82657, "text": "Accolite" }, { "code": null, "e": 82673, "s": 82666, "text": "Amazon" }, { "code": null, "e": 82683, "s": 82673, "text": "Microsoft" }, { "code": null, "e": 82691, "s": 82683, "text": "FactSet" }, { "code": null, "e": 82696, "s": 82691, "text": "Hike" }, { "code": null, "e": 82701, "s": 82696, "text": "ABCO" }, { "code": null, "e": 82707, "s": 82701, "text": "Wipro" }, { "code": null, "e": 82716, "s": 82707, "text": "SAP Labs" }, { "code": null, "e": 82724, "s": 82716, "text": "CarWale" }, { "code": null, "e": 82731, "s": 82724, "text": "Arrays" }, { "code": null, "e": 82736, "s": 82731, "text": "Hash" }, { "code": null, "e": 82746, "s": 82736, "text": "Recursion" }, { "code": null, "e": 82759, "s": 82746, "text": "Backtracking" }, { "code": null, "e": 82857, "s": 82759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 82925, "s": 82857, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 82957, "s": 82925, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 83001, "s": 82957, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 83033, "s": 83001, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 83047, "s": 83033, "text": "Linear Search" }, { "code": null, "e": 83080, "s": 83047, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 83140, "s": 83080, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 83168, "s": 83140, "text": "Backtracking | Introduction" }, { "code": null, "e": 83199, "s": 83168, "text": "Rat in a Maze | Backtracking-2" } ]
Aptitude | JavaScript Course Quiz 3 | Question 10 - GeeksforGeeks
10 May, 2019 What will be the output of the following code? <script> document.write(NaN == NaN);</script> (A) true(B) false(C) 1(D) 0Answer: (B)Explanation: Equality operator (== and ===) cannot be used to test a value against NaN. Use Number.isNaN() or isNaN() instead.Hence, it is not equal.Quiz of this Question Aptitude Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Aptitude | Wipro Mock Test | Question 3 C | C Quiz - 113 | Question 1 Aptitude | Wipro Mock Test | Question 1 Aptitude | Wipro Mock Test | Question 2 Aptitude | Wipro Mock Test | Question 4 Aptitude | Wipro Mock Test | Question 5 Aptitude | Wipro Mock Test | Question 6 Aptitude | Wipro Mock Test | Question 7 Aptitude | Wipro Mock Test | Question 8 Aptitude | Wipro Mock Test | Question 9
[ { "code": null, "e": 26013, "s": 25985, "text": "\n10 May, 2019" }, { "code": null, "e": 26060, "s": 26013, "text": "What will be the output of the following code?" }, { "code": "<script> document.write(NaN == NaN);</script>", "e": 26106, "s": 26060, "text": null }, { "code": null, "e": 26315, "s": 26106, "text": "(A) true(B) false(C) 1(D) 0Answer: (B)Explanation: Equality operator (== and ===) cannot be used to test a value against NaN. Use Number.isNaN() or isNaN() instead.Hence, it is not equal.Quiz of this Question" }, { "code": null, "e": 26324, "s": 26315, "text": "Aptitude" }, { "code": null, "e": 26422, "s": 26324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26462, "s": 26422, "text": "Aptitude | Wipro Mock Test | Question 3" }, { "code": null, "e": 26492, "s": 26462, "text": "C | C Quiz - 113 | Question 1" }, { "code": null, "e": 26532, "s": 26492, "text": "Aptitude | Wipro Mock Test | Question 1" }, { "code": null, "e": 26572, "s": 26532, "text": "Aptitude | Wipro Mock Test | Question 2" }, { "code": null, "e": 26612, "s": 26572, "text": "Aptitude | Wipro Mock Test | Question 4" }, { "code": null, "e": 26652, "s": 26612, "text": "Aptitude | Wipro Mock Test | Question 5" }, { "code": null, "e": 26692, "s": 26652, "text": "Aptitude | Wipro Mock Test | Question 6" }, { "code": null, "e": 26732, "s": 26692, "text": "Aptitude | Wipro Mock Test | Question 7" }, { "code": null, "e": 26772, "s": 26732, "text": "Aptitude | Wipro Mock Test | Question 8" } ]
Distance of chord from center when distance between center and another equal length chord is given - GeeksforGeeks
09 Mar, 2021 Given two equal length chords of a circle and Distance between the centre and one chord. The task is here to find the distance between the centre and the other chord. Examples: Input: 48 Output: 48 Input: 82 Output: 82 Below is the implementation of the above approach:Approach: Let AB & CD be the two equal chords of the circle having center at O.OM be the given distance of the chord AB from center. now in triangle AOM and CON, OA = OC (radii of same circle) MA = CN (since OM and ON are the perpendicular to the chord and it bisects the chord and AM = MB & CN = CD) angle AMO = angle ONC = 90 degrees so the triangles are congruent so, OM = ON Equal chords of a circle are equidistant from the centre of a circle. Below is the implementation of the above approach: C++ Java Python 3 C# Javascript // C++ program to find the distance of chord// from center when distance between center// and another equal length chord is given #include <bits/stdc++.h>using namespace std; void lengequichord(int z){ cout << "The distance between the " << "chord and the center is " << z << endl;} // Driver codeint main(){ int z = 48; lengequichord(z); return 0;} // Java program to find the distance of chord// from center when distance between center// and another equal length chord is given/ import java.io.*; class GFG{ static void lengequichord(int z){ System.out.println ("The distance between the "+ "chord and the center is "+ z );} // Driver codepublic static void main (String[] args){ int z = 48; lengequichord(z);}} // This code is contributed by jit_t. # Python 3 program to find the distance of chord# from center when distance between center# and another equal length chord is given def lengequichord(z): print("The distance between the" , "chord and the center is" , z ) # Driver codeif __name__ == "__main__": z = 48 lengequichord(z) # This code is contributed# by ChitraNayal // C# program to find the distance of chord// from center when distance between center// and another equal length chord is givenusing System; class GFG{ static void lengequichord(int z) { Console.WriteLine("The distance between the "+ "chord and the center is "+ z ); } // Driver code public static void Main () { int z = 48; lengequichord(z); }} // This code is contributed by AnkitRai01 <script> // JavaScript program to find the distance of chord// from center when distance between center// and another equal length chord is given function lengequichord(z){ document.write("The distance between the " + "chord and the center is " + z + "<br>");} // Driver code let z = 48; lengequichord(z); // This code is contributed by Surbhi Tyagi. </script> The distance between the chord and the center is 48 jit_t ankthon ukasp surbhityagi15 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Program to find line passing through 2 Points Equation of circle when three points on the circle are given Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26561, "s": 26533, "text": "\n09 Mar, 2021" }, { "code": null, "e": 26740, "s": 26561, "text": "Given two equal length chords of a circle and Distance between the centre and one chord. The task is here to find the distance between the centre and the other chord. Examples: " }, { "code": null, "e": 26784, "s": 26740, "text": "Input: 48\nOutput: 48\n\n\nInput: 82\nOutput: 82" }, { "code": null, "e": 27216, "s": 26786, "text": "Below is the implementation of the above approach:Approach: Let AB & CD be the two equal chords of the circle having center at O.OM be the given distance of the chord AB from center. now in triangle AOM and CON, OA = OC (radii of same circle) MA = CN (since OM and ON are the perpendicular to the chord and it bisects the chord and AM = MB & CN = CD) angle AMO = angle ONC = 90 degrees so the triangles are congruent so, OM = ON " }, { "code": null, "e": 27286, "s": 27216, "text": "Equal chords of a circle are equidistant from the centre of a circle." }, { "code": null, "e": 27338, "s": 27286, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27342, "s": 27338, "text": "C++" }, { "code": null, "e": 27347, "s": 27342, "text": "Java" }, { "code": null, "e": 27356, "s": 27347, "text": "Python 3" }, { "code": null, "e": 27359, "s": 27356, "text": "C#" }, { "code": null, "e": 27370, "s": 27359, "text": "Javascript" }, { "code": "// C++ program to find the distance of chord// from center when distance between center// and another equal length chord is given #include <bits/stdc++.h>using namespace std; void lengequichord(int z){ cout << \"The distance between the \" << \"chord and the center is \" << z << endl;} // Driver codeint main(){ int z = 48; lengequichord(z); return 0;}", "e": 27748, "s": 27370, "text": null }, { "code": "// Java program to find the distance of chord// from center when distance between center// and another equal length chord is given/ import java.io.*; class GFG{ static void lengequichord(int z){ System.out.println (\"The distance between the \"+ \"chord and the center is \"+ z );} // Driver codepublic static void main (String[] args){ int z = 48; lengequichord(z);}} // This code is contributed by jit_t.", "e": 28168, "s": 27748, "text": null }, { "code": "# Python 3 program to find the distance of chord# from center when distance between center# and another equal length chord is given def lengequichord(z): print(\"The distance between the\" , \"chord and the center is\" , z ) # Driver codeif __name__ == \"__main__\": z = 48 lengequichord(z) # This code is contributed# by ChitraNayal", "e": 28514, "s": 28168, "text": null }, { "code": "// C# program to find the distance of chord// from center when distance between center// and another equal length chord is givenusing System; class GFG{ static void lengequichord(int z) { Console.WriteLine(\"The distance between the \"+ \"chord and the center is \"+ z ); } // Driver code public static void Main () { int z = 48; lengequichord(z); }} // This code is contributed by AnkitRai01", "e": 28967, "s": 28514, "text": null }, { "code": "<script> // JavaScript program to find the distance of chord// from center when distance between center// and another equal length chord is given function lengequichord(z){ document.write(\"The distance between the \" + \"chord and the center is \" + z + \"<br>\");} // Driver code let z = 48; lengequichord(z); // This code is contributed by Surbhi Tyagi. </script>", "e": 29351, "s": 28967, "text": null }, { "code": null, "e": 29403, "s": 29351, "text": "The distance between the chord and the center is 48" }, { "code": null, "e": 29411, "s": 29405, "text": "jit_t" }, { "code": null, "e": 29419, "s": 29411, "text": "ankthon" }, { "code": null, "e": 29425, "s": 29419, "text": "ukasp" }, { "code": null, "e": 29439, "s": 29425, "text": "surbhityagi15" }, { "code": null, "e": 29449, "s": 29439, "text": "Geometric" }, { "code": null, "e": 29462, "s": 29449, "text": "Mathematical" }, { "code": null, "e": 29475, "s": 29462, "text": "Mathematical" }, { "code": null, "e": 29485, "s": 29475, "text": "Geometric" }, { "code": null, "e": 29583, "s": 29485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29649, "s": 29583, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 29681, "s": 29649, "text": "Program to find slope of a line" }, { "code": null, "e": 29727, "s": 29681, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 29788, "s": 29727, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 29858, "s": 29788, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 29888, "s": 29858, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29948, "s": 29888, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29991, "s": 29948, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 30006, "s": 29991, "text": "C++ Data Types" } ]
4 Dimensional Array in C/C++ - GeeksforGeeks
18 Feb, 2022 Prerequisite :Array in C/C++, More on array A four-dimensional (4D) array is an array of array of arrays of arrays or in other words 4D array is a array of 3D array.More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding arrays. Declaration of a Multidimensional Array in C:Syntax: data_type array_name[i1][i2][i3][i4].........[in]; where each i is a dimension, and in is the size of final dimension. Examples:1. int student[4][5][6][7];int designates the array type integer.student is the name of our 4D array.Our array can hold 840 integer-type elements. This number is reached by multiplying the value of each dimension. In this case: 4x5x6x7=840. 2. float country[5][6][5][6][5];Array country is a five-dimensional array.It can hold 4500 floating-point elements (5x6x5x6x5=4500). Program : // C Program to input 4D Matrix and print it.#include <stdio.h>int main(){ // variable declaration used for indexes int i, j, k, l, size; // Array declaration int a[2][2][2][2]; // size of array size = 2; // elements input a[0][0][0][0] = 5; a[0][0][0][1] = 3; a[0][0][1][0] = 5; a[0][0][1][1] = 3; a[0][1][0][0] = 6; a[0][1][0][1] = 7; a[0][1][1][0] = 6; a[0][1][1][1] = 7; a[1][0][0][0] = 8; a[1][0][0][1] = 9; a[1][0][1][0] = 8; a[1][0][1][1] = 9; a[1][1][0][0] = 9; a[1][1][0][1] = 7; a[1][1][1][0] = 9; a[1][1][1][1] = 7; // Printing the values for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { for (k = 0; k < size; k++) { for (l = 0; l < size; l++) { printf("Value of a[%d][%d][%d][%d] :- %d ", i, j, k, l, a[i][j][k][l]); printf("\n"); } } } } return 0;} Value of a[0][0][0][0] :- 5 Value of a[0][0][0][1] :- 3 Value of a[0][0][1][0] :- 5 Value of a[0][0][1][1] :- 3 Value of a[0][1][0][0] :- 6 Value of a[0][1][0][1] :- 7 Value of a[0][1][1][0] :- 6 Value of a[0][1][1][1] :- 7 Value of a[1][0][0][0] :- 8 Value of a[1][0][0][1] :- 9 Value of a[1][0][1][0] :- 8 Value of a[1][0][1][1] :- 9 Value of a[1][1][0][0] :- 9 Value of a[1][1][0][1] :- 7 Value of a[1][1][1][0] :- 9 Value of a[1][1][1][1] :- 7 Use:An 4D array can be used to store a collection of data, for example we input 3 coordinates & 1 time, i.e., x, y, z, t and we want to check whether there is collision between two vehicles or not. vitkaodessit sheikhdani669 cpp-array C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Ways to copy a vector in C++ Smart Pointers in C++ and How to Use Them Multiple Inheritance in C++ Understanding "extern" keyword in C How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25477, "s": 25449, "text": "\n18 Feb, 2022" }, { "code": null, "e": 25521, "s": 25477, "text": "Prerequisite :Array in C/C++, More on array" }, { "code": null, "e": 25767, "s": 25521, "text": "A four-dimensional (4D) array is an array of array of arrays of arrays or in other words 4D array is a array of 3D array.More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding arrays." }, { "code": null, "e": 25820, "s": 25767, "text": "Declaration of a Multidimensional Array in C:Syntax:" }, { "code": null, "e": 25939, "s": 25820, "text": "data_type array_name[i1][i2][i3][i4].........[in];\nwhere each i is a dimension, and in is the size of final dimension." }, { "code": null, "e": 26189, "s": 25939, "text": "Examples:1. int student[4][5][6][7];int designates the array type integer.student is the name of our 4D array.Our array can hold 840 integer-type elements. This number is reached by multiplying the value of each dimension. In this case: 4x5x6x7=840." }, { "code": null, "e": 26322, "s": 26189, "text": "2. float country[5][6][5][6][5];Array country is a five-dimensional array.It can hold 4500 floating-point elements (5x6x5x6x5=4500)." }, { "code": null, "e": 26332, "s": 26322, "text": "Program :" }, { "code": "// C Program to input 4D Matrix and print it.#include <stdio.h>int main(){ // variable declaration used for indexes int i, j, k, l, size; // Array declaration int a[2][2][2][2]; // size of array size = 2; // elements input a[0][0][0][0] = 5; a[0][0][0][1] = 3; a[0][0][1][0] = 5; a[0][0][1][1] = 3; a[0][1][0][0] = 6; a[0][1][0][1] = 7; a[0][1][1][0] = 6; a[0][1][1][1] = 7; a[1][0][0][0] = 8; a[1][0][0][1] = 9; a[1][0][1][0] = 8; a[1][0][1][1] = 9; a[1][1][0][0] = 9; a[1][1][0][1] = 7; a[1][1][1][0] = 9; a[1][1][1][1] = 7; // Printing the values for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { for (k = 0; k < size; k++) { for (l = 0; l < size; l++) { printf(\"Value of a[%d][%d][%d][%d] :- %d \", i, j, k, l, a[i][j][k][l]); printf(\"\\n\"); } } } } return 0;}", "e": 27331, "s": 26332, "text": null }, { "code": null, "e": 27795, "s": 27331, "text": "Value of a[0][0][0][0] :- 5 \nValue of a[0][0][0][1] :- 3 \nValue of a[0][0][1][0] :- 5 \nValue of a[0][0][1][1] :- 3 \nValue of a[0][1][0][0] :- 6 \nValue of a[0][1][0][1] :- 7 \nValue of a[0][1][1][0] :- 6 \nValue of a[0][1][1][1] :- 7 \nValue of a[1][0][0][0] :- 8 \nValue of a[1][0][0][1] :- 9 \nValue of a[1][0][1][0] :- 8 \nValue of a[1][0][1][1] :- 9 \nValue of a[1][1][0][0] :- 9 \nValue of a[1][1][0][1] :- 7 \nValue of a[1][1][1][0] :- 9 \nValue of a[1][1][1][1] :- 7\n" }, { "code": null, "e": 27993, "s": 27795, "text": "Use:An 4D array can be used to store a collection of data, for example we input 3 coordinates & 1 time, i.e., x, y, z, t and we want to check whether there is collision between two vehicles or not." }, { "code": null, "e": 28006, "s": 27993, "text": "vitkaodessit" }, { "code": null, "e": 28020, "s": 28006, "text": "sheikhdani669" }, { "code": null, "e": 28030, "s": 28020, "text": "cpp-array" }, { "code": null, "e": 28041, "s": 28030, "text": "C Language" }, { "code": null, "e": 28139, "s": 28041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28177, "s": 28139, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28203, "s": 28177, "text": "Exception Handling in C++" }, { "code": null, "e": 28223, "s": 28203, "text": "Multithreading in C" }, { "code": null, "e": 28245, "s": 28223, "text": "'this' pointer in C++" }, { "code": null, "e": 28286, "s": 28245, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28315, "s": 28286, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 28357, "s": 28315, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 28385, "s": 28357, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 28421, "s": 28385, "text": "Understanding \"extern\" keyword in C" } ]
Perl | 'e' modifier in Regular Expression - GeeksforGeeks
07 Jun, 2019 In Perl, the regular expression allows performing various operations on a given string with the use of suitable operators. These operators can perform operations like modification of string, substitution of other substrings, etc. Substitution of a substring in the given string is done with the use of ‘s'(substitution) operator, which takes two operands, one is the substring to be replaced and the other being the replacement string. s/To_be_replaced/Replacement/ Further, if there is a need to substitute the substring with a replacement string which is a regular expression to be evaluated, ‘e‘ modifier is used. The ‘e’ modifier is placed at the end of the substitution expression. s/To_be_replaced/Regular_Expression/e; ‘e’ modifier can also be used with the ‘g'(globally) modifier to make the changes over all possible substrings in the given string. Example 1: Using character class for substitution #!/usr/bin/perl # Defining the string to be converted$String = "Geeks for Geeks is the best";print "Original String: $String\n"; # Converting the string to UPPERCASE# using 'uc' Function$String =~ s/(\w+)/uc($1)/ge;print"Uppercased String: $String\n"; # Converting the string to lowercase# using 'lc' Function$String =~ s/(\w+)/lc($1)/ge;print"Lowercased String: $String\n"; Original String: Geeks for Geeks is the best Uppercased String: GEEKS FOR GEEKS IS THE BEST Lowercased String: geeks for geeks is the best Above code uses a character class ‘\w’ which holds the alphabet of lower case and upper case along with all the digits(a-z|A_Z|0-9). This is used to perform a single substitution operation on the whole string. Example 2: Using single character or a word for specific substitution #!/usr/bin/perl # Defining the string to be converted$String = "Geeks for Geeks is the best";print "Original String: $String\n"; # Converting a single character using e modifier$String =~ s/(e)/uc($1)/ge;print"Updated String: $String\n"; # Converting a word using e modifier$String =~ s/(for)/uc($1)/ge;print"Updated String: $String\n"; Original String: Geeks for Geeks is the best Updated String: GEEks for GEEks is thE bEst Updated String: GEEks FOR GEEks is thE bEst In the above code, it can be seen that the string after updation will not revert to its original version even after applying the second recursion on it. Use of a subroutine for the substitution operation:Substitution operation in Perl regex can also be done with the use of subroutines to avoid the redundancy of writing the substitution regex again and again for every string. This can be done by placing the regex code in the subroutine and calling it wherever required. Example: #!/usr/bin/perl # Subroutine for substitution operationsub subroutine{ $regex = shift; $regex =~ s/Friday/Tuesday/; return $regex;} # Defining the string to be converted$String = "Monday Friday Wednesday";print "Original String: $String\n"; # Calling the subroutine for substitution$String =~ s/(\w+)/subroutine($1)/ge;print"Updated String: $String\n"; # Defining a new String to be converted$String2 = "Today is Friday";print "\nOriginal String: $String2\n"; # Calling the subroutine for substitution$String2 =~ s/(\w+)/subroutine($1)/ge;print"Updated String: $String2\n"; Original String: Monday Friday Wednesday Updated String: Monday Tuesday Wednesday Original String: Today is Friday Updated String: Today is Tuesday In the above code, when the substitution operation begins then it calls the subroutine ‘change_substitution’ which holds the regex code for replacing the substring which matches the search. Perl-regex Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | join() Function Perl | length() Function Perl | Basic Syntax of a Perl Program Perl | Boolean Values Perl | sleep() Function Perl | Subroutines or Functions
[ { "code": null, "e": 25355, "s": 25327, "text": "\n07 Jun, 2019" }, { "code": null, "e": 25791, "s": 25355, "text": "In Perl, the regular expression allows performing various operations on a given string with the use of suitable operators. These operators can perform operations like modification of string, substitution of other substrings, etc. Substitution of a substring in the given string is done with the use of ‘s'(substitution) operator, which takes two operands, one is the substring to be replaced and the other being the replacement string." }, { "code": null, "e": 25821, "s": 25791, "text": "s/To_be_replaced/Replacement/" }, { "code": null, "e": 26042, "s": 25821, "text": "Further, if there is a need to substitute the substring with a replacement string which is a regular expression to be evaluated, ‘e‘ modifier is used. The ‘e’ modifier is placed at the end of the substitution expression." }, { "code": null, "e": 26081, "s": 26042, "text": "s/To_be_replaced/Regular_Expression/e;" }, { "code": null, "e": 26213, "s": 26081, "text": "‘e’ modifier can also be used with the ‘g'(globally) modifier to make the changes over all possible substrings in the given string." }, { "code": null, "e": 26263, "s": 26213, "text": "Example 1: Using character class for substitution" }, { "code": "#!/usr/bin/perl # Defining the string to be converted$String = \"Geeks for Geeks is the best\";print \"Original String: $String\\n\"; # Converting the string to UPPERCASE# using 'uc' Function$String =~ s/(\\w+)/uc($1)/ge;print\"Uppercased String: $String\\n\"; # Converting the string to lowercase# using 'lc' Function$String =~ s/(\\w+)/lc($1)/ge;print\"Lowercased String: $String\\n\";", "e": 26641, "s": 26263, "text": null }, { "code": null, "e": 26781, "s": 26641, "text": "Original String: Geeks for Geeks is the best\nUppercased String: GEEKS FOR GEEKS IS THE BEST\nLowercased String: geeks for geeks is the best\n" }, { "code": null, "e": 26991, "s": 26781, "text": "Above code uses a character class ‘\\w’ which holds the alphabet of lower case and upper case along with all the digits(a-z|A_Z|0-9). This is used to perform a single substitution operation on the whole string." }, { "code": null, "e": 27061, "s": 26991, "text": "Example 2: Using single character or a word for specific substitution" }, { "code": "#!/usr/bin/perl # Defining the string to be converted$String = \"Geeks for Geeks is the best\";print \"Original String: $String\\n\"; # Converting a single character using e modifier$String =~ s/(e)/uc($1)/ge;print\"Updated String: $String\\n\"; # Converting a word using e modifier$String =~ s/(for)/uc($1)/ge;print\"Updated String: $String\\n\";", "e": 27401, "s": 27061, "text": null }, { "code": null, "e": 27535, "s": 27401, "text": "Original String: Geeks for Geeks is the best\nUpdated String: GEEks for GEEks is thE bEst\nUpdated String: GEEks FOR GEEks is thE bEst\n" }, { "code": null, "e": 27688, "s": 27535, "text": "In the above code, it can be seen that the string after updation will not revert to its original version even after applying the second recursion on it." }, { "code": null, "e": 28008, "s": 27688, "text": "Use of a subroutine for the substitution operation:Substitution operation in Perl regex can also be done with the use of subroutines to avoid the redundancy of writing the substitution regex again and again for every string. This can be done by placing the regex code in the subroutine and calling it wherever required." }, { "code": null, "e": 28017, "s": 28008, "text": "Example:" }, { "code": "#!/usr/bin/perl # Subroutine for substitution operationsub subroutine{ $regex = shift; $regex =~ s/Friday/Tuesday/; return $regex;} # Defining the string to be converted$String = \"Monday Friday Wednesday\";print \"Original String: $String\\n\"; # Calling the subroutine for substitution$String =~ s/(\\w+)/subroutine($1)/ge;print\"Updated String: $String\\n\"; # Defining a new String to be converted$String2 = \"Today is Friday\";print \"\\nOriginal String: $String2\\n\"; # Calling the subroutine for substitution$String2 =~ s/(\\w+)/subroutine($1)/ge;print\"Updated String: $String2\\n\";", "e": 28607, "s": 28017, "text": null }, { "code": null, "e": 28757, "s": 28607, "text": "Original String: Monday Friday Wednesday\nUpdated String: Monday Tuesday Wednesday\n\nOriginal String: Today is Friday\nUpdated String: Today is Tuesday\n" }, { "code": null, "e": 28947, "s": 28757, "text": "In the above code, when the substitution operation begins then it calls the subroutine ‘change_substitution’ which holds the regex code for replacing the substring which matches the search." }, { "code": null, "e": 28958, "s": 28947, "text": "Perl-regex" }, { "code": null, "e": 28963, "s": 28958, "text": "Perl" }, { "code": null, "e": 28968, "s": 28963, "text": "Perl" }, { "code": null, "e": 29066, "s": 28968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29108, "s": 29066, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 29122, "s": 29108, "text": "Perl | Arrays" }, { "code": null, "e": 29163, "s": 29122, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29196, "s": 29163, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 29219, "s": 29196, "text": "Perl | join() Function" }, { "code": null, "e": 29244, "s": 29219, "text": "Perl | length() Function" }, { "code": null, "e": 29282, "s": 29244, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 29304, "s": 29282, "text": "Perl | Boolean Values" }, { "code": null, "e": 29328, "s": 29304, "text": "Perl | sleep() Function" } ]
How to read value from string.xml in Android?
This example demonstrates how to read value from string.xml 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/values/strings.xml <resources> <string name="app_name">Sample</string> <string name="NameOfTheString">Test string</string> </resources> Step 3 − Add the following code to res/layout/activity_main.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" android:text="@string/NameOfTheString" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> Step 4 − Add the following code to src/MainActivity.java package com.example.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 5 – Add the following code to app/manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample"> <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 – Click here to download the project code.
[ { "code": null, "e": 1134, "s": 1062, "text": "This example demonstrates how to read value from string.xml in Android." }, { "code": null, "e": 1264, "s": 1134, "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": 1323, "s": 1264, "text": "Step 2 − Add the following code to res/values/strings.xml" }, { "code": null, "e": 1446, "s": 1323, "text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"NameOfTheString\">Test string</string>\n</resources>" }, { "code": null, "e": 1511, "s": 1446, "text": "Step 3 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 2272, "s": 1511, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\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:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n android:text=\"@string/NameOfTheString\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2330, "s": 2272, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2651, "s": 2330, "text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 2721, "s": 2651, "text": "Step 5 – Add the following code to app/manifests/AndroidManifest.xml" }, { "code": null, "e": 3395, "s": 2721, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.sample\">\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": 3742, "s": 3395, "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": 3783, "s": 3742, "text": "Click here to download the project code." } ]
Check whether the number has only first and last bits set | Set 2 - GeeksforGeeks
08 Apr, 2021 Given a positive integer n, check whether only the first and last bits are set in the binary representation of n. Print ‘Yes’ or ‘No’.Examples: Input: 9 Output: Yes (9)10 = (1001)2, only the first and last bits are set.Input: 15 Output: No (15)10 = (1111)2, except first and last there are other bits also which are set. We have already discussed a solution here.In this post, a simpler solution is discussed. C++ Java Python3 C# PHP Javascript // C++ to check whether the number has only// first and last bits set#include <bits/stdc++.h>using namespace std; // function to check whether the number has only// first and last bits setbool onlyFirstAndLastAreSet(unsigned int n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver program to test aboveint main(){ unsigned int n = 9; if (onlyFirstAndLastAreSet(n)) cout << "Yes"; else cout << "No"; return 0;} // Java to check whether// the number has only// first and last bits set class GFG{// function to check whether// the number has only// first and last bits setstatic boolean onlyFirstAndLastAreSet(int n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver Codepublic static void main(String[] args){ int n = 9; if (onlyFirstAndLastAreSet(n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed// by Smitha # Python 3 to check whether# the number has only# first and last bits set # function to check whether# the number has only# first and last bits setdef onlyFirstAndLastAreSet(n): if (n == 1): return True if (n == 2): return False return (((n - 1) & (n - 2)) == 0) # Driver Coden = 9if (onlyFirstAndLastAreSet(n)): print("Yes")else: print("No") # This code is contributed# by Smitha // C# to check whether// the number has only// first and last bits setusing System; class GFG{// function to check whether// the number has only// first and last bits setstatic bool onlyFirstAndLastAreSet(int n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver Codepublic static void Main(){ int n = 9; if (onlyFirstAndLastAreSet(n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed// by Smitha <?php// PHP to check whether the// number has only first and// last bits set // function to check whether// the number has only first// and last bits setfunction onlyFirstAndLastAreSet($n){ if ($n == 1) return true; if ($n == 2) return false; return ((($n - 1) & ($n - 2)) == 0);} // Driver Code$n = 9;if (onlyFirstAndLastAreSet($n)) echo "Yes";else echo "No"; // This code is contributed// by Smitha?> <script> // javascript to check whether// the number has only// first and last bits set // function to check whether// the number has only// first and last bits setfunction onlyFirstAndLastAreSet(n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver Code var n = 9;if (onlyFirstAndLastAreSet(n)) document.write("Yes");else document.write("No"); // This code contributed by shikhasingrajput </script> Yes Smitha Dinesh Semwal shikhasingrajput Binary Search Bit Algorithms Bit Magic Misc Misc Bit Magic Misc Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Add two numbers without using arithmetic operators Binary representation of a given number Program to find whether a given number is power of 2 Top 10 algorithms in Interview Questions Find all factors of a natural number | Set 1 vector::push_back() and vector::pop_back() in C++ STL How to write Regular Expressions? fgets() and gets() in C language
[ { "code": null, "e": 24727, "s": 24699, "text": "\n08 Apr, 2021" }, { "code": null, "e": 24873, "s": 24727, "text": "Given a positive integer n, check whether only the first and last bits are set in the binary representation of n. Print ‘Yes’ or ‘No’.Examples: " }, { "code": null, "e": 25052, "s": 24873, "text": "Input: 9 Output: Yes (9)10 = (1001)2, only the first and last bits are set.Input: 15 Output: No (15)10 = (1111)2, except first and last there are other bits also which are set. " }, { "code": null, "e": 25144, "s": 25054, "text": "We have already discussed a solution here.In this post, a simpler solution is discussed. " }, { "code": null, "e": 25148, "s": 25144, "text": "C++" }, { "code": null, "e": 25153, "s": 25148, "text": "Java" }, { "code": null, "e": 25161, "s": 25153, "text": "Python3" }, { "code": null, "e": 25164, "s": 25161, "text": "C#" }, { "code": null, "e": 25168, "s": 25164, "text": "PHP" }, { "code": null, "e": 25179, "s": 25168, "text": "Javascript" }, { "code": "// C++ to check whether the number has only// first and last bits set#include <bits/stdc++.h>using namespace std; // function to check whether the number has only// first and last bits setbool onlyFirstAndLastAreSet(unsigned int n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver program to test aboveint main(){ unsigned int n = 9; if (onlyFirstAndLastAreSet(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 25688, "s": 25179, "text": null }, { "code": "// Java to check whether// the number has only// first and last bits set class GFG{// function to check whether// the number has only// first and last bits setstatic boolean onlyFirstAndLastAreSet(int n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver Codepublic static void main(String[] args){ int n = 9; if (onlyFirstAndLastAreSet(n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed// by Smitha", "e": 26234, "s": 25688, "text": null }, { "code": "# Python 3 to check whether# the number has only# first and last bits set # function to check whether# the number has only# first and last bits setdef onlyFirstAndLastAreSet(n): if (n == 1): return True if (n == 2): return False return (((n - 1) & (n - 2)) == 0) # Driver Coden = 9if (onlyFirstAndLastAreSet(n)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Smitha", "e": 26662, "s": 26234, "text": null }, { "code": "// C# to check whether// the number has only// first and last bits setusing System; class GFG{// function to check whether// the number has only// first and last bits setstatic bool onlyFirstAndLastAreSet(int n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver Codepublic static void Main(){ int n = 9; if (onlyFirstAndLastAreSet(n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed// by Smitha", "e": 27193, "s": 26662, "text": null }, { "code": "<?php// PHP to check whether the// number has only first and// last bits set // function to check whether// the number has only first// and last bits setfunction onlyFirstAndLastAreSet($n){ if ($n == 1) return true; if ($n == 2) return false; return ((($n - 1) & ($n - 2)) == 0);} // Driver Code$n = 9;if (onlyFirstAndLastAreSet($n)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Smitha?>", "e": 27641, "s": 27193, "text": null }, { "code": "<script> // javascript to check whether// the number has only// first and last bits set // function to check whether// the number has only// first and last bits setfunction onlyFirstAndLastAreSet(n){ if (n == 1) return true; if (n == 2) return false; return (((n - 1) & (n - 2)) == 0);} // Driver Code var n = 9;if (onlyFirstAndLastAreSet(n)) document.write(\"Yes\");else document.write(\"No\"); // This code contributed by shikhasingrajput </script>", "e": 28129, "s": 27641, "text": null }, { "code": null, "e": 28133, "s": 28129, "text": "Yes" }, { "code": null, "e": 28156, "s": 28135, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 28173, "s": 28156, "text": "shikhasingrajput" }, { "code": null, "e": 28187, "s": 28173, "text": "Binary Search" }, { "code": null, "e": 28202, "s": 28187, "text": "Bit Algorithms" }, { "code": null, "e": 28212, "s": 28202, "text": "Bit Magic" }, { "code": null, "e": 28217, "s": 28212, "text": "Misc" }, { "code": null, "e": 28222, "s": 28217, "text": "Misc" }, { "code": null, "e": 28232, "s": 28222, "text": "Bit Magic" }, { "code": null, "e": 28237, "s": 28232, "text": "Misc" }, { "code": null, "e": 28251, "s": 28237, "text": "Binary Search" }, { "code": null, "e": 28349, "s": 28251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28358, "s": 28349, "text": "Comments" }, { "code": null, "e": 28371, "s": 28358, "text": "Old Comments" }, { "code": null, "e": 28417, "s": 28371, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 28447, "s": 28417, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 28498, "s": 28447, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 28538, "s": 28498, "text": "Binary representation of a given number" }, { "code": null, "e": 28591, "s": 28538, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 28632, "s": 28591, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 28677, "s": 28632, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 28731, "s": 28677, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 28765, "s": 28731, "text": "How to write Regular Expressions?" } ]
Bootstrap Navigation Bar
A navigation bar is a navigation header that is placed at the top of the page: Home Page 1 Page 2 Page 3 With Bootstrap, a navigation bar can extend or collapse, depending on the screen size. A standard navigation bar is created with <nav class="navbar navbar-default">. The following example shows how to add a navigation bar to the top of the page: Note: All of the examples on this page will show a navigation bar that takes up too much space on small screens (however, the navigation bar will be on one single line on large screens - because Bootstrap is responsive). This problem (with the small screens) will be solved in the last example on this page. If you don't like the style of the default navigation bar, Bootstrap provides an alternative, black navbar: Home Page 1 Page 2 Page 3 Just change the .navbar-default class into .navbar-inverse: Home Page 1 Page 1-1 Page 1-2 Page 1-3 Page 1-1 Page 1-2 Page 1-3 Page 2 Page 3 Navigation bars can also hold dropdown menus. The following example adds a dropdown menu for the "Page 1" button: Home Page 1 Page 2 Sign Up Login The .navbar-right class is used to right-align navigation bar buttons. In the following example we insert a "Sign Up" button and a "Login" button to the right in the navigation bar. We also add a glyphicon on each of the two new buttons: Home Link Link To add buttons inside the navbar, add the .navbar-btn class on a Bootstrap button: Home Page 1 Page 2 To add form elements inside the navbar, add the .navbar-form class to a form element and add an input(s). Note that we have added a .form-group class to the div container holding the input. This adds proper padding if you have more than one inputs (you will learn more about this in the Forms chapter). You can also use the .input-group and .input-group-addon classes to attach an icon or help text next to the input field. You will learn more about these classes in the Bootstrap Inputs chapter. Home Page 1 Page 2 Link Link Some text Use the .navbar-text class to vertical align any elements inside the navbar that are not links (ensures proper padding and text color). The navigation bar can also be fixed at the top or at the bottom of the page. A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll. Link Link A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll. The .navbar-fixed-top class makes the navigation bar fixed at the top: The .navbar-fixed-bottom class makes the navigation bar stay at the bottom: The navigation bar often takes up too much space on a small screen. We should hide the navigation bar; and only show it when it is needed. In the following example the navigation bar is replaced by a button in the top right corner. Only when the button is clicked, the navigation bar will be displayed: Link Link Link Click on the button in the top right corner to reveal the navigation links. Add the required class names to create a default Navigation Bar. <nav class=""> <div class="container-fluid"> <ul class="nav navbar-nav"> <li><a href="#">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> </div> </nav> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 80, "s": 0, "text": "A navigation bar is a navigation header that is placed at the top of the \npage:" }, { "code": null, "e": 85, "s": 80, "text": "Home" }, { "code": null, "e": 92, "s": 85, "text": "Page 1" }, { "code": null, "e": 99, "s": 92, "text": "Page 2" }, { "code": null, "e": 106, "s": 99, "text": "Page 3" }, { "code": null, "e": 194, "s": 106, "text": "With Bootstrap, a navigation bar can extend or collapse, depending on the \nscreen size." }, { "code": null, "e": 273, "s": 194, "text": "A standard navigation bar is created with <nav class=\"navbar navbar-default\">." }, { "code": null, "e": 353, "s": 273, "text": "The following example shows how to add a navigation bar to the top of the page:" }, { "code": null, "e": 665, "s": 353, "text": "Note: All of the examples on this page will show a navigation bar that takes up \ntoo much space on small screens (however, the navigation bar will be on one single \nline on large screens - because Bootstrap is responsive). This problem (with the \nsmall screens) will be \nsolved in the last example on this page." }, { "code": null, "e": 774, "s": 665, "text": "If you don't like the style of the default navigation bar, Bootstrap provides an alternative, \nblack navbar:" }, { "code": null, "e": 779, "s": 774, "text": "Home" }, { "code": null, "e": 786, "s": 779, "text": "Page 1" }, { "code": null, "e": 793, "s": 786, "text": "Page 2" }, { "code": null, "e": 800, "s": 793, "text": "Page 3" }, { "code": null, "e": 860, "s": 800, "text": "Just change the .navbar-default class into .navbar-inverse:" }, { "code": null, "e": 865, "s": 860, "text": "Home" }, { "code": null, "e": 903, "s": 865, "text": "Page 1 \n\nPage 1-1\nPage 1-2\nPage 1-3\n\n" }, { "code": null, "e": 912, "s": 903, "text": "Page 1-1" }, { "code": null, "e": 921, "s": 912, "text": "Page 1-2" }, { "code": null, "e": 930, "s": 921, "text": "Page 1-3" }, { "code": null, "e": 937, "s": 930, "text": "Page 2" }, { "code": null, "e": 944, "s": 937, "text": "Page 3" }, { "code": null, "e": 990, "s": 944, "text": "Navigation bars can also hold dropdown menus." }, { "code": null, "e": 1059, "s": 990, "text": "The following example adds a dropdown menu for the \"Page 1\" \nbutton:" }, { "code": null, "e": 1064, "s": 1059, "text": "Home" }, { "code": null, "e": 1071, "s": 1064, "text": "Page 1" }, { "code": null, "e": 1078, "s": 1071, "text": "Page 2" }, { "code": null, "e": 1087, "s": 1078, "text": " Sign Up" }, { "code": null, "e": 1094, "s": 1087, "text": " Login" }, { "code": null, "e": 1166, "s": 1094, "text": "The .navbar-right class is used to right-align navigation bar buttons. " }, { "code": null, "e": 1335, "s": 1166, "text": "In the following example we insert a \"Sign Up\" button and a \"Login\" button to \nthe right in the navigation bar. We also add a glyphicon on each of the two new \nbuttons:" }, { "code": null, "e": 1340, "s": 1335, "text": "Home" }, { "code": null, "e": 1345, "s": 1340, "text": "Link" }, { "code": null, "e": 1350, "s": 1345, "text": "Link" }, { "code": null, "e": 1434, "s": 1350, "text": "To add buttons inside the navbar, add the .navbar-btn class on a Bootstrap \nbutton:" }, { "code": null, "e": 1439, "s": 1434, "text": "Home" }, { "code": null, "e": 1446, "s": 1439, "text": "Page 1" }, { "code": null, "e": 1453, "s": 1446, "text": "Page 2" }, { "code": null, "e": 1756, "s": 1453, "text": "To add form elements inside the navbar, add the .navbar-form class to a form element and add an input(s). Note that we have added a .form-group class to the div container holding the input. This adds proper padding if you have more than one inputs (you will learn more about this in the Forms chapter)." }, { "code": null, "e": 1950, "s": 1756, "text": "You can also use the .input-group and .input-group-addon classes to attach an icon or help text next to the input field. You will learn more about these classes in the Bootstrap Inputs chapter." }, { "code": null, "e": 1955, "s": 1950, "text": "Home" }, { "code": null, "e": 1962, "s": 1955, "text": "Page 1" }, { "code": null, "e": 1969, "s": 1962, "text": "Page 2" }, { "code": null, "e": 1974, "s": 1969, "text": "Link" }, { "code": null, "e": 1979, "s": 1974, "text": "Link" }, { "code": null, "e": 1989, "s": 1979, "text": "Some text" }, { "code": null, "e": 2126, "s": 1989, "text": "Use the .navbar-text class to vertical align any elements inside the navbar that are not links (ensures proper padding \nand text color)." }, { "code": null, "e": 2204, "s": 2126, "text": "The navigation bar can also be fixed at the top or at the bottom of the page." }, { "code": null, "e": 2310, "s": 2204, "text": "A fixed navigation bar stays visible in a fixed position (top or bottom) \nindependent of the page scroll." }, { "code": null, "e": 2317, "s": 2310, "text": "\nLink\n" }, { "code": null, "e": 2324, "s": 2317, "text": "\nLink\n" }, { "code": null, "e": 2429, "s": 2324, "text": "A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll." }, { "code": null, "e": 2501, "s": 2429, "text": "The .navbar-fixed-top class makes the navigation bar fixed at \nthe top:" }, { "code": null, "e": 2578, "s": 2501, "text": "The .navbar-fixed-bottom class makes the navigation bar stay at \nthe bottom:" }, { "code": null, "e": 2646, "s": 2578, "text": "The navigation bar often takes up too much space on a small screen." }, { "code": null, "e": 2717, "s": 2646, "text": "We should hide the navigation bar; and only show it when it is needed." }, { "code": null, "e": 2883, "s": 2717, "text": "In the following example the navigation bar is replaced by a button \nin the top right corner. Only when the button is clicked, the navigation bar will be \ndisplayed:" }, { "code": null, "e": 2890, "s": 2883, "text": "\nLink\n" }, { "code": null, "e": 2897, "s": 2890, "text": "\nLink\n" }, { "code": null, "e": 2904, "s": 2897, "text": "\nLink\n" }, { "code": null, "e": 2980, "s": 2904, "text": "Click on the button in the top right corner to reveal the navigation links." }, { "code": null, "e": 3045, "s": 2980, "text": "Add the required class names to create a default Navigation Bar." }, { "code": null, "e": 3265, "s": 3045, "text": "<nav class=\"\">\n <div class=\"container-fluid\">\n <ul class=\"nav navbar-nav\">\n <li><a href=\"#\">Page 1</a></li>\n <li><a href=\"#\">Page 2</a></li>\n <li><a href=\"#\">Page 3</a></li>\n </ul>\n </div>\n</nav>\n" }, { "code": null, "e": 3284, "s": 3265, "text": "Start the Exercise" }, { "code": null, "e": 3317, "s": 3284, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3359, "s": 3317, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3466, "s": 3359, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3485, "s": 3466, "text": "[email protected]" } ]
Filter Pattern in Java - GeeksforGeeks
17 Mar, 2021 Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations. Procedure: Create a class on which Criteria is to be applied.Create an interface for Criteria.Create concrete classes implementing the Criteria interface.Use different Criteria and their combination to filter out persons.Verify the output Create a class on which Criteria is to be applied. Create an interface for Criteria. Create concrete classes implementing the Criteria interface. Use different Criteria and their combination to filter out persons. Verify the output Implementation : We’re going to create a Person object, Criteria interface, and concrete classes implementing this interface to filter the list of Person objects. CriteriaPatternDemo, our demo class uses Criteria objects to filter List of Person objects based on various criteria and their combinations. Step 1: Create a class on which Criteria are to be applied. Person.java public class Person { private String name; private String gender; private String maritalStatus; public Person(String name, String gender, String maritalStatus){ this.name = name; this.gender = gender; this.maritalStatus = maritalStatus; } public String getName() { return name; } public String getGender() { return gender; } public String getMaritalStatus() { return maritalStatus; } } Step 2: Create an interface for Criteria. Criteria.java import java.util.List; public interface Criteria { public List<Person> meetCriteria(List<Person> persons); } Step 3: Create concrete classes implementing the Criteria interface. CriteriaMale.java import java.util.ArrayList; import java.util.List; public class CriteriaMale implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> malePersons = new ArrayList<Person>(); for (Person person : persons) { if(person.getGender().equalsIgnoreCase("MALE")){ malePersons.add(person); } } return malePersons; } } CriteriaFemale.java import java.util.ArrayList; import java.util.List; public class CriteriaFemale implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> femalePersons = new ArrayList<Person>(); for (Person person : persons) { if(person.getGender().equalsIgnoreCase("FEMALE")){ femalePersons.add(person); } } return femalePersons; } } CriteriaSingle.java import java.util.ArrayList; import java.util.List; public class CriteriaSingle implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> singlePersons = new ArrayList<Person>(); for (Person person : persons) { if(person.getMaritalStatus().equalsIgnoreCase("SINGLE")){ singlePersons.add(person); } } return singlePersons; } } AndCriteria.java import java.util.List; public class AndCriteria implements Criteria { private Criteria criteria; private Criteria otherCriteria; public AndCriteria(Criteria criteria, Criteria otherCriteria) { this.criteria = criteria; this.otherCriteria = otherCriteria; } @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> firstCriteriaPersons = criteria.meetCriteria(persons); return otherCriteria.meetCriteria(firstCriteriaPersons); } } OrCriteria.java import java.util.List; public class OrCriteria implements Criteria { private Criteria criteria; private Criteria otherCriteria; public OrCriteria(Criteria criteria, Criteria otherCriteria) { this.criteria = criteria; this.otherCriteria = otherCriteria; } @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> firstCriteriaItems = criteria.meetCriteria(persons); List<Person> otherCriteriaItems = otherCriteria.meetCriteria(persons); for (Person person : otherCriteriaItems) { if(!firstCriteriaItems.contains(person)){ firstCriteriaItems.add(person); } } return firstCriteriaItems; } } Step 4: Use different Criteria and their combination to filter out persons. CriteriaPatternDemo.java Java // Importing ArrayList and List class // from java.util package import java.util.ArrayList;import java.util.List; // Class// Main classpublic class CriteriaPatternDemo { // Main driver method public static void main(String[] args) { // Creating a onbject of List in main() method // Declaring object of user-defined datatype 'Person' List<Person> persons = new ArrayList<Person>(); // Adding elements to the object created above // using the add() method of List // Custom entries persons.add(new Person("Robert","Male", "Single")); persons.add(new Person("John", "Male", "Married")); persons.add(new Person("Laura", "Female", "Married")); persons.add(new Person("Diana", "Female", "Single")); persons.add(new Person("Mike", "Male", "Single")); persons.add(new Person("Bobby", "Male", "Single")); Criteria male = new CriteriaMale(); Criteria female = new CriteriaFemale(); Criteria single = new CriteriaSingle(); Criteria singleMale = new AndCriteria(single, male); Criteria singleOrFemale = new OrCriteria(single, female); // Display message System.out.println("Males: "); printPersons(male.meetCriteria(persons)); // Display message System.out.println("\nFemales: "); printPersons(female.meetCriteria(persons)); // Display message System.out.println("\nSingle Males: "); printPersons(singleMale.meetCriteria(persons)); // Display message System.out.println("\nSingle Or Females: "); printPersons(singleOrFemale.meetCriteria(persons)); } public static void printPersons(List<Person> persons){ for (Person person : persons) { System.out.println("Person : [ Name : " + person.getName() + ", Gender : " + person.getGender() + ", Marital Status : " + person.getMaritalStatus() + " ]"); } } } Step 5: Verify the output. Males: Person : [ Name : Robert, Gender : Male, Marital Status : Single ] Person : [ Name : John, Gender : Male, Marital Status : Married ] Person : [ Name : Mike, Gender : Male, Marital Status : Single ] Person : [ Name : Bobby, Gender : Male, Marital Status : Single ] Females: Person : [ Name : Laura, Gender : Female, Marital Status : Married ] Person : [ Name : Diana, Gender : Female, Marital Status : Single ] Single Males: Person : [ Name : Robert, Gender : Male, Marital Status : Single ] Person : [ Name : Mike, Gender : Male, Marital Status : Single ] Person : [ Name : Bobby, Gender : Male, Marital Status : Single ] Single Or Females: Person : [ Name : Robert, Gender : Male, Marital Status : Single ] Person : [ Name : Diana, Gender : Female, Marital Status : Single ] Person : [ Name : Mike, Gender : Male, Marital Status : Single ] Person : [ Name : Bobby, Gender : Male, Marital Status : Single ] Person : [ Name : Laura, Gender : Female, Marital Status : Married ] Java-Design-Patterns Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23973, "s": 23945, "text": "\n17 Mar, 2021" }, { "code": null, "e": 24169, "s": 23973, "text": "Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations." }, { "code": null, "e": 24180, "s": 24169, "text": "Procedure:" }, { "code": null, "e": 24408, "s": 24180, "text": "Create a class on which Criteria is to be applied.Create an interface for Criteria.Create concrete classes implementing the Criteria interface.Use different Criteria and their combination to filter out persons.Verify the output" }, { "code": null, "e": 24459, "s": 24408, "text": "Create a class on which Criteria is to be applied." }, { "code": null, "e": 24493, "s": 24459, "text": "Create an interface for Criteria." }, { "code": null, "e": 24554, "s": 24493, "text": "Create concrete classes implementing the Criteria interface." }, { "code": null, "e": 24622, "s": 24554, "text": "Use different Criteria and their combination to filter out persons." }, { "code": null, "e": 24640, "s": 24622, "text": "Verify the output" }, { "code": null, "e": 24657, "s": 24640, "text": "Implementation :" }, { "code": null, "e": 24944, "s": 24657, "text": "We’re going to create a Person object, Criteria interface, and concrete classes implementing this interface to filter the list of Person objects. CriteriaPatternDemo, our demo class uses Criteria objects to filter List of Person objects based on various criteria and their combinations." }, { "code": null, "e": 25004, "s": 24944, "text": "Step 1: Create a class on which Criteria are to be applied." }, { "code": null, "e": 25016, "s": 25004, "text": "Person.java" }, { "code": null, "e": 25490, "s": 25016, "text": "public class Person {\n \n private String name;\n private String gender;\n private String maritalStatus;\n\n public Person(String name, String gender, String maritalStatus){\n this.name = name;\n this.gender = gender;\n this.maritalStatus = maritalStatus; \n }\n\n public String getName() {\n return name;\n }\n public String getGender() {\n return gender;\n }\n public String getMaritalStatus() {\n return maritalStatus;\n } \n}" }, { "code": null, "e": 25532, "s": 25490, "text": "Step 2: Create an interface for Criteria." }, { "code": null, "e": 25546, "s": 25532, "text": "Criteria.java" }, { "code": null, "e": 25659, "s": 25546, "text": "import java.util.List;\n\npublic interface Criteria {\n public List<Person> meetCriteria(List<Person> persons);\n}" }, { "code": null, "e": 25728, "s": 25659, "text": "Step 3: Create concrete classes implementing the Criteria interface." }, { "code": null, "e": 25746, "s": 25728, "text": "CriteriaMale.java" }, { "code": null, "e": 26171, "s": 25746, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaMale implements Criteria {\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> malePersons = new ArrayList<Person>(); \n \n for (Person person : persons) {\n if(person.getGender().equalsIgnoreCase(\"MALE\")){\n malePersons.add(person);\n }\n }\n return malePersons;\n }\n}" }, { "code": null, "e": 26191, "s": 26171, "text": "CriteriaFemale.java" }, { "code": null, "e": 26626, "s": 26191, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaFemale implements Criteria {\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> femalePersons = new ArrayList<Person>(); \n \n for (Person person : persons) {\n if(person.getGender().equalsIgnoreCase(\"FEMALE\")){\n femalePersons.add(person);\n }\n }\n return femalePersons;\n }\n}" }, { "code": null, "e": 26646, "s": 26626, "text": "CriteriaSingle.java" }, { "code": null, "e": 27088, "s": 26646, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaSingle implements Criteria {\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> singlePersons = new ArrayList<Person>(); \n \n for (Person person : persons) {\n if(person.getMaritalStatus().equalsIgnoreCase(\"SINGLE\")){\n singlePersons.add(person);\n }\n }\n return singlePersons;\n }\n}" }, { "code": null, "e": 27105, "s": 27088, "text": "AndCriteria.java" }, { "code": null, "e": 27620, "s": 27105, "text": "import java.util.List;\n\npublic class AndCriteria implements Criteria {\n\n private Criteria criteria;\n private Criteria otherCriteria;\n\n public AndCriteria(Criteria criteria, Criteria otherCriteria) {\n this.criteria = criteria;\n this.otherCriteria = otherCriteria; \n }\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n \n List<Person> firstCriteriaPersons = criteria.meetCriteria(persons); \n return otherCriteria.meetCriteria(firstCriteriaPersons);\n }\n}" }, { "code": null, "e": 27636, "s": 27620, "text": "OrCriteria.java" }, { "code": null, "e": 28350, "s": 27636, "text": "import java.util.List;\n\npublic class OrCriteria implements Criteria {\n\n private Criteria criteria;\n private Criteria otherCriteria;\n\n public OrCriteria(Criteria criteria, Criteria otherCriteria) {\n this.criteria = criteria;\n this.otherCriteria = otherCriteria; \n }\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> firstCriteriaItems = criteria.meetCriteria(persons);\n List<Person> otherCriteriaItems = otherCriteria.meetCriteria(persons);\n\n for (Person person : otherCriteriaItems) {\n if(!firstCriteriaItems.contains(person)){\n firstCriteriaItems.add(person);\n }\n } \n return firstCriteriaItems;\n }\n}" }, { "code": null, "e": 28426, "s": 28350, "text": "Step 4: Use different Criteria and their combination to filter out persons." }, { "code": null, "e": 28451, "s": 28426, "text": "CriteriaPatternDemo.java" }, { "code": null, "e": 28456, "s": 28451, "text": "Java" }, { "code": "// Importing ArrayList and List class // from java.util package import java.util.ArrayList;import java.util.List; // Class// Main classpublic class CriteriaPatternDemo { // Main driver method public static void main(String[] args) { // Creating a onbject of List in main() method // Declaring object of user-defined datatype 'Person' List<Person> persons = new ArrayList<Person>(); // Adding elements to the object created above // using the add() method of List // Custom entries persons.add(new Person(\"Robert\",\"Male\", \"Single\")); persons.add(new Person(\"John\", \"Male\", \"Married\")); persons.add(new Person(\"Laura\", \"Female\", \"Married\")); persons.add(new Person(\"Diana\", \"Female\", \"Single\")); persons.add(new Person(\"Mike\", \"Male\", \"Single\")); persons.add(new Person(\"Bobby\", \"Male\", \"Single\")); Criteria male = new CriteriaMale(); Criteria female = new CriteriaFemale(); Criteria single = new CriteriaSingle(); Criteria singleMale = new AndCriteria(single, male); Criteria singleOrFemale = new OrCriteria(single, female); // Display message System.out.println(\"Males: \"); printPersons(male.meetCriteria(persons)); // Display message System.out.println(\"\\nFemales: \"); printPersons(female.meetCriteria(persons)); // Display message System.out.println(\"\\nSingle Males: \"); printPersons(singleMale.meetCriteria(persons)); // Display message System.out.println(\"\\nSingle Or Females: \"); printPersons(singleOrFemale.meetCriteria(persons)); } public static void printPersons(List<Person> persons){ for (Person person : persons) { System.out.println(\"Person : [ Name : \" + person.getName() + \", Gender : \" + person.getGender() + \", Marital Status : \" + person.getMaritalStatus() + \" ]\"); } } }", "e": 30359, "s": 28456, "text": null }, { "code": null, "e": 30386, "s": 30359, "text": "Step 5: Verify the output." }, { "code": null, "e": 31376, "s": 30386, "text": "Males: \nPerson : [ Name : Robert, Gender : Male, Marital Status : Single ]\nPerson : [ Name : John, Gender : Male, Marital Status : Married ]\nPerson : [ Name : Mike, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Bobby, Gender : Male, Marital Status : Single ]\n\nFemales: \nPerson : [ Name : Laura, Gender : Female, Marital Status : Married ]\nPerson : [ Name : Diana, Gender : Female, Marital Status : Single ]\n\nSingle Males: \nPerson : [ Name : Robert, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Mike, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Bobby, Gender : Male, Marital Status : Single ]\n\nSingle Or Females: \nPerson : [ Name : Robert, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Diana, Gender : Female, Marital Status : Single ]\nPerson : [ Name : Mike, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Bobby, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Laura, Gender : Female, Marital Status : Married ]" }, { "code": null, "e": 31397, "s": 31376, "text": "Java-Design-Patterns" }, { "code": null, "e": 31402, "s": 31397, "text": "Java" }, { "code": null, "e": 31407, "s": 31402, "text": "Java" }, { "code": null, "e": 31505, "s": 31407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31514, "s": 31505, "text": "Comments" }, { "code": null, "e": 31527, "s": 31514, "text": "Old Comments" }, { "code": null, "e": 31573, "s": 31527, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31594, "s": 31573, "text": "Constructors in Java" }, { "code": null, "e": 31609, "s": 31594, "text": "Stream In Java" }, { "code": null, "e": 31626, "s": 31609, "text": "Generics in Java" }, { "code": null, "e": 31645, "s": 31626, "text": "Exceptions in Java" }, { "code": null, "e": 31675, "s": 31645, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31718, "s": 31675, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 31747, "s": 31718, "text": "HashMap get() Method in Java" }, { "code": null, "e": 31763, "s": 31747, "text": "Strings in Java" } ]
How to Send Spring Boot Kafka JSON Message to Kafka Topic ?
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Here we will see how to send Spring Boot Kafka JSON Message to Kafka Topic using Kafka Template. We can publish the JSON messages to Apache Kafka through spring boot application, in the previous article we have seen how to send simple string messages to Kafka. Spring Boot 2.1.3.RELEASE Spring Kafka Apache Kafka 2.11 Java 8 Maven To run the application, you have to have Apache Kafka installed on your machine. I have provided a couple of articles which helps you to install Apache Kafka on Windows and Ubuntu operating systems. Install Apache Kafka on Windows 10 Operating System Install Apache Kafka On Ubuntu Operating System After successful installation, start the zookeeper, Kafka servers to connect from spring boot application. root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties [2019-03-28 00:22:52,195] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig) [2019-03-28 00:22:52,210] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-28 00:22:52,210] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-28 00:22:52,211] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-28 00:22:52,211] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain) root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties [2019-03-28 00:24:08,203] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$) [2019-03-28 00:24:09,146] INFO starting (kafka.server.KafkaServer) [2019-03-28 00:24:09,147] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer) [2019-03-28 00:24:09,219] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient) [2019-03-28 00:24:09,229] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper) root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic items-topic Created topic "items-topic". root@work:/usr/local/kafka/bin# ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic items-topic --from-beginning On the above we have created an items-topic from Kafka cli, now we are going to send some JSON messages to items-topic using KafkaTemplate through Spring Boot application. Project Structure: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> </dependencies> This class represents a JSON message to sending messages to Kafka topic. package com.onlinetutorialspoint.model; public class Item { private int id; private String name; private String category; public Item(int id, String name, String category) { this.id = id; this.name = name; this.category = category; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } } Since we are going to send JSON messages to Kafka topic, we have to configure the KafkaProducerFactory with JsonSerializer class. The default configuration for KafkaProducerFactory is StringSerializer, so we don’t have to configure this to send simple messages to Kafka topic. package com.onlinetutorialspoint.config; import com.onlinetutorialspoint.model.Item; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; import org.springframework.kafka.support.serializer.JsonSerializer; import java.util.HashMap; import java.util.Map; @Configuration public class KafkaConfig { @Bean public ProducerFactory<String,Item> producerFactory(){ Map<String,Object> config = new HashMap<>(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory(config); } @Bean public KafkaTemplate<String, Item> kafkaTemplate(){ return new KafkaTemplate<String, Item>(producerFactory()); } } ProducerConfig.BOOTSTRAP_SERVERS_CONFIG tells Kafka IP address and port “127.0.0.1:9092. Currently, I am going to use my local Kafka so that it 127.0.0.1 and the port is 9092. Note: You can find this config information at Kafka/config/server.properties file. ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG tells the type of key which we are going to send messages to a Kafka topic StringSerializer.class. ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, tells the type of value which we are going to send messages to a Kafka topic JsonSerializer.class It a simple rest client having one post method which will send JSON message to Kafka topic (items-topic) using KafkaTemplate. package com.onlinetutorialspoint; import com.onlinetutorialspoint.model.Item; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("producer") public class ItemController { @Autowired KafkaTemplate<String, Item> KafkaJsontemplate; String TOPIC_NAME = "items-topic"; @PostMapping(value = "/postItem",consumes = {"application/json"},produces = {"application/json"}) public String postJsonMessage(@RequestBody Item item){ KafkaJsontemplate.send(TOPIC_NAME,new Item(1,"Lenovo","Laptop")); return "Message published successfully"; } } package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootKafkaJsonMessagesApplication { public static void main(String[] args) { SpringApplication.run(SpringBootKafkaJsonMessagesApplication.class, args); } } $mvn clean install $mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.3.RELEASE) 2019-03-29 02:30:43.248 INFO 19700 --- [ main] o.SpringBootKafkaJsonMessagesApplication : Starting SpringBootKafkaJsonMessagesApplication on work with PID 19700 (/home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-JSON-Messages-Producer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-JSON-Messages-Producer) 2019-03-29 02:30:43.269 INFO 19700 --- [ main] o.SpringBootKafkaJsonMessagesApplication : No active profile set, falling back to default profiles: default ..... ..... Access the application from the postman and make a post request. We can see our JSON message on the Kafka consumer console whether it consumed or not. Apache Kafka Reference Sending simple messages to Kafka topic (Kafka Producer Example) Happy Learning 🙂 SpringBoot-Kafka-JSON-Messages-Producer File size: 114 KB Downloads: 1284 Spring Boot Kafka Consume JSON Messages Example Spring Boot Kafka Producer Example How to install Apache Kafka on Ubuntu 18.04 Install Apache Kafka on Windows 10 Spring Boot RabbitMQ Message Publishing Example External Apache ActiveMQ Spring Boot Example Spring Boot How to change the Tomcat to Jetty Server How To Change Spring Boot Context Path How to set Spring Boot SetTimeZone How to change Spring Boot Tomcat Port Number Spring Boot RabbitMQ Consumer Messages Example How to use Spring Boot Random Port Simple Spring Boot Example MicroServices Spring Boot Eureka Server Example Spring Boot In Memory Basic Authentication Security Spring Boot Kafka Consume JSON Messages Example Spring Boot Kafka Producer Example How to install Apache Kafka on Ubuntu 18.04 Install Apache Kafka on Windows 10 Spring Boot RabbitMQ Message Publishing Example External Apache ActiveMQ Spring Boot Example Spring Boot How to change the Tomcat to Jetty Server How To Change Spring Boot Context Path How to set Spring Boot SetTimeZone How to change Spring Boot Tomcat Port Number Spring Boot RabbitMQ Consumer Messages Example How to use Spring Boot Random Port Simple Spring Boot Example MicroServices Spring Boot Eureka Server Example Spring Boot In Memory Basic Authentication Security Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 495, "s": 398, "text": "Here we will see how to send Spring Boot Kafka JSON Message to Kafka Topic using Kafka Template." }, { "code": null, "e": 659, "s": 495, "text": "We can publish the JSON messages to Apache Kafka through spring boot application, in the previous article we have seen how to send simple string messages to Kafka." }, { "code": null, "e": 685, "s": 659, "text": "Spring Boot 2.1.3.RELEASE" }, { "code": null, "e": 698, "s": 685, "text": "Spring Kafka" }, { "code": null, "e": 716, "s": 698, "text": "Apache Kafka 2.11" }, { "code": null, "e": 723, "s": 716, "text": "Java 8" }, { "code": null, "e": 729, "s": 723, "text": "Maven" }, { "code": null, "e": 928, "s": 729, "text": "To run the application, you have to have Apache Kafka installed on your machine. I have provided a couple of articles which helps you to install Apache Kafka on Windows and Ubuntu operating systems." }, { "code": null, "e": 980, "s": 928, "text": "Install Apache Kafka on Windows 10 Operating System" }, { "code": null, "e": 1028, "s": 980, "text": "Install Apache Kafka On Ubuntu Operating System" }, { "code": null, "e": 1135, "s": 1028, "text": "After successful installation, start the zookeeper, Kafka servers to connect from spring boot application." }, { "code": null, "e": 1877, "s": 1135, "text": "root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties \n[2019-03-28 00:22:52,195] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)\n[2019-03-28 00:22:52,210] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-28 00:22:52,210] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-28 00:22:52,211] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-28 00:22:52,211] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain)" }, { "code": null, "e": 2562, "s": 1877, "text": "root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties \n[2019-03-28 00:24:08,203] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)\n[2019-03-28 00:24:09,146] INFO starting (kafka.server.KafkaServer)\n[2019-03-28 00:24:09,147] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer)\n[2019-03-28 00:24:09,219] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient)\n[2019-03-28 00:24:09,229] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper)" }, { "code": null, "e": 2735, "s": 2562, "text": "root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic items-topic\nCreated topic \"items-topic\"." }, { "code": null, "e": 2866, "s": 2735, "text": "root@work:/usr/local/kafka/bin# ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic items-topic --from-beginning" }, { "code": null, "e": 3038, "s": 2866, "text": "On the above we have created an items-topic from Kafka cli, now we are going to send some JSON messages to items-topic using KafkaTemplate through Spring Boot application." }, { "code": null, "e": 3057, "s": 3038, "text": "Project Structure:" }, { "code": null, "e": 3342, "s": 3057, "text": "<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka</artifactId>\n </dependency>\n</dependencies>" }, { "code": null, "e": 3415, "s": 3342, "text": "This class represents a JSON message to sending messages to Kafka topic." }, { "code": null, "e": 4094, "s": 3415, "text": "package com.onlinetutorialspoint.model;\n\npublic class Item {\n private int id;\n private String name;\n private String category;\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n" }, { "code": null, "e": 4371, "s": 4094, "text": "Since we are going to send JSON messages to Kafka topic, we have to configure the KafkaProducerFactory with JsonSerializer class. The default configuration for KafkaProducerFactory is StringSerializer, so we don’t have to configure this to send simple messages to Kafka topic." }, { "code": null, "e": 5607, "s": 4371, "text": "package com.onlinetutorialspoint.config;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.apache.kafka.clients.producer.ProducerConfig;\nimport org.apache.kafka.common.serialization.StringSerializer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.kafka.core.DefaultKafkaProducerFactory;\nimport org.springframework.kafka.core.KafkaTemplate;\nimport org.springframework.kafka.core.ProducerFactory;\nimport org.springframework.kafka.support.serializer.JsonSerializer;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n@Configuration\npublic class KafkaConfig {\n\n @Bean\n public ProducerFactory<String,Item> producerFactory(){\n Map<String,Object> config = new HashMap<>();\n config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,\"127.0.0.1:9092\");\n config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);\n config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);\n return new DefaultKafkaProducerFactory(config);\n }\n\n @Bean\n public KafkaTemplate<String, Item> kafkaTemplate(){\n return new KafkaTemplate<String, Item>(producerFactory());\n }\n}\n" }, { "code": null, "e": 5783, "s": 5607, "text": "ProducerConfig.BOOTSTRAP_SERVERS_CONFIG tells Kafka IP address and port “127.0.0.1:9092. Currently, I am going to use my local Kafka so that it 127.0.0.1 and the port is 9092." }, { "code": null, "e": 5866, "s": 5783, "text": "Note: You can find this config information at Kafka/config/server.properties file." }, { "code": null, "e": 6008, "s": 5866, "text": "ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG tells the type of key which we are going to send messages to a Kafka topic StringSerializer.class." }, { "code": null, "e": 6152, "s": 6008, "text": "ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, tells the type of value which we are going to send messages to a Kafka topic JsonSerializer.class" }, { "code": null, "e": 6278, "s": 6152, "text": "It a simple rest client having one post method which will send JSON message to Kafka topic (items-topic) using KafkaTemplate." }, { "code": null, "e": 6998, "s": 6278, "text": "package com.onlinetutorialspoint;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.kafka.core.KafkaTemplate;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\n@RequestMapping(\"producer\")\npublic class ItemController {\n\n @Autowired\n KafkaTemplate<String, Item> KafkaJsontemplate;\n String TOPIC_NAME = \"items-topic\";\n\n @PostMapping(value = \"/postItem\",consumes = {\"application/json\"},produces = {\"application/json\"})\n public String postJsonMessage(@RequestBody Item item){\n KafkaJsontemplate.send(TOPIC_NAME,new Item(1,\"Lenovo\",\"Laptop\"));\n return \"Message published successfully\";\n }\n}\n" }, { "code": null, "e": 7362, "s": 6998, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootKafkaJsonMessagesApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootKafkaJsonMessagesApplication.class, args);\n }\n\n}\n" }, { "code": null, "e": 8248, "s": 7362, "text": "$mvn clean install\n$mvn spring-boot:run\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.1.3.RELEASE)\n\n2019-03-29 02:30:43.248 INFO 19700 --- [ main] o.SpringBootKafkaJsonMessagesApplication : Starting SpringBootKafkaJsonMessagesApplication on work with PID 19700 (/home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-JSON-Messages-Producer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-JSON-Messages-Producer)\n2019-03-29 02:30:43.269 INFO 19700 --- [ main] o.SpringBootKafkaJsonMessagesApplication : No active profile set, falling back to default profiles: default\n.....\n....." }, { "code": null, "e": 8313, "s": 8248, "text": "Access the application from the postman and make a post request." }, { "code": null, "e": 8399, "s": 8313, "text": "We can see our JSON message on the Kafka consumer console whether it consumed or not." }, { "code": null, "e": 8422, "s": 8399, "text": "Apache Kafka Reference" }, { "code": null, "e": 8486, "s": 8422, "text": "Sending simple messages to Kafka topic (Kafka Producer Example)" }, { "code": null, "e": 8503, "s": 8486, "text": "Happy Learning 🙂" }, { "code": null, "e": 8581, "s": 8503, "text": "\n\nSpringBoot-Kafka-JSON-Messages-Producer\n\nFile size: 114 KB\nDownloads: 1284\n" }, { "code": null, "e": 9219, "s": 8581, "text": "\nSpring Boot Kafka Consume JSON Messages Example\nSpring Boot Kafka Producer Example\nHow to install Apache Kafka on Ubuntu 18.04\nInstall Apache Kafka on Windows 10\nSpring Boot RabbitMQ Message Publishing Example\nExternal Apache ActiveMQ Spring Boot Example\nSpring Boot How to change the Tomcat to Jetty Server\nHow To Change Spring Boot Context Path\nHow to set Spring Boot SetTimeZone\nHow to change Spring Boot Tomcat Port Number\nSpring Boot RabbitMQ Consumer Messages Example\nHow to use Spring Boot Random Port\nSimple Spring Boot Example\nMicroServices Spring Boot Eureka Server Example\nSpring Boot In Memory Basic Authentication Security\n" }, { "code": null, "e": 9267, "s": 9219, "text": "Spring Boot Kafka Consume JSON Messages Example" }, { "code": null, "e": 9302, "s": 9267, "text": "Spring Boot Kafka Producer Example" }, { "code": null, "e": 9346, "s": 9302, "text": "How to install Apache Kafka on Ubuntu 18.04" }, { "code": null, "e": 9381, "s": 9346, "text": "Install Apache Kafka on Windows 10" }, { "code": null, "e": 9429, "s": 9381, "text": "Spring Boot RabbitMQ Message Publishing Example" }, { "code": null, "e": 9474, "s": 9429, "text": "External Apache ActiveMQ Spring Boot Example" }, { "code": null, "e": 9527, "s": 9474, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 9566, "s": 9527, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 9601, "s": 9566, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 9646, "s": 9601, "text": "How to change Spring Boot Tomcat Port Number" }, { "code": null, "e": 9693, "s": 9646, "text": "Spring Boot RabbitMQ Consumer Messages Example" }, { "code": null, "e": 9728, "s": 9693, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 9755, "s": 9728, "text": "Simple Spring Boot Example" }, { "code": null, "e": 9803, "s": 9755, "text": "MicroServices Spring Boot Eureka Server Example" }, { "code": null, "e": 9855, "s": 9803, "text": "Spring Boot In Memory Basic Authentication Security" }, { "code": null, "e": 9861, "s": 9859, "text": "Δ" }, { "code": null, "e": 9888, "s": 9861, "text": " Spring Boot – Hello World" }, { "code": null, "e": 9915, "s": 9888, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 9949, "s": 9915, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 9990, "s": 9949, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 10035, "s": 9990, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 10073, "s": 10035, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 10107, "s": 10073, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 10138, "s": 10107, "text": " Spring Boot – Properties File" }, { "code": null, "e": 10172, "s": 10138, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 10205, "s": 10172, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 10238, "s": 10205, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 10278, "s": 10238, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 10303, "s": 10278, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 10334, "s": 10303, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 10358, "s": 10334, "text": " Spring Boot – Actuator" }, { "code": null, "e": 10404, "s": 10358, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 10427, "s": 10404, "text": " Spring Boot – Swagger" }, { "code": null, "e": 10454, "s": 10427, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 10500, "s": 10454, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 10540, "s": 10500, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 10569, "s": 10540, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 10603, "s": 10569, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 10633, "s": 10603, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 10669, "s": 10633, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 10702, "s": 10669, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 10735, "s": 10702, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 10779, "s": 10735, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 10813, "s": 10779, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 10845, "s": 10813, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 10873, "s": 10845, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 10904, "s": 10873, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 10945, "s": 10904, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 10979, "s": 10945, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 11004, "s": 10979, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 11038, "s": 11004, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 11074, "s": 11038, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 11120, "s": 11074, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 11171, "s": 11120, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 11213, "s": 11171, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 11244, "s": 11213, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 11267, "s": 11244, "text": " Spring Boot – EhCache" }, { "code": null, "e": 11297, "s": 11267, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 11327, "s": 11297, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 11376, "s": 11327, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 11410, "s": 11376, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 11443, "s": 11410, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 11472, "s": 11443, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 11504, "s": 11472, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 11541, "s": 11504, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 11570, "s": 11541, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 11599, "s": 11570, "text": " Spring Boot – MockMvc JUnit" } ]
Java Generics - Bounded Type Parameters
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound. Following example illustrates how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects − public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf("Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum("pear", "apple", "orange")); } } This will produce the following result − Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2916, "s": 2640, "text": "There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for." }, { "code": null, "e": 3047, "s": 2916, "text": "To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound." }, { "code": null, "e": 3276, "s": 3047, "text": "Following example illustrates how extends is used in a general sense to mean either \"extends\" (as in classes) or \"implements\" (as in interfaces). This example is Generic method to return the largest of three Comparable objects −" }, { "code": null, "e": 4151, "s": 3276, "text": "public class MaximumTest {\n // determines the largest of three Comparable objects\n \n public static <T extends Comparable<T>> T maximum(T x, T y, T z) {\n T max = x; // assume x is initially the largest\n \n if(y.compareTo(max) > 0) {\n max = y; // y is the largest so far\n }\n \n if(z.compareTo(max) > 0) {\n max = z; // z is the largest now \n }\n return max; // returns the largest object \n }\n \n public static void main(String args[]) {\n System.out.printf(\"Max of %d, %d and %d is %d\\n\\n\", \n 3, 4, 5, maximum( 3, 4, 5 ));\n\n System.out.printf(\"Max of %.1f,%.1f and %.1f is %.1f\\n\\n\",\n 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));\n\n System.out.printf(\"Max of %s, %s and %s is %s\\n\",\"pear\",\n \"apple\", \"orange\", maximum(\"pear\", \"apple\", \"orange\"));\n }\n}" }, { "code": null, "e": 4192, "s": 4151, "text": "This will produce the following result −" }, { "code": null, "e": 4286, "s": 4192, "text": "Max of 3, 4 and 5 is 5\n\nMax of 6.6,8.8 and 7.7 is 8.8\n\nMax of pear, apple and orange is pear\n" }, { "code": null, "e": 4319, "s": 4286, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4335, "s": 4319, "text": " Malhar Lathkar" }, { "code": null, "e": 4368, "s": 4335, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4384, "s": 4368, "text": " Malhar Lathkar" }, { "code": null, "e": 4419, "s": 4384, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4433, "s": 4419, "text": " Anadi Sharma" }, { "code": null, "e": 4467, "s": 4433, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4481, "s": 4467, "text": " Tushar Kale" }, { "code": null, "e": 4518, "s": 4481, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4533, "s": 4518, "text": " Monica Mittal" }, { "code": null, "e": 4566, "s": 4533, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4585, "s": 4566, "text": " Arnab Chakraborty" }, { "code": null, "e": 4592, "s": 4585, "text": " Print" }, { "code": null, "e": 4603, "s": 4592, "text": " Add Notes" } ]
C/C++ Tricky Programs
Here are 10 tricky programs that will test your programming basics. In C++ programming language, we use quotes to denote the start and end of the text is to be printed. So, printing quotes “ needs a special escape sequence. So, we will use the \” to print quotes in c++. Live Demo #include<iostream> using namespace std; int main() { cout<<"\"Tutorials Point \""; return 0; } "Tutorials Point " In programming to iterate over the same block of code multiple times, there are a few methods. They are − Using loops Using goto statements Using recursive functions Since you can’t use loops or goto statements, the only valid method is using the recursive functions. Let’s see how we can use the recursive calls to print numbers from 1 to 10. Live Demo #include <stdio.h> void printNumber(int count){ printf("%d\n", count ); count+=1; if(count<=10) printNumber(count); } int main(){ printNumber(1); return 0; } 1 2 3 4 5 6 7 8 9 10 To check for equality of two numbers we can use the bitwise XOR operator (^). If two numbers are equal then the bitwise XOR of these numbers is 0. Now, let’s implement this concept in a program. Live Demo #include<iostream> using namespace std; int main(){ int a = 132; int b = 132; if ( (a ^ b) ) cout<<"a is not equal to b"; else cout<<"a is else to b"; return 0; } a is equal to b In c/c++ programming language there are methods to print something without using a semicolon. We can do this by using the return type of the output method, printf. The printf method in c++ returns the number of characters printed to the output screen. We can use and the conditional statement that can execute without a semicolon. Live Demo #include <stdio.h> int main(){ if(printf("Hello ")) return 0; } Hello To find the maximum and a minimum number of the two numbers that are defined without using a comparison operator we will make use of the abs method, and passing the difference of the two numbers to it. It will return the positive difference between the numbers and we will and subtract this absolute difference to find the max and min of the two given numbers. Live Demo #include<iostream> using namespace std; int main (){ int x = 15, y = 20; cout<<"The numbers are x = "<<x<<"and y = "<<y<<endl; cout<<"The max of the numbers is "<<((x + y) + abs(x - y)) / 2<<endl; cout<<"The min of the numbers is "<<((x + y) - abs(x - y)) / 2<<endl; return 0; } The numbers are x = 15and y = 20 The max of the numbers is 20 The min of the numbers is 15 To print the source code of the program as the output of the same program is a bit of a tricky question and needs quite a good understanding of the programming language to do. In this program, we will use the concepts of file handling and open the same file which we are using to write our code and then print the content of the file. #include <stdio.h> int main(void){ FILE *program; char ch; program = fopen(__FILE__, "r"); do{ ch=fgetc(program); printf("%c", ch); } while(ch!=EOF); fclose(program); return 0; } A sum of two numbers can be found without using the + operator by using the - operator multiple times in the code. The below program shows how to. Live Demo #include<iostream> using namespace std; int main(){ int x = 5; int y = 5; int sum = x - (-y); cout<<"The numbers are x = "<<x<<" y = "<<y<<endl; cout<<"Their sum = "<<sum; return 0; } The numbers are x = 5 y = 5 Their sum = 10 To check if the given number is even or not, we can use bitwise operators. The bitwise & operator along with 0x01 will check for the bit at the 0th position in the number. If the bit at 0th position is 1 then the number is odd otherwise it is even. Live Demo #include<iostream> using namespace std; int main(){ int a = 154; if(a & 0x01) { cout<<a<<" is an odd number"; } else{ cout<<a<<" is an even number"; } printf("\n"); return 0; } 154 is an even number To divide a number by 4 without using a divide operator, we can use the right shift operator >> that shifts the last bit. Live Demo #include<iostream> using namespace std; int main(){ int n = 128; cout<<n<<"divided by 4 = "; n = n >> 2; cout<< n; return 0; } 128 divided by 4 = 32 Calculating recursive sum by adding all digits of the number and then see if it is single digit then stop otherwise recalculate the sum until the sum becomes single digit. Live Demo #include <iostream> using namespace std; int main() { int a = 534; int sum; if(a) sum = a % 9 == 0 ? 9 : a % 9 ; else sum = 0; cout<<"The final sum is "<<sum; return 0; } The final sum is 3
[ { "code": null, "e": 1130, "s": 1062, "text": "Here are 10 tricky programs that will test your programming basics." }, { "code": null, "e": 1333, "s": 1130, "text": "In C++ programming language, we use quotes to denote the start and end of the text is to be printed. So, printing quotes “ needs a special escape sequence. So, we will use the \\” to print quotes in c++." }, { "code": null, "e": 1344, "s": 1333, "text": " Live Demo" }, { "code": null, "e": 1445, "s": 1344, "text": "#include<iostream>\nusing namespace std;\nint main() {\n cout<<\"\\\"Tutorials Point \\\"\";\n return 0;\n}" }, { "code": null, "e": 1464, "s": 1445, "text": "\"Tutorials Point \"" }, { "code": null, "e": 1570, "s": 1464, "text": "In programming to iterate over the same block of code multiple times, there are a few methods. They are −" }, { "code": null, "e": 1582, "s": 1570, "text": "Using loops" }, { "code": null, "e": 1604, "s": 1582, "text": "Using goto statements" }, { "code": null, "e": 1630, "s": 1604, "text": "Using recursive functions" }, { "code": null, "e": 1808, "s": 1630, "text": "Since you can’t use loops or goto statements, the only valid method is using the recursive functions. Let’s see how we can use the recursive calls to print numbers from 1 to 10." }, { "code": null, "e": 1819, "s": 1808, "text": " Live Demo" }, { "code": null, "e": 1998, "s": 1819, "text": "#include <stdio.h>\nvoid printNumber(int count){\n printf(\"%d\\n\", count );\n count+=1;\n if(count<=10)\n printNumber(count);\n}\nint main(){\n printNumber(1);\n return 0;\n}" }, { "code": null, "e": 2019, "s": 1998, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 2214, "s": 2019, "text": "To check for equality of two numbers we can use the bitwise XOR operator (^). If two numbers are equal then the bitwise XOR of these numbers is 0. Now, let’s implement this concept in a program." }, { "code": null, "e": 2225, "s": 2214, "text": " Live Demo" }, { "code": null, "e": 2418, "s": 2225, "text": "#include<iostream>\nusing namespace std;\nint main(){\n int a = 132;\n int b = 132;\n if ( (a ^ b) )\n cout<<\"a is not equal to b\";\n else\n cout<<\"a is else to b\";\n return 0;\n}" }, { "code": null, "e": 2434, "s": 2418, "text": "a is equal to b" }, { "code": null, "e": 2765, "s": 2434, "text": "In c/c++ programming language there are methods to print something without using a semicolon. We can do this by using the return type of the output method, printf. The printf method in c++ returns the number of characters printed to the output screen. We can use and the conditional statement that can execute without a semicolon." }, { "code": null, "e": 2776, "s": 2765, "text": " Live Demo" }, { "code": null, "e": 2846, "s": 2776, "text": "#include <stdio.h>\nint main(){\n if(printf(\"Hello \"))\n return 0;\n}" }, { "code": null, "e": 2852, "s": 2846, "text": "Hello" }, { "code": null, "e": 3213, "s": 2852, "text": "To find the maximum and a minimum number of the two numbers that are defined without using a comparison operator we will make use of the abs method, and passing the difference of the two numbers to it. It will return the positive difference between the numbers and we will and subtract this absolute difference to find the max and min of the two given numbers." }, { "code": null, "e": 3224, "s": 3213, "text": " Live Demo" }, { "code": null, "e": 3518, "s": 3224, "text": "#include<iostream>\nusing namespace std;\nint main (){\n int x = 15, y = 20;\n cout<<\"The numbers are x = \"<<x<<\"and y = \"<<y<<endl;\n cout<<\"The max of the numbers is \"<<((x + y) + abs(x - y)) / 2<<endl;\n cout<<\"The min of the numbers is \"<<((x + y) - abs(x - y)) / 2<<endl;\n return 0;\n}" }, { "code": null, "e": 3609, "s": 3518, "text": "The numbers are x = 15and y = 20\nThe max of the numbers is 20\nThe min of the numbers is 15" }, { "code": null, "e": 3785, "s": 3609, "text": "To print the source code of the program as the output of the same program is a bit of a tricky question and needs quite a good understanding of the programming language to do." }, { "code": null, "e": 3944, "s": 3785, "text": "In this program, we will use the concepts of file handling and open the same file which we are using to write our code and then print the content of the file." }, { "code": null, "e": 4162, "s": 3944, "text": "#include <stdio.h>\nint main(void){\n FILE *program;\n char ch;\n program = fopen(__FILE__, \"r\");\n do{\n ch=fgetc(program);\n printf(\"%c\", ch);\n }\n while(ch!=EOF);\n fclose(program);\n return 0;\n}" }, { "code": null, "e": 4309, "s": 4162, "text": "A sum of two numbers can be found without using the + operator by using the - operator multiple times in the code. The below program shows how to." }, { "code": null, "e": 4320, "s": 4309, "text": " Live Demo" }, { "code": null, "e": 4522, "s": 4320, "text": "#include<iostream>\nusing namespace std;\nint main(){\n int x = 5;\n int y = 5;\n int sum = x - (-y);\n cout<<\"The numbers are x = \"<<x<<\" y = \"<<y<<endl;\n cout<<\"Their sum = \"<<sum;\n return 0;\n}" }, { "code": null, "e": 4565, "s": 4522, "text": "The numbers are x = 5 y = 5\nTheir sum = 10" }, { "code": null, "e": 4814, "s": 4565, "text": "To check if the given number is even or not, we can use bitwise operators. The bitwise & operator along with 0x01 will check for the bit at the 0th position in the number. If the bit at 0th position is 1 then the number is odd otherwise it is even." }, { "code": null, "e": 4825, "s": 4814, "text": " Live Demo" }, { "code": null, "e": 5032, "s": 4825, "text": "#include<iostream>\nusing namespace std;\nint main(){\n int a = 154;\n if(a & 0x01) {\n cout<<a<<\" is an odd number\";\n } else{\n cout<<a<<\" is an even number\";\n }\n printf(\"\\n\");\n return 0;\n}" }, { "code": null, "e": 5054, "s": 5032, "text": "154 is an even number" }, { "code": null, "e": 5176, "s": 5054, "text": "To divide a number by 4 without using a divide operator, we can use the right shift operator >> that shifts the last bit." }, { "code": null, "e": 5187, "s": 5176, "text": " Live Demo" }, { "code": null, "e": 5329, "s": 5187, "text": "#include<iostream>\nusing namespace std;\nint main(){\n int n = 128;\n cout<<n<<\"divided by 4 = \";\n n = n >> 2;\n cout<< n;\n return 0;\n}" }, { "code": null, "e": 5351, "s": 5329, "text": "128 divided by 4 = 32" }, { "code": null, "e": 5523, "s": 5351, "text": "Calculating recursive sum by adding all digits of the number and then see if it is single digit then stop otherwise recalculate the sum until the sum becomes single digit." }, { "code": null, "e": 5534, "s": 5523, "text": " Live Demo" }, { "code": null, "e": 5735, "s": 5534, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 534;\n int sum;\n if(a)\n sum = a % 9 == 0 ? 9 : a % 9 ;\n else\n sum = 0;\n cout<<\"The final sum is \"<<sum;\n return 0;\n}" }, { "code": null, "e": 5754, "s": 5735, "text": "The final sum is 3" } ]
Browsable API in Django REST Framework - GeeksforGeeks
16 Mar, 2021 The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header. It helps us to use web browsers to surf through the API and can make different HTTP requests. In this section, we will work with the browsable API feature in the Django REST API framework. To check how to setup Django RESt Framework and create a API visit – How to Create a basic API using Django Rest Framework ? Let’s create models, serializers, and views required for our application robots. In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create the following models: RobotCategory (Robot Categories) Manufacturer (Manufacturer Details) Robot (Robot Details) The RobotCategory model requires: Robot category name The Manufacturer model requires: Manufacturer name The Robot model requires: Robot name A foreign key to the RobotCategory model A foreign key to the Manufacturer model Currency Price Manufacturing date Let’s look into the HTTP verb, scope semantics in our robots Restful web service. Let’s create the models for the robot category, manufacturer, robot, and their relationships. You can add the below code in the models.py file. Python3 from django.db import models class RobotCategory(models.Model): name = models.CharField(max_length=150, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Manufacturer(models.Model): name = models.CharField(max_length=150, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Robot(models.Model): CURRENCY_CHOICES = ( ('INR', 'Indian Rupee'), ('USD', 'US Dollar'), ('EUR', 'Euro'), ) name = models.CharField(max_length=150, unique=True) robot_category = models.ForeignKey( RobotCategory, related_name='robots', on_delete=models.CASCADE) manufacturer = models.ForeignKey( Manufacturer, related_name='robots', on_delete=models.CASCADE) currency = models.CharField( max_length=3, choices= CURRENCY_CHOICES, default='INR') price = models.IntegerField() manufacturing_date = models.DateTimeField() class Meta: ordering = ('name',) def __str__(self): return self.name Here we have three classes that are subclasses of the django.db.models.Model class: RobotCategory Manufacturer Robot The Robot class holds a many-to-one relationship to the RobotCategory model and Manufacturer model. This relationship is achieved by making use of the django.db.models.ForeignKey class. The code as follows: robot_category = models.ForeignKey( RobotCategory, related_name='robots', on_delete=models.CASCADE) manufacturer = models.ForeignKey( Manufacturer, related_name='robots', on_delete=models.CASCADE) The related_name argument creates a reverse relationship. Here the value ‘robots’ in related_name creates a reverse relationship from RobotCategory to Robot and Manufacturer to Robot. This facilitates fetching all the robots that belong to a robot category and also based on the manufacturer. Next, you can perform the migration process and apply all generated migration. You can use the below commands python manage.py makemigrations python manage.py migrate Now, we need to serialize the RobotCategory, Manufacturer, and Robot instances. Here, we will use HyperlinkedModelSerializer to deal with the model relationships. You can check DRF Serializer Relations topic to understand in detail. Python3 from rest_framework import serializersfrom robots.models import RobotCategory, Manufacturer, Robot class RobotCategorySerializer(serializers.HyperlinkedModelSerializer): robots = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='robot-detail') class Meta: model = RobotCategory fields = '__all__' class ManufacturerSerializer(serializers.HyperlinkedModelSerializer): robots = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='robot-detail') class Meta: model = Manufacturer fields = '__all__' class RobotSerializer(serializers.HyperlinkedModelSerializer): robot_category = serializers.SlugRelatedField( queryset=RobotCategory.objects.all(), slug_field='name') manufacturer = serializers.SlugRelatedField( queryset=Manufacturer.objects.all(), slug_field='name') currency = serializers.ChoiceField( choices=Robot.CURRENCY_CHOICES) currency_name = serializers.CharField( source='get_currency_display', read_only=True) class Meta: model = Robot fields = '__all__' The RobotCategorySerializer and ManufacturerSerializer class are subclasses of HyperlinkedModelSerializer class, and the reverse relationship (RobotCategory to Robot and Manufacturer to Robot) is represented using HyperlinkedRelatedField with many and read_only attributes set to True. The view_name — robot-detail — allows the browsable API feature to provide a click facility for the user, to render the hyperlink. The RobotSerializer class is also a subclass of HyperlinkedModelSerializer class. The RobotSerializer class declares two attributes – robot_category and manufacturer – that holds an instance of serializers.SlugRelatedField. A SlugRelated Field represents a relationship by a unique slug attribute. Let’s make use of generic class-based views provided by Django REST Framework to process the HTTP requests and to provide the appropriate HTTP responses. You can check DRF Class based views for a detailed explanation. Python3 from django.shortcuts import render from rest_framework import genericsfrom rest_framework.response import Responsefrom rest_framework.reverse import reverse from robots.models import RobotCategory, Manufacturer, Robotfrom robots.serializers import RobotCategorySerializer, \ ManufacturerSerializer, RobotSerializer class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) }) class RobotCategoryList(generics.ListCreateAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer name = 'robotcategory-list' class RobotCategoryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer name = 'robotcategory-detail' class ManufacturerList(generics.ListCreateAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name= 'manufacturer-list' class ManufacturerDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name = 'manufacturer-detail' class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' Here, our view classes import from rest_framework.generics and we took advantage of two generic class-based views — ListCreateAPIView and RetrieveUpdateDestroyAPIView. You can notice an ApiRoot class, a subclass of the generics.GenericAPIView, creates an endpoint for the root of our web service. It facilitates browsing the resources with the browsable API feature. class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) }) The get method returns a Response object (as a key/value pair of strings) that has the descriptive name for the view and its URL. Go to the apps (robots) folder and create a new file named urls.py file. You can add the below code: Python3 from django.urls import pathfrom robots import views urlpatterns = [ path('robocategory/', views.RobotCategoryList.as_view(), name='robotcategory-list'), path('robocategory/<int:pk>/', views.RobotCategoryDetail.as_view(), name='robotcategory-detail'), path('manufacturer/', views.ManufacturerList.as_view(), name='manufacturer-list'), path('manufacturer/<int:pk>/', views.ManufacturerDetail.as_view(), name='manufacturer-detail'), path('robot/', views.RobotList.as_view(), name='robot-list'), path('robot/<int:pk>/', views.RobotDetail.as_view(), name='robot-detail'), path('', views.ApiRoot.as_view(), name=views.ApiRoot.name)] It defines the URL pattern that has to be matched in the request to execute the particular method for a class-based view defined in the views.py file. Now we have to set the root URL configuration. You can add the below code: Python3 from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('', include('robots.urls')),] Let’s compose and send HTTP requests to generate text/html content in the response. The RESTFul web service uses the BrowsableAPIRenderer class to generate HTML content. The HTTPie command to accept text/html as follows: http -v :8000/robot/ “Accept:text/html” Sharing the command prompt screenshot for your reference Before making use of browsable API, let’s create a new entry for Robot Category, Manufacturer, and Robot using the HTTPie command. The command as follows: http POST :8000/robocategory/ name=”Articulated Robots” http POST :8000/manufacturer/ name=”Fanuc” http POST :8000/robot/ name=”FANUC M-710ic/50′′ robot_category=”Articulated Robots” manufacturer=”Fanuc” currency=”USD” price=37000 manufacturing_date=”2019-10-12 00:00:00+00:00′′ Now, let’s browse the ‘robots’ Restful web service using a browser. You can use the below URL. http://localhost:8000/ Sharing the screenshot of the browser for your reference You can click the link that corresponds to robot-categories, manufacturers, and robots and check the data. Sharing the browser screenshot that displays the result of robots (http://localhost:8000/robot/) Next, let’s create a new robot category. You can browse the below link and scroll down. http://localhost:8000/robocategory/ Sharing the browser screenshot for your reference You can type the name of the new robot category and click the POST button. Here, it displays in HTML form. If you choose Raw data, select media type as application/json, populate the new robot category name to the name field, and click the POST button. Sharing the screenshot for your reference. Sharing the output screenshot Let’s create a new manufacturer, you can browse the below URL http://localhost:8000/manufacturer/ Sharing the browser screenshot You can type the manufacturer name (ABB) and click the POST button. The browser displays the output as shown below Finally, let’s create a new entry for the robot. You can browse the below URL and scroll down. http://localhost:8000/robot/ Let’s populate the data. Sharing the browser screenshot for your reference Here, you can notice that the Robot category, Manufacture, and Currency are dropdown field. After populating the entries, you can click the POST button. Sharing below the screenshot of the displayed output. Let’s edit the price of the robot that has a pk value 2. You can browse the below URL and scroll down. http://localhost:8000/robot/2/ Sharing the browser screenshot. You can change the price to 27000 and click the PUT button. Sharing the screenshot of the output. You can create a new test entry and browse the URL with the pk value. http://localhost:8000/robot/2/ You can notice a DELETE button. Sharing the browser screenshot below: On clicking the Delete button, the browser confirms the same. You can click the Delete button in the confirmation window. Sharing the screenshot below. If the deletion is successful, it displays the below output. From this section, we understood how to make use of the browsable API feature in the Django REST API framework. We composed and sent HTTP requests that generate text/html content as a response and also analyzed the response in a web browser. Django-REST Python Django 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 ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists sum() function in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Print lists in Python (4 Different Ways)
[ { "code": null, "e": 24346, "s": 24318, "text": "\n16 Mar, 2021" }, { "code": null, "e": 24816, "s": 24346, "text": "The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header. It helps us to use web browsers to surf through the API and can make different HTTP requests. In this section, we will work with the browsable API feature in the Django REST API framework. " }, { "code": null, "e": 24941, "s": 24816, "text": "To check how to setup Django RESt Framework and create a API visit – How to Create a basic API using Django Rest Framework ?" }, { "code": null, "e": 25022, "s": 24941, "text": "Let’s create models, serializers, and views required for our application robots." }, { "code": null, "e": 25258, "s": 25022, "text": "In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create the following models:" }, { "code": null, "e": 25291, "s": 25258, "text": "RobotCategory (Robot Categories)" }, { "code": null, "e": 25328, "s": 25291, "text": "Manufacturer (Manufacturer Details)" }, { "code": null, "e": 25350, "s": 25328, "text": "Robot (Robot Details)" }, { "code": null, "e": 25384, "s": 25350, "text": "The RobotCategory model requires:" }, { "code": null, "e": 25404, "s": 25384, "text": "Robot category name" }, { "code": null, "e": 25437, "s": 25404, "text": "The Manufacturer model requires:" }, { "code": null, "e": 25455, "s": 25437, "text": "Manufacturer name" }, { "code": null, "e": 25481, "s": 25455, "text": "The Robot model requires:" }, { "code": null, "e": 25492, "s": 25481, "text": "Robot name" }, { "code": null, "e": 25533, "s": 25492, "text": "A foreign key to the RobotCategory model" }, { "code": null, "e": 25573, "s": 25533, "text": "A foreign key to the Manufacturer model" }, { "code": null, "e": 25582, "s": 25573, "text": "Currency" }, { "code": null, "e": 25588, "s": 25582, "text": "Price" }, { "code": null, "e": 25607, "s": 25588, "text": "Manufacturing date" }, { "code": null, "e": 25689, "s": 25607, "text": "Let’s look into the HTTP verb, scope semantics in our robots Restful web service." }, { "code": null, "e": 25833, "s": 25689, "text": "Let’s create the models for the robot category, manufacturer, robot, and their relationships. You can add the below code in the models.py file." }, { "code": null, "e": 25841, "s": 25833, "text": "Python3" }, { "code": "from django.db import models class RobotCategory(models.Model): name = models.CharField(max_length=150, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Manufacturer(models.Model): name = models.CharField(max_length=150, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Robot(models.Model): CURRENCY_CHOICES = ( ('INR', 'Indian Rupee'), ('USD', 'US Dollar'), ('EUR', 'Euro'), ) name = models.CharField(max_length=150, unique=True) robot_category = models.ForeignKey( RobotCategory, related_name='robots', on_delete=models.CASCADE) manufacturer = models.ForeignKey( Manufacturer, related_name='robots', on_delete=models.CASCADE) currency = models.CharField( max_length=3, choices= CURRENCY_CHOICES, default='INR') price = models.IntegerField() manufacturing_date = models.DateTimeField() class Meta: ordering = ('name',) def __str__(self): return self.name", "e": 26966, "s": 25841, "text": null }, { "code": null, "e": 27050, "s": 26966, "text": "Here we have three classes that are subclasses of the django.db.models.Model class:" }, { "code": null, "e": 27064, "s": 27050, "text": "RobotCategory" }, { "code": null, "e": 27077, "s": 27064, "text": "Manufacturer" }, { "code": null, "e": 27083, "s": 27077, "text": "Robot" }, { "code": null, "e": 27290, "s": 27083, "text": "The Robot class holds a many-to-one relationship to the RobotCategory model and Manufacturer model. This relationship is achieved by making use of the django.db.models.ForeignKey class. The code as follows:" }, { "code": null, "e": 27543, "s": 27290, "text": " robot_category = models.ForeignKey(\n RobotCategory,\n related_name='robots',\n on_delete=models.CASCADE)\n manufacturer = models.ForeignKey(\n Manufacturer,\n related_name='robots',\n on_delete=models.CASCADE)" }, { "code": null, "e": 27836, "s": 27543, "text": "The related_name argument creates a reverse relationship. Here the value ‘robots’ in related_name creates a reverse relationship from RobotCategory to Robot and Manufacturer to Robot. This facilitates fetching all the robots that belong to a robot category and also based on the manufacturer." }, { "code": null, "e": 27946, "s": 27836, "text": "Next, you can perform the migration process and apply all generated migration. You can use the below commands" }, { "code": null, "e": 27978, "s": 27946, "text": "python manage.py makemigrations" }, { "code": null, "e": 28003, "s": 27978, "text": "python manage.py migrate" }, { "code": null, "e": 28236, "s": 28003, "text": "Now, we need to serialize the RobotCategory, Manufacturer, and Robot instances. Here, we will use HyperlinkedModelSerializer to deal with the model relationships. You can check DRF Serializer Relations topic to understand in detail." }, { "code": null, "e": 28244, "s": 28236, "text": "Python3" }, { "code": "from rest_framework import serializersfrom robots.models import RobotCategory, Manufacturer, Robot class RobotCategorySerializer(serializers.HyperlinkedModelSerializer): robots = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='robot-detail') class Meta: model = RobotCategory fields = '__all__' class ManufacturerSerializer(serializers.HyperlinkedModelSerializer): robots = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='robot-detail') class Meta: model = Manufacturer fields = '__all__' class RobotSerializer(serializers.HyperlinkedModelSerializer): robot_category = serializers.SlugRelatedField( queryset=RobotCategory.objects.all(), slug_field='name') manufacturer = serializers.SlugRelatedField( queryset=Manufacturer.objects.all(), slug_field='name') currency = serializers.ChoiceField( choices=Robot.CURRENCY_CHOICES) currency_name = serializers.CharField( source='get_currency_display', read_only=True) class Meta: model = Robot fields = '__all__'", "e": 29411, "s": 28244, "text": null }, { "code": null, "e": 29829, "s": 29411, "text": "The RobotCategorySerializer and ManufacturerSerializer class are subclasses of HyperlinkedModelSerializer class, and the reverse relationship (RobotCategory to Robot and Manufacturer to Robot) is represented using HyperlinkedRelatedField with many and read_only attributes set to True. The view_name — robot-detail — allows the browsable API feature to provide a click facility for the user, to render the hyperlink. " }, { "code": null, "e": 30127, "s": 29829, "text": "The RobotSerializer class is also a subclass of HyperlinkedModelSerializer class. The RobotSerializer class declares two attributes – robot_category and manufacturer – that holds an instance of serializers.SlugRelatedField. A SlugRelated Field represents a relationship by a unique slug attribute." }, { "code": null, "e": 30345, "s": 30127, "text": "Let’s make use of generic class-based views provided by Django REST Framework to process the HTTP requests and to provide the appropriate HTTP responses. You can check DRF Class based views for a detailed explanation." }, { "code": null, "e": 30353, "s": 30345, "text": "Python3" }, { "code": "from django.shortcuts import render from rest_framework import genericsfrom rest_framework.response import Responsefrom rest_framework.reverse import reverse from robots.models import RobotCategory, Manufacturer, Robotfrom robots.serializers import RobotCategorySerializer, \\ ManufacturerSerializer, RobotSerializer class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) }) class RobotCategoryList(generics.ListCreateAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer name = 'robotcategory-list' class RobotCategoryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer name = 'robotcategory-detail' class ManufacturerList(generics.ListCreateAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name= 'manufacturer-list' class ManufacturerDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name = 'manufacturer-detail' class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'", "e": 32058, "s": 30353, "text": null }, { "code": null, "e": 32226, "s": 32058, "text": "Here, our view classes import from rest_framework.generics and we took advantage of two generic class-based views — ListCreateAPIView and RetrieveUpdateDestroyAPIView." }, { "code": null, "e": 32426, "s": 32226, "text": "You can notice an ApiRoot class, a subclass of the generics.GenericAPIView, creates an endpoint for the root of our web service. It facilitates browsing the resources with the browsable API feature. " }, { "code": null, "e": 32801, "s": 32426, "text": "class ApiRoot(generics.GenericAPIView):\n name = 'api-root'\n def get(self, request, *args, **kwargs):\n return Response({\n 'robot-categories': reverse(RobotCategoryList.name, request=request),\n 'manufacturers': reverse(ManufacturerList.name, request=request),\n 'robots': reverse(RobotList.name, request=request)\n }) " }, { "code": null, "e": 32931, "s": 32801, "text": "The get method returns a Response object (as a key/value pair of strings) that has the descriptive name for the view and its URL." }, { "code": null, "e": 33032, "s": 32931, "text": "Go to the apps (robots) folder and create a new file named urls.py file. You can add the below code:" }, { "code": null, "e": 33040, "s": 33032, "text": "Python3" }, { "code": "from django.urls import pathfrom robots import views urlpatterns = [ path('robocategory/', views.RobotCategoryList.as_view(), name='robotcategory-list'), path('robocategory/<int:pk>/', views.RobotCategoryDetail.as_view(), name='robotcategory-detail'), path('manufacturer/', views.ManufacturerList.as_view(), name='manufacturer-list'), path('manufacturer/<int:pk>/', views.ManufacturerDetail.as_view(), name='manufacturer-detail'), path('robot/', views.RobotList.as_view(), name='robot-list'), path('robot/<int:pk>/', views.RobotDetail.as_view(), name='robot-detail'), path('', views.ApiRoot.as_view(), name=views.ApiRoot.name)]", "e": 33800, "s": 33040, "text": null }, { "code": null, "e": 34026, "s": 33800, "text": "It defines the URL pattern that has to be matched in the request to execute the particular method for a class-based view defined in the views.py file. Now we have to set the root URL configuration. You can add the below code:" }, { "code": null, "e": 34034, "s": 34026, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('', include('robots.urls')),]", "e": 34159, "s": 34034, "text": null }, { "code": null, "e": 34380, "s": 34159, "text": "Let’s compose and send HTTP requests to generate text/html content in the response. The RESTFul web service uses the BrowsableAPIRenderer class to generate HTML content. The HTTPie command to accept text/html as follows:" }, { "code": null, "e": 34420, "s": 34380, "text": "http -v :8000/robot/ “Accept:text/html”" }, { "code": null, "e": 34477, "s": 34420, "text": "Sharing the command prompt screenshot for your reference" }, { "code": null, "e": 34632, "s": 34477, "text": "Before making use of browsable API, let’s create a new entry for Robot Category, Manufacturer, and Robot using the HTTPie command. The command as follows:" }, { "code": null, "e": 34688, "s": 34632, "text": "http POST :8000/robocategory/ name=”Articulated Robots”" }, { "code": null, "e": 34731, "s": 34688, "text": "http POST :8000/manufacturer/ name=”Fanuc”" }, { "code": null, "e": 34911, "s": 34731, "text": "http POST :8000/robot/ name=”FANUC M-710ic/50′′ robot_category=”Articulated Robots” manufacturer=”Fanuc” currency=”USD” price=37000 manufacturing_date=”2019-10-12 00:00:00+00:00′′" }, { "code": null, "e": 35006, "s": 34911, "text": "Now, let’s browse the ‘robots’ Restful web service using a browser. You can use the below URL." }, { "code": null, "e": 35029, "s": 35006, "text": "http://localhost:8000/" }, { "code": null, "e": 35086, "s": 35029, "text": "Sharing the screenshot of the browser for your reference" }, { "code": null, "e": 35290, "s": 35086, "text": "You can click the link that corresponds to robot-categories, manufacturers, and robots and check the data. Sharing the browser screenshot that displays the result of robots (http://localhost:8000/robot/)" }, { "code": null, "e": 35378, "s": 35290, "text": "Next, let’s create a new robot category. You can browse the below link and scroll down." }, { "code": null, "e": 35414, "s": 35378, "text": "http://localhost:8000/robocategory/" }, { "code": null, "e": 35464, "s": 35414, "text": "Sharing the browser screenshot for your reference" }, { "code": null, "e": 35760, "s": 35464, "text": "You can type the name of the new robot category and click the POST button. Here, it displays in HTML form. If you choose Raw data, select media type as application/json, populate the new robot category name to the name field, and click the POST button. Sharing the screenshot for your reference." }, { "code": null, "e": 35790, "s": 35760, "text": "Sharing the output screenshot" }, { "code": null, "e": 35852, "s": 35790, "text": "Let’s create a new manufacturer, you can browse the below URL" }, { "code": null, "e": 35888, "s": 35852, "text": "http://localhost:8000/manufacturer/" }, { "code": null, "e": 35919, "s": 35888, "text": "Sharing the browser screenshot" }, { "code": null, "e": 36034, "s": 35919, "text": "You can type the manufacturer name (ABB) and click the POST button. The browser displays the output as shown below" }, { "code": null, "e": 36129, "s": 36034, "text": "Finally, let’s create a new entry for the robot. You can browse the below URL and scroll down." }, { "code": null, "e": 36158, "s": 36129, "text": "http://localhost:8000/robot/" }, { "code": null, "e": 36233, "s": 36158, "text": "Let’s populate the data. Sharing the browser screenshot for your reference" }, { "code": null, "e": 36440, "s": 36233, "text": "Here, you can notice that the Robot category, Manufacture, and Currency are dropdown field. After populating the entries, you can click the POST button. Sharing below the screenshot of the displayed output." }, { "code": null, "e": 36544, "s": 36440, "text": "Let’s edit the price of the robot that has a pk value 2. You can browse the below URL and scroll down. " }, { "code": null, "e": 36575, "s": 36544, "text": "http://localhost:8000/robot/2/" }, { "code": null, "e": 36667, "s": 36575, "text": "Sharing the browser screenshot. You can change the price to 27000 and click the PUT button." }, { "code": null, "e": 36705, "s": 36667, "text": "Sharing the screenshot of the output." }, { "code": null, "e": 36776, "s": 36705, "text": "You can create a new test entry and browse the URL with the pk value. " }, { "code": null, "e": 36807, "s": 36776, "text": "http://localhost:8000/robot/2/" }, { "code": null, "e": 36877, "s": 36807, "text": "You can notice a DELETE button. Sharing the browser screenshot below:" }, { "code": null, "e": 37029, "s": 36877, "text": "On clicking the Delete button, the browser confirms the same. You can click the Delete button in the confirmation window. Sharing the screenshot below." }, { "code": null, "e": 37090, "s": 37029, "text": "If the deletion is successful, it displays the below output." }, { "code": null, "e": 37332, "s": 37090, "text": "From this section, we understood how to make use of the browsable API feature in the Django REST API framework. We composed and sent HTTP requests that generate text/html content as a response and also analyzed the response in a web browser." }, { "code": null, "e": 37344, "s": 37332, "text": "Django-REST" }, { "code": null, "e": 37358, "s": 37344, "text": "Python Django" }, { "code": null, "e": 37365, "s": 37358, "text": "Python" }, { "code": null, "e": 37463, "s": 37365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37481, "s": 37463, "text": "Python Dictionary" }, { "code": null, "e": 37503, "s": 37481, "text": "Enumerate() in Python" }, { "code": null, "e": 37535, "s": 37503, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 37577, "s": 37535, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 37603, "s": 37577, "text": "Python String | replace()" }, { "code": null, "e": 37640, "s": 37603, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 37665, "s": 37640, "text": "sum() function in Python" }, { "code": null, "e": 37694, "s": 37665, "text": "*args and **kwargs in Python" }, { "code": null, "e": 37750, "s": 37694, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Lucky number and a sum | Practice | GeeksforGeeks
Given a number N.Find the minimum Lucky number, the sum of whose digits is equal to N. Note:-Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. Example 1: Input: N=29 Output: 44777 Explanation: 44777 is the smallest number whose digit-sum(4+4+7+7+7) is equal to 29. Example 2: Input: N=9 Output: -1 Explanation: There is no lucky number whose digit-sum is equal to 9. Your Task: You don't need to read input or print anything.Your task is to complete the function minimumLuckyNumber() which takes a number N as input parameters and returns the minimum Lucky number(in the form of a string) whose digit-sum is equal to N. If there is no lucky number whose digit-sum is equal to N, then return -1. Expected Time Complexity:O(N) Expected Auxillary Space:O(1) Constraints: 1<=N<=105 Note:The answer may not fit in 64 bit integer representations. 0 Annanya Mathur1 year ago Annanya Mathur string minimumLuckyNumber(int n) { int c=0; string r=""; while(n>0) { if(n%7==0) {r+='7'; n=n-7; c=1;} else {r+='4'; n=n-4; } if(n==0) return r; } if(c==0) return "-1"; } 0 nitin verma1 year ago nitin verma how to time exceed ?? class Solution: def minimumLuckyNumber(self,N): #code here k = 4 l = 7 s = '' while(N>0): if N%7 == 0: N = N - l s = s + '7' else: N = N - k s = s + '4' if N == 0: return s else: return -1 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": 441, "s": 238, "text": "Given a number N.Find the minimum Lucky number, the sum of whose digits is equal to N.\nNote:-Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. " }, { "code": null, "e": 453, "s": 441, "text": "\nExample 1:" }, { "code": null, "e": 565, "s": 453, "text": "Input:\nN=29\nOutput:\n44777\nExplanation:\n44777 is the smallest number whose \ndigit-sum(4+4+7+7+7) is equal to 29." }, { "code": null, "e": 577, "s": 565, "text": "\nExample 2:" }, { "code": null, "e": 668, "s": 577, "text": "Input:\nN=9\nOutput:\n-1\nExplanation:\nThere is no lucky number whose digit-sum\nis equal to 9." }, { "code": null, "e": 997, "s": 668, "text": "\nYour Task:\nYou don't need to read input or print anything.Your task is to complete the function minimumLuckyNumber() which takes a number N as input parameters and returns the minimum Lucky number(in the form of a string) whose digit-sum is equal to N. If there is no lucky number whose digit-sum is equal to N, then return -1." }, { "code": null, "e": 1058, "s": 997, "text": "\nExpected Time Complexity:O(N)\nExpected Auxillary Space:O(1)" }, { "code": null, "e": 1082, "s": 1058, "text": "\nConstraints:\n1<=N<=105" }, { "code": null, "e": 1145, "s": 1082, "text": "Note:The answer may not fit in 64 bit integer representations." }, { "code": null, "e": 1147, "s": 1145, "text": "0" }, { "code": null, "e": 1172, "s": 1147, "text": "Annanya Mathur1 year ago" }, { "code": null, "e": 1187, "s": 1172, "text": "Annanya Mathur" }, { "code": null, "e": 1222, "s": 1187, "text": "string minimumLuckyNumber(int n) {" }, { "code": null, "e": 1517, "s": 1222, "text": " int c=0; string r=\"\"; while(n>0) { if(n%7==0) {r+='7'; n=n-7; c=1;} else {r+='4'; n=n-4; } if(n==0) return r; } if(c==0) return \"-1\";" }, { "code": null, "e": 1523, "s": 1517, "text": " }" }, { "code": null, "e": 1525, "s": 1523, "text": "0" }, { "code": null, "e": 1547, "s": 1525, "text": "nitin verma1 year ago" }, { "code": null, "e": 1559, "s": 1547, "text": "nitin verma" }, { "code": null, "e": 1581, "s": 1559, "text": "how to time exceed ??" }, { "code": null, "e": 1926, "s": 1581, "text": "class Solution: def minimumLuckyNumber(self,N): #code here k = 4 l = 7 s = '' while(N>0): if N%7 == 0: N = N - l s = s + '7' else: N = N - k s = s + '4' if N == 0: return s else: return -1" }, { "code": null, "e": 2072, "s": 1926, "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": 2108, "s": 2072, "text": " Login to access your submissions. " }, { "code": null, "e": 2118, "s": 2108, "text": "\nProblem\n" }, { "code": null, "e": 2128, "s": 2118, "text": "\nContest\n" }, { "code": null, "e": 2191, "s": 2128, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2339, "s": 2191, "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": 2547, "s": 2339, "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": 2653, "s": 2547, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Windows 10 Development - Live Tiles
In this chapter, we will talk about the interaction with a user through tiles. It is the iconic part of Windows 10. Tiles are displayed on the Start Screen as well as on the Start Menu. In other words, it is an application icon asset, which appears in a variety of forms throughout the Windows 10 operating system. They are the calling cards for your Universal Windows Platform (UWP) app. There are three states of tile. Basic State − Basic components of a Start tile consist of a back plate, an icon, and an app title. Basic State − Basic components of a Start tile consist of a back plate, an icon, and an app title. Semi-Live state − It is the same as the basic tile with the only difference that the badge, which is a number, can display the numbers from 0-99. Semi-Live state − It is the same as the basic tile with the only difference that the badge, which is a number, can display the numbers from 0-99. Live State − This tile contains all the elements of semi-live state tile and also shows additional content plate where you can put anything you want such as photos, text etc. Live State − This tile contains all the elements of semi-live state tile and also shows additional content plate where you can put anything you want such as photos, text etc. There are four ways to update the tiles. Scheduled − You can set the template and time with ScheduledTileNotification. Scheduled − You can set the template and time with ScheduledTileNotification. Periodic − When information is retrieved from a URI and you can specify the time to pull the information after that period of time, such as 30min, 1 hr., 6 hrs. etc. Periodic − When information is retrieved from a URI and you can specify the time to pull the information after that period of time, such as 30min, 1 hr., 6 hrs. etc. Local − Local one can be updated from your application; either from the foreground or the background app. Local − Local one can be updated from your application; either from the foreground or the background app. Push − It is updated from the server by pushing the information from the server. Push − It is updated from the server by pushing the information from the server. To create a tile, follow the given code. var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text01); var tileAttributes = tileXml.GetElementsByTagName("text"); tileAttributes[0].AppendChild(tileXml.CreateTextNode("Hello")); var tileNotification = new TileNotification(tileXml); TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification); Update badge is pretty simple because it is just a number and you can set the value of badge as shown below. var type = BadgeTemplateType.BadgeNumber; var xml = BadgeUpdateManager.GetTemplateContent(type); var elements = xml.GetElementsByTagName("badge"); var element = elements[0] as Windows.Data.Xml.Dom.XmlElement; element.SetAttribute("value", "7"); var updator = BadgeUpdateManager.CreateBadgeUpdaterForApplication(); var notification = new BadgeNotification(xml); updator.Update(notification); Let us create a new UWP project in Visual Studio. You will see the different png files under the Assets folder in Solution Explorer. You will see the different png files under the Assets folder in Solution Explorer. Let us define a default tile and its image in the package manifest. Let us define a default tile and its image in the package manifest. Double-click on the package.appxmanifest. This opens the manifest editor window. Double-click on the package.appxmanifest. This opens the manifest editor window. Select Visual Assets tab. Select Visual Assets tab. You can select the images and icons for your application tile with any of the specified dimensions. Under the Tile Images and Logos, default images are provided for all logos such as Square 71x71 Logo Square 150x150 Logo Square 310x310 Logo Store Logo You can select the images and icons for your application tile with any of the specified dimensions. Under the Tile Images and Logos, default images are provided for all logos such as Square 71x71 Logo Square 150x150 Logo Square 310x310 Logo Store Logo When you execute your application and then go to your start screen, you will see the tile for your application. When you execute your application and then go to your start screen, you will see the tile for your application. 23 Lectures 2 hours Pavan Lalwani 37 Lectures 13 hours Trevoir Williams 46 Lectures 3.5 hours Fettah Ben 55 Lectures 6 hours Total Seminars 20 Lectures 2.5 hours Brandon Dennis 52 Lectures 9 hours Fabrice Chrzanowski Print Add Notes Bookmark this page
[ { "code": null, "e": 2673, "s": 2284, "text": "In this chapter, we will talk about the interaction with a user through tiles. It is the iconic part of Windows 10. Tiles are displayed on the Start Screen as well as on the Start Menu. In other words, it is an application icon asset, which appears in a variety of forms throughout the Windows 10 operating system. They are the calling cards for your Universal Windows Platform (UWP) app." }, { "code": null, "e": 2705, "s": 2673, "text": "There are three states of tile." }, { "code": null, "e": 2804, "s": 2705, "text": "Basic State − Basic components of a Start tile consist of a back plate, an icon, and an app title." }, { "code": null, "e": 2903, "s": 2804, "text": "Basic State − Basic components of a Start tile consist of a back plate, an icon, and an app title." }, { "code": null, "e": 3049, "s": 2903, "text": "Semi-Live state − It is the same as the basic tile with the only difference that the badge, which is a number, can display the numbers from 0-99." }, { "code": null, "e": 3195, "s": 3049, "text": "Semi-Live state − It is the same as the basic tile with the only difference that the badge, which is a number, can display the numbers from 0-99." }, { "code": null, "e": 3370, "s": 3195, "text": "Live State − This tile contains all the elements of semi-live state tile and also shows additional content plate where you can put anything you want such as photos, text etc." }, { "code": null, "e": 3545, "s": 3370, "text": "Live State − This tile contains all the elements of semi-live state tile and also shows additional content plate where you can put anything you want such as photos, text etc." }, { "code": null, "e": 3586, "s": 3545, "text": "There are four ways to update the tiles." }, { "code": null, "e": 3664, "s": 3586, "text": "Scheduled − You can set the template and time with ScheduledTileNotification." }, { "code": null, "e": 3742, "s": 3664, "text": "Scheduled − You can set the template and time with ScheduledTileNotification." }, { "code": null, "e": 3908, "s": 3742, "text": "Periodic − When information is retrieved from a URI and you can specify the time to pull the information after that period of time, such as 30min, 1 hr., 6 hrs. etc." }, { "code": null, "e": 4074, "s": 3908, "text": "Periodic − When information is retrieved from a URI and you can specify the time to pull the information after that period of time, such as 30min, 1 hr., 6 hrs. etc." }, { "code": null, "e": 4180, "s": 4074, "text": "Local − Local one can be updated from your application; either from the foreground or the background app." }, { "code": null, "e": 4286, "s": 4180, "text": "Local − Local one can be updated from your application; either from the foreground or the background app." }, { "code": null, "e": 4367, "s": 4286, "text": "Push − It is updated from the server by pushing the information from the server." }, { "code": null, "e": 4448, "s": 4367, "text": "Push − It is updated from the server by pushing the information from the server." }, { "code": null, "e": 4489, "s": 4448, "text": "To create a tile, follow the given code." }, { "code": null, "e": 4853, "s": 4489, "text": "var tileXml = \n TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text01); \n \nvar tileAttributes = tileXml.GetElementsByTagName(\"text\"); \ntileAttributes[0].AppendChild(tileXml.CreateTextNode(\"Hello\"));\n\t\t\t\nvar tileNotification = new TileNotification(tileXml);\t\t\t\nTileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);" }, { "code": null, "e": 4962, "s": 4853, "text": "Update badge is pretty simple because it is just a number and you can set the value of badge as shown below." }, { "code": null, "e": 5364, "s": 4962, "text": "var type = BadgeTemplateType.BadgeNumber; \nvar xml = BadgeUpdateManager.GetTemplateContent(type); \n\nvar elements = xml.GetElementsByTagName(\"badge\"); \nvar element = elements[0] as Windows.Data.Xml.Dom.XmlElement; \nelement.SetAttribute(\"value\", \"7\");\n \nvar updator = BadgeUpdateManager.CreateBadgeUpdaterForApplication(); \nvar notification = new BadgeNotification(xml); \nupdator.Update(notification);" }, { "code": null, "e": 5414, "s": 5364, "text": "Let us create a new UWP project in Visual Studio." }, { "code": null, "e": 5497, "s": 5414, "text": "You will see the different png files under the Assets folder in Solution Explorer." }, { "code": null, "e": 5580, "s": 5497, "text": "You will see the different png files under the Assets folder in Solution Explorer." }, { "code": null, "e": 5648, "s": 5580, "text": "Let us define a default tile and its image in the package manifest." }, { "code": null, "e": 5716, "s": 5648, "text": "Let us define a default tile and its image in the package manifest." }, { "code": null, "e": 5797, "s": 5716, "text": "Double-click on the package.appxmanifest. This opens the manifest editor window." }, { "code": null, "e": 5878, "s": 5797, "text": "Double-click on the package.appxmanifest. This opens the manifest editor window." }, { "code": null, "e": 5904, "s": 5878, "text": "Select Visual Assets tab." }, { "code": null, "e": 5930, "s": 5904, "text": "Select Visual Assets tab." }, { "code": null, "e": 6185, "s": 5930, "text": "You can select the images and icons for your application tile with any of the specified dimensions. Under the Tile Images and Logos, default images are provided for all logos such as\n\nSquare 71x71 Logo\nSquare 150x150 Logo\nSquare 310x310 Logo\nStore Logo\n\n" }, { "code": null, "e": 6368, "s": 6185, "text": "You can select the images and icons for your application tile with any of the specified dimensions. Under the Tile Images and Logos, default images are provided for all logos such as" }, { "code": null, "e": 6386, "s": 6368, "text": "Square 71x71 Logo" }, { "code": null, "e": 6406, "s": 6386, "text": "Square 150x150 Logo" }, { "code": null, "e": 6426, "s": 6406, "text": "Square 310x310 Logo" }, { "code": null, "e": 6437, "s": 6426, "text": "Store Logo" }, { "code": null, "e": 6549, "s": 6437, "text": "When you execute your application and then go to your start screen, you will see the tile for your application." }, { "code": null, "e": 6661, "s": 6549, "text": "When you execute your application and then go to your start screen, you will see the tile for your application." }, { "code": null, "e": 6694, "s": 6661, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 6709, "s": 6694, "text": " Pavan Lalwani" }, { "code": null, "e": 6743, "s": 6709, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 6761, "s": 6743, "text": " Trevoir Williams" }, { "code": null, "e": 6796, "s": 6761, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6808, "s": 6796, "text": " Fettah Ben" }, { "code": null, "e": 6841, "s": 6808, "text": "\n 55 Lectures \n 6 hours \n" }, { "code": null, "e": 6857, "s": 6841, "text": " Total Seminars" }, { "code": null, "e": 6892, "s": 6857, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6908, "s": 6892, "text": " Brandon Dennis" }, { "code": null, "e": 6941, "s": 6908, "text": "\n 52 Lectures \n 9 hours \n" }, { "code": null, "e": 6962, "s": 6941, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 6969, "s": 6962, "text": " Print" }, { "code": null, "e": 6980, "s": 6969, "text": " Add Notes" } ]
Bitwise Operators | Practice | GeeksforGeeks
Bitwise operators are useful when we want to work with bits. Here, we'll take a look at them. Given three positive integers a, b and c. Your task is to perform some bitwise operations on them as given below:1. d = a ^ a2. e = c ^ b3. f = a & b4. g = c | (a ^ a)5. e = ~eNote: ^ is for xor. The working of bitwise operators can be found here. Example: Input:a = 4b = 8c = 2Output:01002-11 Constraints:1 <= A, B, C <= 106 Video: YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Operators in C / C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreMore 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 / 3:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WFy9SFJsAWQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 0 sahibealam293 months ago void bitWiseOperation(int a, int b, int c) { int l1=a^a,l2=c^b,l3=a&b,l4=c|l1,l5=~l2; cout<<l1<<endl<<l2<<endl<<l3<<endl<<l4<<endl<<l5<<endl; // Your code here} 0 sahibealam293 months ago use endl or "\n" at end so 0 will not add at end of output 0 swnkhurana6 months ago void bitWiseOperation(int a, int b, int c) { int d = a^a;int e = c^b;int f = a&b;int g = c | (a^a);int h= ~e ;cout<<d<<endl<<e<<endl<<f<<endl<<g<<endl<< h <<endl; // Your code here} 0 yogeshwari harode11 months ago yogeshwari harode Bitwise Operators (Simple way to solve)https://github.com/yogeshwa... 0 yogeshwari harode11 months ago yogeshwari harode Bitwise Operators (Simple way to solve)https://github.com/yogeshwa... 0 SACHIN KUMAR1 year ago SACHIN KUMAR void bitWiseOperation(int a, int b, int c){ int d = a^a; int e = c^b; int j=e; int f = a&b; int g = c | (a^a); e = ~e; cout<<d<<endl<<j<<endl<<f<<endl<<g<<endl<<e<<endl; }=""> 0 preet gandhi2 years ago preet gandhi Test Case:- 324 435 192Actual O/P:- 0371256192-372My O/P :- 0371256448 code:-int e=a&b; int d=c|e; int f=c^b; // Your code here cout<< int(a^a) <<endl; cout<<="" f="" <<endl;="" cout<<="" e="" <<endl;="" cout<<="" d="" <<endl;="" cout<<="" ~f<<endl;=""> 0 aditya jha2 years ago aditya jha int d = a ^ a;int e = c ^ b;int f = a & b;int g = c | (a ^ a);int h= ~e;cout< 0 h3 h32 years ago h3 h3 0 ANKIT SAHU2 years ago ANKIT SAHU https://ide.geeksforgeeks.o... 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": 372, "s": 278, "text": "Bitwise operators are useful when we want to work with bits. Here, we'll take a look at them." }, { "code": null, "e": 620, "s": 372, "text": "Given three positive integers a, b and c. Your task is to perform some bitwise operations on them as given below:1. d = a ^ a2. e = c ^ b3. f = a & b4. g = c | (a ^ a)5. e = ~eNote: ^ is for xor. The working of bitwise operators can be found here." }, { "code": null, "e": 629, "s": 620, "text": "Example:" }, { "code": null, "e": 666, "s": 629, "text": "Input:a = 4b = 8c = 2Output:01002-11" }, { "code": null, "e": 698, "s": 666, "text": "Constraints:1 <= A, B, C <= 106" }, { "code": null, "e": 705, "s": 698, "text": "Video:" }, { "code": null, "e": 1598, "s": 705, "text": "YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Operators in C / C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreMore 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 / 3:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WFy9SFJsAWQ\" 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": 1600, "s": 1598, "text": "0" }, { "code": null, "e": 1625, "s": 1600, "text": "sahibealam293 months ago" }, { "code": null, "e": 1792, "s": 1625, "text": "void bitWiseOperation(int a, int b, int c) { int l1=a^a,l2=c^b,l3=a&b,l4=c|l1,l5=~l2; cout<<l1<<endl<<l2<<endl<<l3<<endl<<l4<<endl<<l5<<endl; // Your code here}" }, { "code": null, "e": 1794, "s": 1792, "text": "0" }, { "code": null, "e": 1819, "s": 1794, "text": "sahibealam293 months ago" }, { "code": null, "e": 1878, "s": 1819, "text": "use endl or \"\\n\" at end so 0 will not add at end of output" }, { "code": null, "e": 1880, "s": 1878, "text": "0" }, { "code": null, "e": 1903, "s": 1880, "text": "swnkhurana6 months ago" }, { "code": null, "e": 1948, "s": 1903, "text": "void bitWiseOperation(int a, int b, int c) {" }, { "code": null, "e": 2066, "s": 1948, "text": "int d = a^a;int e = c^b;int f = a&b;int g = c | (a^a);int h= ~e ;cout<<d<<endl<<e<<endl<<f<<endl<<g<<endl<< h <<endl;" }, { "code": null, "e": 2088, "s": 2066, "text": " // Your code here}" }, { "code": null, "e": 2090, "s": 2088, "text": "0" }, { "code": null, "e": 2121, "s": 2090, "text": "yogeshwari harode11 months ago" }, { "code": null, "e": 2139, "s": 2121, "text": "yogeshwari harode" }, { "code": null, "e": 2209, "s": 2139, "text": "Bitwise Operators (Simple way to solve)https://github.com/yogeshwa..." }, { "code": null, "e": 2211, "s": 2209, "text": "0" }, { "code": null, "e": 2242, "s": 2211, "text": "yogeshwari harode11 months ago" }, { "code": null, "e": 2260, "s": 2242, "text": "yogeshwari harode" }, { "code": null, "e": 2330, "s": 2260, "text": "Bitwise Operators (Simple way to solve)https://github.com/yogeshwa..." }, { "code": null, "e": 2332, "s": 2330, "text": "0" }, { "code": null, "e": 2355, "s": 2332, "text": "SACHIN KUMAR1 year ago" }, { "code": null, "e": 2368, "s": 2355, "text": "SACHIN KUMAR" }, { "code": null, "e": 2412, "s": 2368, "text": "void bitWiseOperation(int a, int b, int c){" }, { "code": null, "e": 2567, "s": 2412, "text": " int d = a^a; int e = c^b; int j=e; int f = a&b; int g = c | (a^a); e = ~e; cout<<d<<endl<<j<<endl<<f<<endl<<g<<endl<<e<<endl; }=\"\">" }, { "code": null, "e": 2569, "s": 2567, "text": "0" }, { "code": null, "e": 2593, "s": 2569, "text": "preet gandhi2 years ago" }, { "code": null, "e": 2606, "s": 2593, "text": "preet gandhi" }, { "code": null, "e": 2677, "s": 2606, "text": "Test Case:- 324 435 192Actual O/P:- 0371256192-372My O/P :- 0371256448" }, { "code": null, "e": 2872, "s": 2677, "text": "code:-int e=a&b; int d=c|e; int f=c^b; // Your code here cout<< int(a^a) <<endl; cout<<=\"\" f=\"\" <<endl;=\"\" cout<<=\"\" e=\"\" <<endl;=\"\" cout<<=\"\" d=\"\" <<endl;=\"\" cout<<=\"\" ~f<<endl;=\"\">" }, { "code": null, "e": 2874, "s": 2872, "text": "0" }, { "code": null, "e": 2896, "s": 2874, "text": "aditya jha2 years ago" }, { "code": null, "e": 2907, "s": 2896, "text": "aditya jha" }, { "code": null, "e": 2985, "s": 2907, "text": "int d = a ^ a;int e = c ^ b;int f = a & b;int g = c | (a ^ a);int h= ~e;cout<" }, { "code": null, "e": 2987, "s": 2985, "text": "0" }, { "code": null, "e": 3004, "s": 2987, "text": "h3 h32 years ago" }, { "code": null, "e": 3010, "s": 3004, "text": "h3 h3" }, { "code": null, "e": 3012, "s": 3010, "text": "0" }, { "code": null, "e": 3034, "s": 3012, "text": "ANKIT SAHU2 years ago" }, { "code": null, "e": 3045, "s": 3034, "text": "ANKIT SAHU" }, { "code": null, "e": 3076, "s": 3045, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3222, "s": 3076, "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": 3258, "s": 3222, "text": " Login to access your submissions. " }, { "code": null, "e": 3268, "s": 3258, "text": "\nProblem\n" }, { "code": null, "e": 3278, "s": 3268, "text": "\nContest\n" }, { "code": null, "e": 3341, "s": 3278, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3489, "s": 3341, "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": 3697, "s": 3489, "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": 3803, "s": 3697, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
From Novice to Expert: How to Write a Configuration file in Python | by Xiaoxu Gao | Towards Data Science
When we design software, we normally put a lot of effort into writing high-quality code. But that’s not enough. A good software should also take care of its eco-system, like testing, deployment, network, etc. One of the most important aspects is configuration management. Good configuration management should allow the software to be executed in any environment without changing the code. It helps Ops to manage all the hassle settings and it provides a view on what can happen during the process and even allows them to change the behavior during the runtime. The most common configuration includes credentials to the database or an external service, the hostname of the deployed server, dynamic parameters, etc. In this article, I want to share with you some good practices of configuration management and how we can implement them in Python. If you have more ideas, please leave your comments below. Before writing any configuration file, we should ask ourselves why we need an external file? Can’t we just make them constants in the code? Actually, the famous The Twelve-Factor App has answered this question for us: A litmus test for whether an app has all config correctly factored out of the code is whether the codebase could be made open source at any moment, without compromising any credentials. Note that this definition of “config” does not include internal application config, such as config/routes.rb in Rails, or how code modules are connected in Spring. This type of config does not vary between deploys, and so is best done in the code. It recommends that any environment-dependent parameters such as database credentials should sit in the external file. Otherwise, they are just normal constants in the code. Another use case I see a lot is to store dynamic variables in the external file, for instance, a blacklist or whitelist. But it can also be a number within a certain range (e.g. timeout) or some free texts. These variables can possibly be the same in each environment, but the configuration file makes the software much more flexible and easy to edit. However, if it grows too much, we might consider moving it to a database instead. In fact, there are no constraints on the format of the configuration file as long as the code could read and parse them. But, there are some good practices. The most common and standardized formats are YAML, JSON, TOML and INI. A good configuration file should meet at least these 3 criteria: Easy to read and edit: It should be text-based and structured in such a way that is easy to understand. Even non-developers should be able to read.Allow comments: Configuration file is not something that will be only read by developers. It is extremely important in production when non-developers try to understand the process and modify the software behavior. Writing comments is a way to quickly explain certain things, thus making the config file more expressive.Easy to deploy: Configuration file should be accepted by all the operating systems and environments. It should also be easily shipped to the server via a CDaaS pipeline. Easy to read and edit: It should be text-based and structured in such a way that is easy to understand. Even non-developers should be able to read. Allow comments: Configuration file is not something that will be only read by developers. It is extremely important in production when non-developers try to understand the process and modify the software behavior. Writing comments is a way to quickly explain certain things, thus making the config file more expressive. Easy to deploy: Configuration file should be accepted by all the operating systems and environments. It should also be easily shipped to the server via a CDaaS pipeline. Maybe you still don’t know which one is better. But if you think about it in the context of Python, then the answer would be YAML or INI. YAML and INI are well accepted by most of the Python programs and packages. INI is probably the most straightforward solution with only 1 level of the hierarchy. However, there is no data type in INI, everything is encoded as a string. The same configuration in YAML looks like this. As you can see, YAML supports nested structures quite well (like JSON). Besides, YAML natively encodes some data types such as string, integer, double, boolean, list, dictionary, etc. JSON is very similar to YAML and is extremely popular as well, however, it’s not possible to add comments in JSON. I use JSON a lot for internal config inside the program, but not when I want to share the config with other people. TOML, on the other hand, is similar to INI, but supports more data types and has defined syntax for nested structures. It’s used a lot by Python package managements like pip or poetry. But if the config file has too many nested structures, YAML is a better choice. The following file looks like INI, but every string value has quotes. So far, I’ve explained WHY and WHAT. In the next sections, I will show you the HOW. As usual, we start from the most basic approach, that is simply creating an external file and reading it. Python has dedicated built-in packages to parse YAML and JSON files. As you see from the code below, they actually return the same dict object, so the attribute access will be the same for both files. Read Due to security issue, it is recommended to use yaml.safe_load() instead of yaml.load() to avoid code injection in the configuration file. Validation Both packages will raise a FileNotFoundError for a non-existing file. YAML throws different exceptions for a non-YAML file and an invalid YAML file, while JSON throws JSONDecoderError for both errors. From this onwards, I will introduce packages designed for configuration management. We start with a Python built-in package: Configureparser. Configureparser is primarily used for reading and writing INI files, but it also supports dictionary and iterable file object as an input. Each INI file consists of multiple sections where there are multiple key, value pairs. Below is an example of accessing the fields. Read Configureparser doesn’t guess datatypes in the config file, so every config is stored as a string. But it provides a few methods to convert string to the correct datatype. The most interesting one is Boolean type as it’s able to recognize Boolean values from 'yes'/'no', 'on'/'off', 'true'/'false' and '1'/'0'. As mentioned before, it could also read from a dictionary using read_dict(), or a string using read_string() or an iterable file object using read_file(). Validation The validation of Configureparser is not as straightforward as YAML and JSON. First, it doesn’t raise a FileNotFoundError if the file doesn’t exist, but instead, it raises a KeyError when it tries to access a key. Besides, the package “ignores” the error of indentation. Like the example below, if you have an extra tab or space before “DEBUG”, then you would get a wrong value for both ENVIRONMENT and DEBUG. Nevertheless, Configureparser is able to return ParserError for multiple errors (see the last test case). This helps us to solve problems in one shot. Now we move to third-party libraries. So far, I have actually missed one type of configuration files which is .env. The variables inside .env file will be loaded as environment variables by python-dotenv and can be accessed by os.getenv. A .env file basically looks like this. The default path is the root folder of your project. ENVIRONMENT=testDEBUG=trueUSERNAME=xiaoxuPASSWORD=xiaoxuHOST=127.0.0.1PORT=5432 Read It is extremely easy to use. You can decide whether you want to override the existing variable in the environment with parameter override. Validation However, python-dotenv doesn’t validate the .env file. If you have a .env file like this, and you want to access DEBUG, you will get None as the return without an exception. # .envENVIRONMENT=testDEBUG# load.pyload_dotenv()print('DEBUG' in os.environ.keys())# False Dynaconf is a very powerful settings configuration for Python that supports multi file formats: yaml, json, ini, toml and python. It can automatically load .env file and supports custom validation rules. In a short, it covers pretty much all the functionalities from the previous 3 options and even goes beyond that. For example, you can store an encrypted password and use a custom loader to decrypt the password. It’s also nicely integrated with Flask, Django and Pytest. I will not mention all the functionalities in this article, for more details, please refer to their documentation. Read Dynaconf uses .env to find all the settings file and populate settings object with the fields. If 2 settings file have the same variable, then the value will be overridden by the latest settings file. Validation One of the interesting features to me is the custom validator. As mentioned before, Configureparser doesn’t validate INI file strictly enough, but this can be achieved within dynaconf. In this example, I check whether certain keys exist in the file and whether certain key has the correct value. If you read from YAML or TOML file which supports multi datatypes, you can even check if a number is in a certain range. Integration with Pytest Another interesting feature is the integration with pytest. The settings for unit testing are normally different from other environments. You can use FORCE_ENV_FOR_DYNACONF to let the application read a different section in your settings file, or use monkeypatch to replace a speific key and value pair in the settings file. Refresh the config during Runtime Dynaconf also supports reload() , that cleans and executes all the loaders. This is helpful if you want the application to reload the settings file during runtime. For example, the application should automatically reload the settings when the config file has been opened and modified. The last option is much more than just a file loader. Hydra is a framework developed by Facebook for elegantly configuring complex applications. Besides reading, writing and validating config files, Hydra also comes up with a strategy to simplify the management of multi config files, override it through command line interface, create a snapshot of each run and etc. Read Here is the basic use of hydra. +APP.NAME means adding a new field in the config, or APP.NAME=hydra1.1 to override an existing field. Validation Hydra nicely integrate with @dataclass to perform basic validations such as type checking and read-only fields. But it doesn’t support __post_init__ method for advanced value checking like described in my previous article. Config group Hydra introduces a concept called config group. The idea is to group configs with the same type and choose one of them during the execution. For example, you can have a group “database” with one config for Postgres, and another one for MySQL. When it gets more complex, you might have a layout like this in your program (an example from Hydra documentation) and you want to benchmark your application with different combinations of db, schema and ui, then you can run: python my_app.py db=postgresql schema=school.yaml More ... Hydra supports parameter sweep with --multirun, that runs multiple jobs at the same with different config files. For instance, for the previous example, we can run: python my_app.py schema=warehouse,support,school db=mysql,postgresql -m Then you basically start 6 jobs simultaneously [2019-10-01 14:44:16,254] - Launching 6 jobs locally[2019-10-01 14:44:16,254] - Sweep output dir : multirun/2019-10-01/14-44-16[2019-10-01 14:44:16,254] - #0 : schema=warehouse db=mysql[2019-10-01 14:44:16,321] - #1 : schema=warehouse db=postgresql[2019-10-01 14:44:16,390] - #2 : schema=support db=mysql[2019-10-01 14:44:16,458] - #3 : schema=support db=postgresql[2019-10-01 14:44:16,527] - #4 : schema=school db=mysql[2019-10-01 14:44:16,602] - #5 : schema=school db=postgresql In this article, I’ve talk about configuration management in Python in terms of WHY, WHAT and HOW. Depending on the usecase, a complex tool/framework isn’t always better than a simple package. No matter which one you choose, you should always think about its readbility, matainbility and how to spot the error as earily as possible. In fact, config file is just another type of code. I hope you enjoy this article, and feel free to leave your comments below.
[ { "code": null, "e": 444, "s": 172, "text": "When we design software, we normally put a lot of effort into writing high-quality code. But that’s not enough. A good software should also take care of its eco-system, like testing, deployment, network, etc. One of the most important aspects is configuration management." }, { "code": null, "e": 733, "s": 444, "text": "Good configuration management should allow the software to be executed in any environment without changing the code. It helps Ops to manage all the hassle settings and it provides a view on what can happen during the process and even allows them to change the behavior during the runtime." }, { "code": null, "e": 886, "s": 733, "text": "The most common configuration includes credentials to the database or an external service, the hostname of the deployed server, dynamic parameters, etc." }, { "code": null, "e": 1075, "s": 886, "text": "In this article, I want to share with you some good practices of configuration management and how we can implement them in Python. If you have more ideas, please leave your comments below." }, { "code": null, "e": 1293, "s": 1075, "text": "Before writing any configuration file, we should ask ourselves why we need an external file? Can’t we just make them constants in the code? Actually, the famous The Twelve-Factor App has answered this question for us:" }, { "code": null, "e": 1727, "s": 1293, "text": "A litmus test for whether an app has all config correctly factored out of the code is whether the codebase could be made open source at any moment, without compromising any credentials. Note that this definition of “config” does not include internal application config, such as config/routes.rb in Rails, or how code modules are connected in Spring. This type of config does not vary between deploys, and so is best done in the code." }, { "code": null, "e": 2334, "s": 1727, "text": "It recommends that any environment-dependent parameters such as database credentials should sit in the external file. Otherwise, they are just normal constants in the code. Another use case I see a lot is to store dynamic variables in the external file, for instance, a blacklist or whitelist. But it can also be a number within a certain range (e.g. timeout) or some free texts. These variables can possibly be the same in each environment, but the configuration file makes the software much more flexible and easy to edit. However, if it grows too much, we might consider moving it to a database instead." }, { "code": null, "e": 2491, "s": 2334, "text": "In fact, there are no constraints on the format of the configuration file as long as the code could read and parse them. But, there are some good practices." }, { "code": null, "e": 2627, "s": 2491, "text": "The most common and standardized formats are YAML, JSON, TOML and INI. A good configuration file should meet at least these 3 criteria:" }, { "code": null, "e": 3263, "s": 2627, "text": "Easy to read and edit: It should be text-based and structured in such a way that is easy to understand. Even non-developers should be able to read.Allow comments: Configuration file is not something that will be only read by developers. It is extremely important in production when non-developers try to understand the process and modify the software behavior. Writing comments is a way to quickly explain certain things, thus making the config file more expressive.Easy to deploy: Configuration file should be accepted by all the operating systems and environments. It should also be easily shipped to the server via a CDaaS pipeline." }, { "code": null, "e": 3411, "s": 3263, "text": "Easy to read and edit: It should be text-based and structured in such a way that is easy to understand. Even non-developers should be able to read." }, { "code": null, "e": 3731, "s": 3411, "text": "Allow comments: Configuration file is not something that will be only read by developers. It is extremely important in production when non-developers try to understand the process and modify the software behavior. Writing comments is a way to quickly explain certain things, thus making the config file more expressive." }, { "code": null, "e": 3901, "s": 3731, "text": "Easy to deploy: Configuration file should be accepted by all the operating systems and environments. It should also be easily shipped to the server via a CDaaS pipeline." }, { "code": null, "e": 4275, "s": 3901, "text": "Maybe you still don’t know which one is better. But if you think about it in the context of Python, then the answer would be YAML or INI. YAML and INI are well accepted by most of the Python programs and packages. INI is probably the most straightforward solution with only 1 level of the hierarchy. However, there is no data type in INI, everything is encoded as a string." }, { "code": null, "e": 4507, "s": 4275, "text": "The same configuration in YAML looks like this. As you can see, YAML supports nested structures quite well (like JSON). Besides, YAML natively encodes some data types such as string, integer, double, boolean, list, dictionary, etc." }, { "code": null, "e": 4738, "s": 4507, "text": "JSON is very similar to YAML and is extremely popular as well, however, it’s not possible to add comments in JSON. I use JSON a lot for internal config inside the program, but not when I want to share the config with other people." }, { "code": null, "e": 5073, "s": 4738, "text": "TOML, on the other hand, is similar to INI, but supports more data types and has defined syntax for nested structures. It’s used a lot by Python package managements like pip or poetry. But if the config file has too many nested structures, YAML is a better choice. The following file looks like INI, but every string value has quotes." }, { "code": null, "e": 5157, "s": 5073, "text": "So far, I’ve explained WHY and WHAT. In the next sections, I will show you the HOW." }, { "code": null, "e": 5464, "s": 5157, "text": "As usual, we start from the most basic approach, that is simply creating an external file and reading it. Python has dedicated built-in packages to parse YAML and JSON files. As you see from the code below, they actually return the same dict object, so the attribute access will be the same for both files." }, { "code": null, "e": 5469, "s": 5464, "text": "Read" }, { "code": null, "e": 5608, "s": 5469, "text": "Due to security issue, it is recommended to use yaml.safe_load() instead of yaml.load() to avoid code injection in the configuration file." }, { "code": null, "e": 5619, "s": 5608, "text": "Validation" }, { "code": null, "e": 5820, "s": 5619, "text": "Both packages will raise a FileNotFoundError for a non-existing file. YAML throws different exceptions for a non-YAML file and an invalid YAML file, while JSON throws JSONDecoderError for both errors." }, { "code": null, "e": 5962, "s": 5820, "text": "From this onwards, I will introduce packages designed for configuration management. We start with a Python built-in package: Configureparser." }, { "code": null, "e": 6233, "s": 5962, "text": "Configureparser is primarily used for reading and writing INI files, but it also supports dictionary and iterable file object as an input. Each INI file consists of multiple sections where there are multiple key, value pairs. Below is an example of accessing the fields." }, { "code": null, "e": 6238, "s": 6233, "text": "Read" }, { "code": null, "e": 6549, "s": 6238, "text": "Configureparser doesn’t guess datatypes in the config file, so every config is stored as a string. But it provides a few methods to convert string to the correct datatype. The most interesting one is Boolean type as it’s able to recognize Boolean values from 'yes'/'no', 'on'/'off', 'true'/'false' and '1'/'0'." }, { "code": null, "e": 6704, "s": 6549, "text": "As mentioned before, it could also read from a dictionary using read_dict(), or a string using read_string() or an iterable file object using read_file()." }, { "code": null, "e": 6715, "s": 6704, "text": "Validation" }, { "code": null, "e": 6929, "s": 6715, "text": "The validation of Configureparser is not as straightforward as YAML and JSON. First, it doesn’t raise a FileNotFoundError if the file doesn’t exist, but instead, it raises a KeyError when it tries to access a key." }, { "code": null, "e": 7125, "s": 6929, "text": "Besides, the package “ignores” the error of indentation. Like the example below, if you have an extra tab or space before “DEBUG”, then you would get a wrong value for both ENVIRONMENT and DEBUG." }, { "code": null, "e": 7276, "s": 7125, "text": "Nevertheless, Configureparser is able to return ParserError for multiple errors (see the last test case). This helps us to solve problems in one shot." }, { "code": null, "e": 7514, "s": 7276, "text": "Now we move to third-party libraries. So far, I have actually missed one type of configuration files which is .env. The variables inside .env file will be loaded as environment variables by python-dotenv and can be accessed by os.getenv." }, { "code": null, "e": 7606, "s": 7514, "text": "A .env file basically looks like this. The default path is the root folder of your project." }, { "code": null, "e": 7686, "s": 7606, "text": "ENVIRONMENT=testDEBUG=trueUSERNAME=xiaoxuPASSWORD=xiaoxuHOST=127.0.0.1PORT=5432" }, { "code": null, "e": 7691, "s": 7686, "text": "Read" }, { "code": null, "e": 7830, "s": 7691, "text": "It is extremely easy to use. You can decide whether you want to override the existing variable in the environment with parameter override." }, { "code": null, "e": 7841, "s": 7830, "text": "Validation" }, { "code": null, "e": 8015, "s": 7841, "text": "However, python-dotenv doesn’t validate the .env file. If you have a .env file like this, and you want to access DEBUG, you will get None as the return without an exception." }, { "code": null, "e": 8107, "s": 8015, "text": "# .envENVIRONMENT=testDEBUG# load.pyload_dotenv()print('DEBUG' in os.environ.keys())# False" }, { "code": null, "e": 8696, "s": 8107, "text": "Dynaconf is a very powerful settings configuration for Python that supports multi file formats: yaml, json, ini, toml and python. It can automatically load .env file and supports custom validation rules. In a short, it covers pretty much all the functionalities from the previous 3 options and even goes beyond that. For example, you can store an encrypted password and use a custom loader to decrypt the password. It’s also nicely integrated with Flask, Django and Pytest. I will not mention all the functionalities in this article, for more details, please refer to their documentation." }, { "code": null, "e": 8701, "s": 8696, "text": "Read" }, { "code": null, "e": 8902, "s": 8701, "text": "Dynaconf uses .env to find all the settings file and populate settings object with the fields. If 2 settings file have the same variable, then the value will be overridden by the latest settings file." }, { "code": null, "e": 8913, "s": 8902, "text": "Validation" }, { "code": null, "e": 9330, "s": 8913, "text": "One of the interesting features to me is the custom validator. As mentioned before, Configureparser doesn’t validate INI file strictly enough, but this can be achieved within dynaconf. In this example, I check whether certain keys exist in the file and whether certain key has the correct value. If you read from YAML or TOML file which supports multi datatypes, you can even check if a number is in a certain range." }, { "code": null, "e": 9354, "s": 9330, "text": "Integration with Pytest" }, { "code": null, "e": 9679, "s": 9354, "text": "Another interesting feature is the integration with pytest. The settings for unit testing are normally different from other environments. You can use FORCE_ENV_FOR_DYNACONF to let the application read a different section in your settings file, or use monkeypatch to replace a speific key and value pair in the settings file." }, { "code": null, "e": 9713, "s": 9679, "text": "Refresh the config during Runtime" }, { "code": null, "e": 9998, "s": 9713, "text": "Dynaconf also supports reload() , that cleans and executes all the loaders. This is helpful if you want the application to reload the settings file during runtime. For example, the application should automatically reload the settings when the config file has been opened and modified." }, { "code": null, "e": 10143, "s": 9998, "text": "The last option is much more than just a file loader. Hydra is a framework developed by Facebook for elegantly configuring complex applications." }, { "code": null, "e": 10366, "s": 10143, "text": "Besides reading, writing and validating config files, Hydra also comes up with a strategy to simplify the management of multi config files, override it through command line interface, create a snapshot of each run and etc." }, { "code": null, "e": 10371, "s": 10366, "text": "Read" }, { "code": null, "e": 10505, "s": 10371, "text": "Here is the basic use of hydra. +APP.NAME means adding a new field in the config, or APP.NAME=hydra1.1 to override an existing field." }, { "code": null, "e": 10516, "s": 10505, "text": "Validation" }, { "code": null, "e": 10739, "s": 10516, "text": "Hydra nicely integrate with @dataclass to perform basic validations such as type checking and read-only fields. But it doesn’t support __post_init__ method for advanced value checking like described in my previous article." }, { "code": null, "e": 10752, "s": 10739, "text": "Config group" }, { "code": null, "e": 10995, "s": 10752, "text": "Hydra introduces a concept called config group. The idea is to group configs with the same type and choose one of them during the execution. For example, you can have a group “database” with one config for Postgres, and another one for MySQL." }, { "code": null, "e": 11110, "s": 10995, "text": "When it gets more complex, you might have a layout like this in your program (an example from Hydra documentation)" }, { "code": null, "e": 11221, "s": 11110, "text": "and you want to benchmark your application with different combinations of db, schema and ui, then you can run:" }, { "code": null, "e": 11271, "s": 11221, "text": "python my_app.py db=postgresql schema=school.yaml" }, { "code": null, "e": 11280, "s": 11271, "text": "More ..." }, { "code": null, "e": 11445, "s": 11280, "text": "Hydra supports parameter sweep with --multirun, that runs multiple jobs at the same with different config files. For instance, for the previous example, we can run:" }, { "code": null, "e": 11517, "s": 11445, "text": "python my_app.py schema=warehouse,support,school db=mysql,postgresql -m" }, { "code": null, "e": 11564, "s": 11517, "text": "Then you basically start 6 jobs simultaneously" }, { "code": null, "e": 12069, "s": 11564, "text": "[2019-10-01 14:44:16,254] - Launching 6 jobs locally[2019-10-01 14:44:16,254] - Sweep output dir : multirun/2019-10-01/14-44-16[2019-10-01 14:44:16,254] - #0 : schema=warehouse db=mysql[2019-10-01 14:44:16,321] - #1 : schema=warehouse db=postgresql[2019-10-01 14:44:16,390] - #2 : schema=support db=mysql[2019-10-01 14:44:16,458] - #3 : schema=support db=postgresql[2019-10-01 14:44:16,527] - #4 : schema=school db=mysql[2019-10-01 14:44:16,602] - #5 : schema=school db=postgresql" }, { "code": null, "e": 12453, "s": 12069, "text": "In this article, I’ve talk about configuration management in Python in terms of WHY, WHAT and HOW. Depending on the usecase, a complex tool/framework isn’t always better than a simple package. No matter which one you choose, you should always think about its readbility, matainbility and how to spot the error as earily as possible. In fact, config file is just another type of code." } ]
Twitter Trends Analysis using Python | by Saiteja Kura | Towards Data Science
Twitter, launched in 2006 is one of the most popular social media platforms available today. It helps by providing insights into popular trends and important cultural and political moments. In the Data Science industry twitter analysis can be used for tasks like marketing or product analysis. Twitter data has been used to analyze political polarisation and the spread of protest movements. In this article, we will learn the process of collecting twitter data, processing twitter text, and mapping twitter data geographically. We will be dealing with a subset of data having keywords #python and #javascript. While collecting data, we are limited in two ways.1. Cannot collect data from the past(a year ago, etc.)2. Twitter only provides a sample of its data for free(like 1% of its data). However, a 1% sample of data is in order of a few million tweets a day. Many Social Media companies have APIs which are made available to third party developers and researchers. Twitter has many API’s available. According to tweepy docs, the Twitter streaming API is used to download twitter messages in real-time. It is useful for obtaining a high volume of tweets, or for creating a live feed using a site stream or user stream. It has two endpoints filter and sample. With a filter endpoint, users can request data using a few hundred keywords, a few thousand usernames, and 25 location ranges. With a sample endpoint, twitter will return 1 % of all twitter data. To collect data from Streaming API we will be using a package called tweepy which abstracts the work of setting up a stable Streaming API connection. We need to have our own twitter account and API keys for authentication. tweepy requires an object called SListener which tells it how to handle incoming data. This SListener object opens a new timestamp file to store tweets and takes an optional API Argument. The below code will run until explicitly stopped(More the execution time, more the number of Twitter JSON objects in our file). The dataset in this article consists of 685 tweets(Twitter JSON objects) which were fetched from 7:39 pm IST to 7:44 pm IST. Now a file named tweets.json will contain the JSON objects. The number of JSON objects depends on the opening and closing of the above connection. json data format is a special data format that is human-readable and is easily transferred between machines. It is a combination of dictionaries and lists. Each JSON object has many child objects. In our case the main JSON object describes the main tweet, favourites_count, retweet_count, etc. and has nested dictionaries that describe the user, location, etc. To analyze tweets at scale, it is better to store these tweets in a Pandas DataFrame. This allows us to apply analysis methods across rows and columns. However, with nested dictionaries the JSON object is complex. To overcome this problem, we will flatten the JSON object(maintain all attributes at one level instead of nesting). Let us load the tweets list into a DataFrame. df_tweet = pd.DataFrame(tweets) Now let us compare the number of tweets having #python and #javascript. Let us write a function that will check for the given hashtag in all the text columns and return a series of boolean values indicating whether each row has that keyword or not. We can notice that #python holds a slight lead over #javascript. Now, let us try and understand how mentions of the above two keywords change over time. Tweets about products, companies vary a lot wrt time. Let us try and capture the variation over time. When data is tagged with date and time it is known as Time Series data. Firstly let us convert the created_at column to type DateTime. We need to create a metric that can be graphed over time. Let us create two columns python and js which consists of boolean values. Now let us create a per minute average of mentions of both the hashtags and plot them across time. We will be using a Series method resample() that will allow us to summarize over a time window of our choice and apply an aggregate function to it. resample(“1 min”).mean() will group the data minute wise and apply mean function to the grouped data. As I already mentioned we fetched data from 7:39 pm to 7:44 pm we can notice that the minute's axis has values from 39 to 44 and we can notice how the frequency varies wrt time. Sentiment analysis is a method of deriving meaning from text. It is a type of natural language processing method which determines whether a word, sentence, paragraph, document is positive or negative. Each document is given a positive or negative score based on the number of positive and negative words. This can be used to analyze the reactions over a product, company, etc. We will use the VADER SentimentIntensityAnalyzer included in the Natural Language Toolkit or nltk. It is useful for analyzing short documents especially tweets. Considers emojis and capitalization of words too. Each Sentiment score from the VADER Analyzer provides 4 values. Negative, Positive, Neutral, and Compound. The first 3 are self-explanatory and range between 0 and 1 whereas the compound value ranges from-1 to 1. Closer to 1 indicates positive and -1 indicates negative. We will again resample data minute-wise and find sentiment scores for every minute. We can notice that, in the small subset of data we have, there are no negative tweets whereas javascript has more positive tweets in comparison to python. We can sample data day-wise, month-wise depending on the data we collect and perform similar analyses to generate more insights. The full code can be found here. In this article, we learned how to fetch information from an API and we also learned how to deal with JSON data and perform time-series analysis on it. Much emphasis was not put on the internal explanation of Sentiment Analysis which would be covered in my future articles. As a part of my upcoming network analysis series, I will illustrate the network analysis of Twitter data using graph data structure. Thanks for reading and feel free to share feedback! Stay home and stay safe.
[ { "code": null, "e": 783, "s": 172, "text": "Twitter, launched in 2006 is one of the most popular social media platforms available today. It helps by providing insights into popular trends and important cultural and political moments. In the Data Science industry twitter analysis can be used for tasks like marketing or product analysis. Twitter data has been used to analyze political polarisation and the spread of protest movements. In this article, we will learn the process of collecting twitter data, processing twitter text, and mapping twitter data geographically. We will be dealing with a subset of data having keywords #python and #javascript." }, { "code": null, "e": 964, "s": 783, "text": "While collecting data, we are limited in two ways.1. Cannot collect data from the past(a year ago, etc.)2. Twitter only provides a sample of its data for free(like 1% of its data)." }, { "code": null, "e": 1176, "s": 964, "text": "However, a 1% sample of data is in order of a few million tweets a day. Many Social Media companies have APIs which are made available to third party developers and researchers. Twitter has many API’s available." }, { "code": null, "e": 1854, "s": 1176, "text": "According to tweepy docs, the Twitter streaming API is used to download twitter messages in real-time. It is useful for obtaining a high volume of tweets, or for creating a live feed using a site stream or user stream. It has two endpoints filter and sample. With a filter endpoint, users can request data using a few hundred keywords, a few thousand usernames, and 25 location ranges. With a sample endpoint, twitter will return 1 % of all twitter data. To collect data from Streaming API we will be using a package called tweepy which abstracts the work of setting up a stable Streaming API connection. We need to have our own twitter account and API keys for authentication." }, { "code": null, "e": 2295, "s": 1854, "text": "tweepy requires an object called SListener which tells it how to handle incoming data. This SListener object opens a new timestamp file to store tweets and takes an optional API Argument. The below code will run until explicitly stopped(More the execution time, more the number of Twitter JSON objects in our file). The dataset in this article consists of 685 tweets(Twitter JSON objects) which were fetched from 7:39 pm IST to 7:44 pm IST." }, { "code": null, "e": 2442, "s": 2295, "text": "Now a file named tweets.json will contain the JSON objects. The number of JSON objects depends on the opening and closing of the above connection." }, { "code": null, "e": 2803, "s": 2442, "text": "json data format is a special data format that is human-readable and is easily transferred between machines. It is a combination of dictionaries and lists. Each JSON object has many child objects. In our case the main JSON object describes the main tweet, favourites_count, retweet_count, etc. and has nested dictionaries that describe the user, location, etc." }, { "code": null, "e": 3133, "s": 2803, "text": "To analyze tweets at scale, it is better to store these tweets in a Pandas DataFrame. This allows us to apply analysis methods across rows and columns. However, with nested dictionaries the JSON object is complex. To overcome this problem, we will flatten the JSON object(maintain all attributes at one level instead of nesting)." }, { "code": null, "e": 3179, "s": 3133, "text": "Let us load the tweets list into a DataFrame." }, { "code": null, "e": 3211, "s": 3179, "text": "df_tweet = pd.DataFrame(tweets)" }, { "code": null, "e": 3460, "s": 3211, "text": "Now let us compare the number of tweets having #python and #javascript. Let us write a function that will check for the given hashtag in all the text columns and return a series of boolean values indicating whether each row has that keyword or not." }, { "code": null, "e": 3787, "s": 3460, "text": "We can notice that #python holds a slight lead over #javascript. Now, let us try and understand how mentions of the above two keywords change over time. Tweets about products, companies vary a lot wrt time. Let us try and capture the variation over time. When data is tagged with date and time it is known as Time Series data." }, { "code": null, "e": 3982, "s": 3787, "text": "Firstly let us convert the created_at column to type DateTime. We need to create a metric that can be graphed over time. Let us create two columns python and js which consists of boolean values." }, { "code": null, "e": 4229, "s": 3982, "text": "Now let us create a per minute average of mentions of both the hashtags and plot them across time. We will be using a Series method resample() that will allow us to summarize over a time window of our choice and apply an aggregate function to it." }, { "code": null, "e": 4331, "s": 4229, "text": "resample(“1 min”).mean() will group the data minute wise and apply mean function to the grouped data." }, { "code": null, "e": 4509, "s": 4331, "text": "As I already mentioned we fetched data from 7:39 pm to 7:44 pm we can notice that the minute's axis has values from 39 to 44 and we can notice how the frequency varies wrt time." }, { "code": null, "e": 4886, "s": 4509, "text": "Sentiment analysis is a method of deriving meaning from text. It is a type of natural language processing method which determines whether a word, sentence, paragraph, document is positive or negative. Each document is given a positive or negative score based on the number of positive and negative words. This can be used to analyze the reactions over a product, company, etc." }, { "code": null, "e": 5097, "s": 4886, "text": "We will use the VADER SentimentIntensityAnalyzer included in the Natural Language Toolkit or nltk. It is useful for analyzing short documents especially tweets. Considers emojis and capitalization of words too." }, { "code": null, "e": 5452, "s": 5097, "text": "Each Sentiment score from the VADER Analyzer provides 4 values. Negative, Positive, Neutral, and Compound. The first 3 are self-explanatory and range between 0 and 1 whereas the compound value ranges from-1 to 1. Closer to 1 indicates positive and -1 indicates negative. We will again resample data minute-wise and find sentiment scores for every minute." }, { "code": null, "e": 5607, "s": 5452, "text": "We can notice that, in the small subset of data we have, there are no negative tweets whereas javascript has more positive tweets in comparison to python." }, { "code": null, "e": 5736, "s": 5607, "text": "We can sample data day-wise, month-wise depending on the data we collect and perform similar analyses to generate more insights." }, { "code": null, "e": 5769, "s": 5736, "text": "The full code can be found here." }, { "code": null, "e": 6176, "s": 5769, "text": "In this article, we learned how to fetch information from an API and we also learned how to deal with JSON data and perform time-series analysis on it. Much emphasis was not put on the internal explanation of Sentiment Analysis which would be covered in my future articles. As a part of my upcoming network analysis series, I will illustrate the network analysis of Twitter data using graph data structure." } ]
Plotting Maps with GeoPandas. Beginners Guide to Geospatial Data... | by Ryan Lewis | Towards Data Science
Recently, in my data science program, we were given a project where we needed create a model to predict house prices. The training data set we received included property data relating to square feet, bathroom count, construction grade, etc. The data I was most excited to begin my analysis with was the location data. We were given columns containing the latitude and the longitude coordinates and instantly the first thing I wanted to do was to create a heat map showing the distribution of property prices. Let’s take a peek at our data: import pandas as pdimport numpy as npimport geopandas as gpdimport matplotlib.pyplot as pltfrom shapely.geometry import Point, Polygondf = pd.read_csv('kc_house_data_train.csv')df = df[['id', 'price', 'sqft_living', 'waterfront', 'zipcode', 'long', 'lat']]df.head() Before we can plot these coordinates, we need a ‘shapefile’ to plot them on top of. If you’re like me, and new to plotting geospatial data, ‘shapefiles’ were a very foreign topic. Luckily for you I found this great description : “The shapefile format is a digital vector storage format for storing geometric location and associated attribute information.” Basically, coding languages like Python utilizing Geopandas can read shapefiles and transform them into functioning maps that you are able to plot on. Much to my surprise, shapefiles are readily available from a lot of open-source databases online. Shapefiles are designated as ‘.shp’ — the shape format/geometry file; but they also depend on the associated ‘.shx’ — shape index format, and the ‘.dbf’ — attribute format files to properly function. So, in order to utilize the ‘.shp’ file in GeoPandas, you must also save the other two mandatory file extensions in the same directory. Let's take a look at our shapefile in Python. kings_county_map = gpd.read_file('kc_tract_10.shp')kings_county_map.plot() Now we have the outline of our dataset’s location (King County, WA.) You might notice that our axis is not referring to latitude and longitude coordinates. This can be adjusted using the Coordinate Reference System or CRS. The most common CRS used is WGS84 lat/long projection. kings_county_map.to_crs(epsg=4326).plot() Now that we have our shapefile mapped to our proper coordinates we can start to format our real estate data. In order for to see where the properties in our dataframe are located, we first need to reformat our data into a ‘GeoPandas Dataframe.’ crs = {'init':'EPSG:4326'}geometry = [Point(xy) for xy in zip(df['long'], df['lat'])]geo_df = gpd.GeoDataFrame(df, crs = crs, geometry = geometry) To match the ‘shapefile’ we need specify the same CRS. Next we need to utilize Shapely to transform our latitude and longitude data into geometric points. Finally passing our original dataframe with our ‘crs’ and ‘geometry’ variables into the GeoDataFrame function will create our ‘geo_df’ that is a copy of our original data frame but with the newly created ‘geometry’ column. geo_df.head() Now that both our shapefile and GeoPandas dataframe are properly formatted we can begin the fun part of visualizing our real estate data! Let’s plot the location of our property data on top of our shapefile map. By utilizing Matplotlib’s subplots we can plot both of our data sets on the same axis and see where the properties are located. fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(ax=ax)ax.set_title('Kings County Real Estate') We can see that the majority of King County properties are located in the western part of the county. Though, it’s hard to tell if there are more houses north or south due to how dense are points are being plotted. fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(ax=ax, alpha = .1 )ax.set_title('Kings County Real Estate')plt.savefig('Property Map') By reducing the alpha in our GeoPandas plot, we can now see there are more houses located in the northwestern part of the county as the blue plots are a lot more dense compared to the south. Now this is great and all — we can see the locations of the properties, but what is the top factor when determining the right house? Price. We are able to use this same plot, but we can specify the price column in our dataframe to create a heatmap! (Note, we log transformed our price data to reduce how outliers were skewing our data.) geo_df['price_log'] = np.log(geo_df['price'])fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(column = 'price_log', ax=ax, cmap = 'rainbow', legend = True, legend_kwds={'shrink': 0.3}, markersize = 10)ax.set_title('Kings County Price Heatmap')plt.savefig('Heat Map') Finally, we can now easily see where the higher priced homes are located in Kings County! This makes sense as that circle of red in the northwest encapsulates Seattle and Medina (Home to both Bill Gates & Jeff Bezos.) If we wanted to see this same plot but for square feet of the properties we can: geo_df['sqft_log'] = np.log(geo_df['sqft_living'])fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(column = 'sqft_log', ax=ax, cmap = 'winter', legend = True, legend_kwds={'shrink': 0.3}, alpha = .5)ax.set_title('Sqft Heatmap') We can see now that houses tend to have more square feet east of longitude -122.3 as we move further away from Seattle. I hope this quick tutorial was helpful in understanding how to use GeoPandas and understand why it is such a powerful tool. Using GeoPandas is a great way to visualize geospatial data during any exploratory data analysis. It provides a way to make inferences about your data set and most importantly it brings data to life for everyone to see.
[ { "code": null, "e": 681, "s": 172, "text": "Recently, in my data science program, we were given a project where we needed create a model to predict house prices. The training data set we received included property data relating to square feet, bathroom count, construction grade, etc. The data I was most excited to begin my analysis with was the location data. We were given columns containing the latitude and the longitude coordinates and instantly the first thing I wanted to do was to create a heat map showing the distribution of property prices." }, { "code": null, "e": 712, "s": 681, "text": "Let’s take a peek at our data:" }, { "code": null, "e": 978, "s": 712, "text": "import pandas as pdimport numpy as npimport geopandas as gpdimport matplotlib.pyplot as pltfrom shapely.geometry import Point, Polygondf = pd.read_csv('kc_house_data_train.csv')df = df[['id', 'price', 'sqft_living', 'waterfront', 'zipcode', 'long', 'lat']]df.head()" }, { "code": null, "e": 1207, "s": 978, "text": "Before we can plot these coordinates, we need a ‘shapefile’ to plot them on top of. If you’re like me, and new to plotting geospatial data, ‘shapefiles’ were a very foreign topic. Luckily for you I found this great description :" }, { "code": null, "e": 1334, "s": 1207, "text": "“The shapefile format is a digital vector storage format for storing geometric location and associated attribute information.”" }, { "code": null, "e": 1965, "s": 1334, "text": "Basically, coding languages like Python utilizing Geopandas can read shapefiles and transform them into functioning maps that you are able to plot on. Much to my surprise, shapefiles are readily available from a lot of open-source databases online. Shapefiles are designated as ‘.shp’ — the shape format/geometry file; but they also depend on the associated ‘.shx’ — shape index format, and the ‘.dbf’ — attribute format files to properly function. So, in order to utilize the ‘.shp’ file in GeoPandas, you must also save the other two mandatory file extensions in the same directory. Let's take a look at our shapefile in Python." }, { "code": null, "e": 2040, "s": 1965, "text": "kings_county_map = gpd.read_file('kc_tract_10.shp')kings_county_map.plot()" }, { "code": null, "e": 2318, "s": 2040, "text": "Now we have the outline of our dataset’s location (King County, WA.) You might notice that our axis is not referring to latitude and longitude coordinates. This can be adjusted using the Coordinate Reference System or CRS. The most common CRS used is WGS84 lat/long projection." }, { "code": null, "e": 2360, "s": 2318, "text": "kings_county_map.to_crs(epsg=4326).plot()" }, { "code": null, "e": 2605, "s": 2360, "text": "Now that we have our shapefile mapped to our proper coordinates we can start to format our real estate data. In order for to see where the properties in our dataframe are located, we first need to reformat our data into a ‘GeoPandas Dataframe.’" }, { "code": null, "e": 2804, "s": 2605, "text": "crs = {'init':'EPSG:4326'}geometry = [Point(xy) for xy in zip(df['long'], df['lat'])]geo_df = gpd.GeoDataFrame(df, crs = crs, geometry = geometry)" }, { "code": null, "e": 3182, "s": 2804, "text": "To match the ‘shapefile’ we need specify the same CRS. Next we need to utilize Shapely to transform our latitude and longitude data into geometric points. Finally passing our original dataframe with our ‘crs’ and ‘geometry’ variables into the GeoDataFrame function will create our ‘geo_df’ that is a copy of our original data frame but with the newly created ‘geometry’ column." }, { "code": null, "e": 3196, "s": 3182, "text": "geo_df.head()" }, { "code": null, "e": 3536, "s": 3196, "text": "Now that both our shapefile and GeoPandas dataframe are properly formatted we can begin the fun part of visualizing our real estate data! Let’s plot the location of our property data on top of our shapefile map. By utilizing Matplotlib’s subplots we can plot both of our data sets on the same axis and see where the properties are located." }, { "code": null, "e": 3701, "s": 3536, "text": "fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(ax=ax)ax.set_title('Kings County Real Estate')" }, { "code": null, "e": 3916, "s": 3701, "text": "We can see that the majority of King County properties are located in the western part of the county. Though, it’s hard to tell if there are more houses north or south due to how dense are points are being plotted." }, { "code": null, "e": 4121, "s": 3916, "text": "fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(ax=ax, alpha = .1 )ax.set_title('Kings County Real Estate')plt.savefig('Property Map')" }, { "code": null, "e": 4312, "s": 4121, "text": "By reducing the alpha in our GeoPandas plot, we can now see there are more houses located in the northwestern part of the county as the blue plots are a lot more dense compared to the south." }, { "code": null, "e": 4649, "s": 4312, "text": "Now this is great and all — we can see the locations of the properties, but what is the top factor when determining the right house? Price. We are able to use this same plot, but we can specify the price column in our dataframe to create a heatmap! (Note, we log transformed our price data to reduce how outliers were skewing our data.)" }, { "code": null, "e": 5008, "s": 4649, "text": "geo_df['price_log'] = np.log(geo_df['price'])fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(column = 'price_log', ax=ax, cmap = 'rainbow', legend = True, legend_kwds={'shrink': 0.3}, markersize = 10)ax.set_title('Kings County Price Heatmap')plt.savefig('Heat Map')" }, { "code": null, "e": 5307, "s": 5008, "text": "Finally, we can now easily see where the higher priced homes are located in Kings County! This makes sense as that circle of red in the northwest encapsulates Seattle and Medina (Home to both Bill Gates & Jeff Bezos.) If we wanted to see this same plot but for square feet of the properties we can:" }, { "code": null, "e": 5626, "s": 5307, "text": "geo_df['sqft_log'] = np.log(geo_df['sqft_living'])fig, ax = plt.subplots(figsize = (10,10))kings_county_map.to_crs(epsg=4326).plot(ax=ax, color='lightgrey')geo_df.plot(column = 'sqft_log', ax=ax, cmap = 'winter', legend = True, legend_kwds={'shrink': 0.3}, alpha = .5)ax.set_title('Sqft Heatmap')" }, { "code": null, "e": 5746, "s": 5626, "text": "We can see now that houses tend to have more square feet east of longitude -122.3 as we move further away from Seattle." } ]
Declare syntax error in MySQL Workbench?
The DECLARE syntax must between BEGIN and END. The syntax is as follows − BEGIN DECLARE yourVariableName1 dataType, DECLARE yourVariableName2 dataType, . . . . END Here is the query to avoid DECLARE syntax error in MySQL − mysql> DELIMITER // mysql> create procedure declare_Demo() -> BEGIN -> DECLARE Name varchar(100); -> SET Name: ='John'; -> SELECT Name; -> END -> // Query OK, 0 rows affected (0.17 sec) mysql> DELIMITER ; Call the stored procedure with the help of CALL command. The syntax is as follows − CALL yourStoredProcedureName(); The query is as follows − mysql> call declare_Demo(); The following is the output − +------+ | Name | +------+ | John | +------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
[ { "code": null, "e": 1136, "s": 1062, "text": "The DECLARE syntax must between BEGIN and END. The syntax is as follows −" }, { "code": null, "e": 1226, "s": 1136, "text": "BEGIN\nDECLARE yourVariableName1 dataType,\nDECLARE yourVariableName2 dataType,\n.\n.\n.\n.\nEND" }, { "code": null, "e": 1285, "s": 1226, "text": "Here is the query to avoid DECLARE syntax error in MySQL −" }, { "code": null, "e": 1508, "s": 1285, "text": "mysql> DELIMITER //\nmysql> create procedure declare_Demo()\n -> BEGIN\n -> DECLARE Name varchar(100);\n -> SET Name: ='John';\n -> SELECT Name;\n -> END\n -> //\nQuery OK, 0 rows affected (0.17 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1592, "s": 1508, "text": "Call the stored procedure with the help of CALL command. The syntax is as follows −" }, { "code": null, "e": 1624, "s": 1592, "text": "CALL yourStoredProcedureName();" }, { "code": null, "e": 1650, "s": 1624, "text": "The query is as follows −" }, { "code": null, "e": 1678, "s": 1650, "text": "mysql> call declare_Demo();" }, { "code": null, "e": 1708, "s": 1678, "text": "The following is the output −" }, { "code": null, "e": 1814, "s": 1708, "text": "+------+\n| Name |\n+------+\n| John |\n+------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.01 sec)" } ]
ZonedDateTime equals() method in Java with Examples - GeeksforGeeks
10 May, 2019 The equals() method of ZonedDateTime class in Java is used to compare this ZonedDateTime to the another date-time object passed as parameter. The comparison is based on the offset date-time and the zone. Only objects of type ZonedDateTime are compared with each other and other types return false. The value to be returned by this method is determined as follows: if both ZonedDateTime are equal, then true is returned. if both ZonedDateTime are not equal, then false is returned. Syntax: public boolean equals(Object obj) Parameters: This method accepts a single parameter obj which represents the object to compare with this ZonedDateTime. This is a mandatory parameter and it should not be null. Return value: This method returns true if both ZonedDateTime are equal else false. Below programs illustrate the equals() method:Program 1: // Java program to demonstrate// ZonedDateTime.equals() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime1 = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); ZonedDateTime zoneddatetime2 = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // apply equals() boolean value = zoneddatetime1.equals(zoneddatetime2); // print result System.out.println("Both ZonedDateTime are equal: " + value); }} Both ZonedDateTime are equal: true Program 2: // Java program to demonstrate// ZonedDateTime.equals() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime1 = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); ZonedDateTime zoneddatetime2 = ZonedDateTime.parse("2018-12-16T20:28:33.213+05:30[Asia/Calcutta]"); // apply equals() boolean value = zoneddatetime1.equals(zoneddatetime2); // print result System.out.println("Both ZonedDateTime are equal: " + value); }} Both ZonedDateTime are equal: false Reference:https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#equals(java.lang.Object) Kirti_Mangal Java-Functions Java-time package Java-ZonedDateTime Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23868, "s": 23840, "text": "\n10 May, 2019" }, { "code": null, "e": 24232, "s": 23868, "text": "The equals() method of ZonedDateTime class in Java is used to compare this ZonedDateTime to the another date-time object passed as parameter. The comparison is based on the offset date-time and the zone. Only objects of type ZonedDateTime are compared with each other and other types return false. The value to be returned by this method is determined as follows:" }, { "code": null, "e": 24288, "s": 24232, "text": "if both ZonedDateTime are equal, then true is returned." }, { "code": null, "e": 24349, "s": 24288, "text": "if both ZonedDateTime are not equal, then false is returned." }, { "code": null, "e": 24357, "s": 24349, "text": "Syntax:" }, { "code": null, "e": 24392, "s": 24357, "text": "public boolean equals(Object obj)\n" }, { "code": null, "e": 24568, "s": 24392, "text": "Parameters: This method accepts a single parameter obj which represents the object to compare with this ZonedDateTime. This is a mandatory parameter and it should not be null." }, { "code": null, "e": 24651, "s": 24568, "text": "Return value: This method returns true if both ZonedDateTime are equal else false." }, { "code": null, "e": 24708, "s": 24651, "text": "Below programs illustrate the equals() method:Program 1:" }, { "code": "// Java program to demonstrate// ZonedDateTime.equals() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime1 = ZonedDateTime.parse(\"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); ZonedDateTime zoneddatetime2 = ZonedDateTime.parse(\"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // apply equals() boolean value = zoneddatetime1.equals(zoneddatetime2); // print result System.out.println(\"Both ZonedDateTime are equal: \" + value); }}", "e": 25327, "s": 24708, "text": null }, { "code": null, "e": 25363, "s": 25327, "text": "Both ZonedDateTime are equal: true\n" }, { "code": null, "e": 25374, "s": 25363, "text": "Program 2:" }, { "code": "// Java program to demonstrate// ZonedDateTime.equals() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime1 = ZonedDateTime.parse(\"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); ZonedDateTime zoneddatetime2 = ZonedDateTime.parse(\"2018-12-16T20:28:33.213+05:30[Asia/Calcutta]\"); // apply equals() boolean value = zoneddatetime1.equals(zoneddatetime2); // print result System.out.println(\"Both ZonedDateTime are equal: \" + value); }}", "e": 25993, "s": 25374, "text": null }, { "code": null, "e": 26030, "s": 25993, "text": "Both ZonedDateTime are equal: false\n" }, { "code": null, "e": 26137, "s": 26030, "text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#equals(java.lang.Object)" }, { "code": null, "e": 26150, "s": 26137, "text": "Kirti_Mangal" }, { "code": null, "e": 26165, "s": 26150, "text": "Java-Functions" }, { "code": null, "e": 26183, "s": 26165, "text": "Java-time package" }, { "code": null, "e": 26202, "s": 26183, "text": "Java-ZonedDateTime" }, { "code": null, "e": 26207, "s": 26202, "text": "Java" }, { "code": null, "e": 26212, "s": 26207, "text": "Java" }, { "code": null, "e": 26310, "s": 26212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26319, "s": 26310, "text": "Comments" }, { "code": null, "e": 26332, "s": 26319, "text": "Old Comments" }, { "code": null, "e": 26353, "s": 26332, "text": "Constructors in Java" }, { "code": null, "e": 26368, "s": 26353, "text": "Stream In Java" }, { "code": null, "e": 26387, "s": 26368, "text": "Exceptions in Java" }, { "code": null, "e": 26417, "s": 26387, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26463, "s": 26417, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26489, "s": 26463, "text": "Java Programming Examples" }, { "code": null, "e": 26525, "s": 26489, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 26565, "s": 26525, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 26581, "s": 26565, "text": "Strings in Java" } ]
C++ Program to Implement Queue using Linked List
A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first. In other words, the least recently added element is removed first in a queue. A program that implements the queue using linked list is given as follows − #include <iostream> using namespace std; struct node { int data; struct node *next; }; struct node* front = NULL; struct node* rear = NULL; struct node* temp; void Insert() { int val; cout<<"Insert the element in queue : "<<endl; cin>>val; if (rear == NULL) { rear = (struct node *)malloc(sizeof(struct node)); rear->next = NULL; rear->data = val; front = rear; } else { temp=(struct node *)malloc(sizeof(struct node)); rear->next = temp; temp->data = val; temp->next = NULL; rear = temp; } } void Delete() { temp = front; if (front == NULL) { cout<<"Underflow"<<endl; return; } else if (temp->next != NULL) { temp = temp->next; cout<<"Element deleted from queue is : "<<front->data<<endl; free(front); front = temp; } else { cout<<"Element deleted from queue is : "<<front->data<<endl; free(front); front = NULL; rear = NULL; } } void Display() { temp = front; if ((front == NULL) && (rear == NULL)) { cout<<"Queue is empty"<<endl; return; } cout<<"Queue elements are: "; while (temp != NULL) { cout<<temp->data<<" "; temp = temp->next; } cout<<endl; } int main() { int ch; cout<<"1) Insert element to queue"<<endl; cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter your choice : "<<endl; cin>>ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"<<endl; break; default: cout<<"Invalid choice"<<endl; } } while(ch!=4); return 0; } The output of the above program is as follows 1) Insert element to queue 2) Delete element from queue 3) Display all the elements of queue 4) Exit Enter your choice : 1 Insert the element in queue : 4 Enter your choice : 1 Insert the element in queue : 3 Enter your choice : 1 Insert the element in queue : 5 Enter your choice : 2 Element deleted from queue is : 4 Enter your choice : 3 Queue elements are : 3 5 Enter your choice : 7 Invalid choice Enter your choice : 4 Exit In the above program, the function Insert() inserts an element into the queue. If rear is NULL,then the queue is empty and a single element is inserted. Otherwise, a node is inserted after rear with the required element and then that node is set to rear. This is shown below − void Insert() { int val; cout<<"Insert the element in queue : "<<endl; cin>>val; if (rear == NULL) { rear = (struct node *)malloc(sizeof(struct node)); rear->next = NULL; rear->data = val; front = rear; } else { temp=(struct node *)malloc(sizeof(struct node)); rear->next = temp; temp->data = val; temp->next = NULL; rear = temp; } } In the function Delete(), if there are no elements in queue then it is underflow condition. If there is only one element in the queue that is deleted and front and rear are set to NULL. Otherwise, the element at front is deleted and front points to next element. This is shown below − void Delete() { temp = front; if (front == NULL) { cout<<"Underflow"<<endl; return; } else if (temp->next != NULL) { temp = temp->next; cout<<"Element deleted from queue is : "<<front->data<<endl; free(front); front = temp; } else { cout<<"Element deleted from queue is : "<<front->data<<endl; free(front); front = NULL; rear = NULL; } } In the function display(), if front and rear are NULL then queue is empty. Otherwise, all the queue elements are displayed using a while loop with the help of temp variable. This is shown below − void Display() { temp = front; if ((front == NULL) && (rear == NULL)) { cout<<"Queue is empty"<<endl; return; } cout<<"Queue elements are: "; while (temp != NULL) { cout<<temp->data<<" "; temp = temp->next; } cout<<endl; } The function main() provides a choice to the user if they want to insert, delete or display the queue. According to the user response, the appropriate function is called using switch. If the user enters an invalid response, then that is printed. The code snippet for this is given below − int main() { int ch; cout<<"1) Insert element to queue"<<endl; cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter your choice : "<<endl; cin>>ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"<<endl; break; default: cout<<"Invalid choice"<<endl; } } while(ch!=4); return 0; }
[ { "code": null, "e": 1316, "s": 1062, "text": "A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first. In other words, the least recently added element is removed first in a queue." }, { "code": null, "e": 1392, "s": 1316, "text": "A program that implements the queue using linked list is given as follows −" }, { "code": null, "e": 3205, "s": 1392, "text": "#include <iostream>\nusing namespace std;\nstruct node {\n int data;\n struct node *next;\n};\nstruct node* front = NULL;\nstruct node* rear = NULL;\nstruct node* temp;\nvoid Insert() {\n int val;\n cout<<\"Insert the element in queue : \"<<endl;\n cin>>val;\n if (rear == NULL) {\n rear = (struct node *)malloc(sizeof(struct node));\n rear->next = NULL;\n rear->data = val;\n front = rear;\n } else {\n temp=(struct node *)malloc(sizeof(struct node));\n rear->next = temp;\n temp->data = val;\n temp->next = NULL;\n rear = temp;\n }\n}\nvoid Delete() {\n temp = front;\n if (front == NULL) {\n cout<<\"Underflow\"<<endl;\n return;\n }\n else\n if (temp->next != NULL) {\n temp = temp->next;\n cout<<\"Element deleted from queue is : \"<<front->data<<endl;\n free(front);\n front = temp;\n } else {\n cout<<\"Element deleted from queue is : \"<<front->data<<endl;\n free(front);\n front = NULL;\n rear = NULL;\n }\n}\nvoid Display() {\n temp = front;\n if ((front == NULL) && (rear == NULL)) {\n cout<<\"Queue is empty\"<<endl;\n return;\n }\n cout<<\"Queue elements are: \";\n while (temp != NULL) {\n cout<<temp->data<<\" \";\n temp = temp->next;\n }\n cout<<endl;\n}\nint main() {\n int ch;\n cout<<\"1) Insert element to queue\"<<endl;\n cout<<\"2) Delete element from queue\"<<endl;\n cout<<\"3) Display all the elements of queue\"<<endl;\n cout<<\"4) Exit\"<<endl;\n do {\n cout<<\"Enter your choice : \"<<endl;\n cin>>ch;\n switch (ch) {\n case 1: Insert();\n break;\n case 2: Delete();\n break;\n case 3: Display();\n break;\n case 4: cout<<\"Exit\"<<endl;\n break;\n default: cout<<\"Invalid choice\"<<endl;\n }\n } while(ch!=4);\n return 0;\n}" }, { "code": null, "e": 3251, "s": 3205, "text": "The output of the above program is as follows" }, { "code": null, "e": 3681, "s": 3251, "text": "1) Insert element to queue\n2) Delete element from queue\n3) Display all the elements of queue\n4) Exit\nEnter your choice : 1\nInsert the element in queue : 4\nEnter your choice : 1\nInsert the element in queue : 3\nEnter your choice : 1\nInsert the element in queue : 5\nEnter your choice : 2\nElement deleted from queue is : 4\nEnter your choice : 3\nQueue elements are : 3 5\nEnter your choice : 7\nInvalid choice\nEnter your choice : 4\nExit" }, { "code": null, "e": 3958, "s": 3681, "text": "In the above program, the function Insert() inserts an element into the queue. If rear is NULL,then the queue is empty and a single element is inserted. Otherwise, a node is inserted after rear with the required element and then that node is set to rear. This is shown below −" }, { "code": null, "e": 4364, "s": 3958, "text": "void Insert() {\n int val;\n cout<<\"Insert the element in queue : \"<<endl;\n cin>>val;\n if (rear == NULL) {\n rear = (struct node *)malloc(sizeof(struct node));\n rear->next = NULL;\n rear->data = val;\n front = rear;\n } else {\n temp=(struct node *)malloc(sizeof(struct node));\n rear->next = temp;\n temp->data = val;\n temp->next = NULL;\n rear = temp;\n }\n}" }, { "code": null, "e": 4649, "s": 4364, "text": "In the function Delete(), if there are no elements in queue then it is underflow condition. If there is only one element in the queue that is deleted and front and rear are set to NULL. Otherwise, the element at front is deleted and front points to next element. This is shown below −" }, { "code": null, "e": 5065, "s": 4649, "text": "void Delete() {\n temp = front;\n if (front == NULL) {\n cout<<\"Underflow\"<<endl;\n return;\n } else\n if (temp->next != NULL) {\n temp = temp->next;\n cout<<\"Element deleted from queue is : \"<<front->data<<endl;\n free(front);\n front = temp;\n } else {\n cout<<\"Element deleted from queue is : \"<<front->data<<endl;\n free(front);\n front = NULL;\n rear = NULL;\n }\n}" }, { "code": null, "e": 5261, "s": 5065, "text": "In the function display(), if front and rear are NULL then queue is empty. Otherwise, all the queue elements are displayed using a while loop with the help of temp variable. This is shown below −" }, { "code": null, "e": 5529, "s": 5261, "text": "void Display() {\n temp = front;\n if ((front == NULL) && (rear == NULL)) {\n cout<<\"Queue is empty\"<<endl;\n return;\n }\n cout<<\"Queue elements are: \";\n while (temp != NULL) {\n cout<<temp->data<<\" \";\n temp = temp->next;\n }\n cout<<endl;\n}" }, { "code": null, "e": 5818, "s": 5529, "text": "The function main() provides a choice to the user if they want to insert, delete or display the queue. According to the user response, the appropriate function is called using switch. If the user enters an invalid response, then that is printed. The code snippet for this is given below −" }, { "code": null, "e": 6373, "s": 5818, "text": "int main() {\n int ch;\n cout<<\"1) Insert element to queue\"<<endl;\n cout<<\"2) Delete element from queue\"<<endl;\n cout<<\"3) Display all the elements of queue\"<<endl;\n cout<<\"4) Exit\"<<endl;\n do {\n cout<<\"Enter your choice : \"<<endl;\n cin>>ch;\n switch (ch) {\n case 1: Insert();\n break;\n case 2: Delete();\n break;\n case 3: Display();\n break;\n case 4: cout<<\"Exit\"<<endl;\n break;\n default: cout<<\"Invalid choice\"<<endl;\n }\n } while(ch!=4);\n return 0;\n}" } ]
Beyond Single Point Estimations using Neural Networks | by Elliott Zhu | Towards Data Science
Machine learning algorithms often estimate the first moment (i.e., the mean) of an unknown data generating process. However, applications that go beyond the first moment of distribution fitting can be found in a wide variety of different fields, such as economy [2], engineering [3] and natural sciences [4]. For example, a neural network that is looking at financial markets and attempting to guide investors may calculate the probability of the stock market movement in additional to the direction of the movement. To do so, it could use a Probability Density Function in order to calculate the total probability that the continuous random variable range will occur. Traditional approaches for density estimation (such as here) are based on the preliminary choice of a statistical model of the function and subsequent fitting on its parameters. For example, a neural network outputs the mean (μ) and the standard deviation (σ) parameters would be sufficient to describe the density function of a normal distribution: However, what id. the priori knowledge on the data generating process is not available? An alternative approach based on Bayesian statistics was first proposed in this early work by Aristidis Likas [1]. This simple but effective method does not require any assumption on the available data, but extracts the probability density function from the output of a neural network, that is trained with a suitable database including the original data and some ad hoc created data with known distribution. Unfortunately, the original implementation does not fit the modern computation environment, therefore, in this post, I will demonstrate how the method can be used in the context of Python and TensorFlow. For illustration purpose, we may create some simple data generating process such as the one below, where the outcome is generated using the conditional normal distribution of unit exponential Xs. Therefore, each individual will have their unique probability density function (PDF) conditioned on X. def hi_sample(N): fx = lambda x: np.random.normal(loc = np.mean(x[:,0:-1],1), size=N) X1 = np.random.exponential(1, size=N) X2 = np.random.exponential(1, size=N) Y = fx(np.array([X1,X2]).T) hi_data = [X1, X2, Y] return np.array(hi_data).Ttrain_array = hi_sample(5000) The generated Y will have the following distribution: Rather than going through all the math jargon in the original work, here, we highlight the essential steps required for implementation in python: Augment the original dataset with known data generating process (creating a prior distribution), which is from the reference PDF: P(ref). Here, we assume all individuals’ outcome in the augment dataset will be generated from a standard normal distribution: Augment the original dataset with known data generating process (creating a prior distribution), which is from the reference PDF: P(ref). Here, we assume all individuals’ outcome in the augment dataset will be generated from a standard normal distribution: train_array_0 = train_array.copy()train_array_0[:,-1] = metropolis_hastings_normal(train_array_0[:,-1]) #regenerate the outcome f(x) using metropolis_hastings simulators with a standard normal distribution. train_data = [train_array,train_array_0] 2. Fit the augmented dataset with a binary discrimination neural network which estimates the probability, y(X), that an observation pair X:=(x,f(x)) is generated from the pr(X) or from the target PDF: p(X). It can be a simple network like this: def simple_nn(dim_x): input_x = tfkl.Input(shape=(dim_x+1)) combined_layer = tfkl.Dense(dim_x)(input_x) for i in range(5): combined_layer = tfkl.Dense(dim_x)(combined_layer) combined_layer = tfkl.Dropout(0.1)(combined_layer) out = tfkl.Dense(1, activation='sigmoid')(combined_layer) model = tf.keras.Model(inputs = input_x, outputs=out) model.compile(loss = 'binary_crossentropy', optimizer=tf.keras.optimizers.RMSprop(lr=0.001)) return model 3. Compute the target probability density function using Bayes theory: Thus, training the NN with the purposely augmented data set produces a neural function y(X) from which the unknown PDF p(X) can be inferred, by using an intermediate arbitrary PDF pr(X): conditional_y = pdf_function_i(x).numpy()reference_dense = norm.pdf(x[:,-1]).reshape(-1, 1) #norm(loc = np.sum(x[:,0:-1],1)).pdf(x[:,-1]).reshape(-1, 1)conditional_dense = (conditional_y / np.clip(1 - conditional_y, a_min=1e-3, a_max=1.0)) * reference_dense Now lets plot the estimated PDF (conditional_dense) with the true PDF: Note here each individual point has a normal distribution conditioned on given X. Let’s see the estimations of a few other conditional distributions derived from standard density functions: We are able to get fairly accurate estimation of individual PDFs from different original data generating process using the same standard normal prior. Are we able to further improve the estimation? Yes. In another work by Leonardo Reyneri et al.[5], authors suggested using the estimated PDF, p’(X), from the initial estimation as the prior for the adjustment estimation. That is, we repeat step 1 to 2, with the standard normal prior being replaced by the p’(X), and in step three we estimate the following quantity: Thus, we can get the one step adjustment of the original estimation of PDF. The intuition behind this is similar as an autoencoder, where the estimated the PDF will be optimal if the neural network cannot distinguish the estimated PDF and the prior PDF. [1] Likas, A. (2001). Probability density estimation using artificial neural networks. Computer physics communications, 135(2), 167–175. [2] Combes, C., Dussauchoy, A.: Generalized extreme value distribution for fitting open- ing/closing asset prices and returns in stock-exchange. Springer Operational Re- search 6(1), 3–26 (2006) [3] Zaharim, A., Razali, A.M., Abidin, R.Z., Sopian, K.: Fitting of Statistical Dis- tributions to Wind Speed Data in Malaysia. European Journal of Scientific Re- search 26(1), 6–12 (2009) [4] Wendell Cropper Jr., P., Anderson, P.J.: Population dynamics of a tropical palm: use of a genetic algorithm for inverse parameter estimation. Ecological Modelling 177, 119–127 (2004) [5] Reyneri, L., Colla, V., & Vannucci, M. (2011, June). Estimate of a probability density function through neural networks. In International Work-Conference on Artificial Neural Networks(pp. 57–64). Springer, Berlin, Heidelberg.
[ { "code": null, "e": 841, "s": 172, "text": "Machine learning algorithms often estimate the first moment (i.e., the mean) of an unknown data generating process. However, applications that go beyond the first moment of distribution fitting can be found in a wide variety of different fields, such as economy [2], engineering [3] and natural sciences [4]. For example, a neural network that is looking at financial markets and attempting to guide investors may calculate the probability of the stock market movement in additional to the direction of the movement. To do so, it could use a Probability Density Function in order to calculate the total probability that the continuous random variable range will occur." }, { "code": null, "e": 1191, "s": 841, "text": "Traditional approaches for density estimation (such as here) are based on the preliminary choice of a statistical model of the function and subsequent fitting on its parameters. For example, a neural network outputs the mean (μ) and the standard deviation (σ) parameters would be sufficient to describe the density function of a normal distribution:" }, { "code": null, "e": 1892, "s": 1191, "text": "However, what id. the priori knowledge on the data generating process is not available? An alternative approach based on Bayesian statistics was first proposed in this early work by Aristidis Likas [1]. This simple but effective method does not require any assumption on the available data, but extracts the probability density function from the output of a neural network, that is trained with a suitable database including the original data and some ad hoc created data with known distribution. Unfortunately, the original implementation does not fit the modern computation environment, therefore, in this post, I will demonstrate how the method can be used in the context of Python and TensorFlow." }, { "code": null, "e": 2191, "s": 1892, "text": "For illustration purpose, we may create some simple data generating process such as the one below, where the outcome is generated using the conditional normal distribution of unit exponential Xs. Therefore, each individual will have their unique probability density function (PDF) conditioned on X." }, { "code": null, "e": 2478, "s": 2191, "text": "def hi_sample(N): fx = lambda x: np.random.normal(loc = np.mean(x[:,0:-1],1), size=N) X1 = np.random.exponential(1, size=N) X2 = np.random.exponential(1, size=N) Y = fx(np.array([X1,X2]).T) hi_data = [X1, X2, Y] return np.array(hi_data).Ttrain_array = hi_sample(5000)" }, { "code": null, "e": 2532, "s": 2478, "text": "The generated Y will have the following distribution:" }, { "code": null, "e": 2678, "s": 2532, "text": "Rather than going through all the math jargon in the original work, here, we highlight the essential steps required for implementation in python:" }, { "code": null, "e": 2935, "s": 2678, "text": "Augment the original dataset with known data generating process (creating a prior distribution), which is from the reference PDF: P(ref). Here, we assume all individuals’ outcome in the augment dataset will be generated from a standard normal distribution:" }, { "code": null, "e": 3192, "s": 2935, "text": "Augment the original dataset with known data generating process (creating a prior distribution), which is from the reference PDF: P(ref). Here, we assume all individuals’ outcome in the augment dataset will be generated from a standard normal distribution:" }, { "code": null, "e": 3440, "s": 3192, "text": "train_array_0 = train_array.copy()train_array_0[:,-1] = metropolis_hastings_normal(train_array_0[:,-1]) #regenerate the outcome f(x) using metropolis_hastings simulators with a standard normal distribution. train_data = [train_array,train_array_0]" }, { "code": null, "e": 3685, "s": 3440, "text": "2. Fit the augmented dataset with a binary discrimination neural network which estimates the probability, y(X), that an observation pair X:=(x,f(x)) is generated from the pr(X) or from the target PDF: p(X). It can be a simple network like this:" }, { "code": null, "e": 4180, "s": 3685, "text": "def simple_nn(dim_x): input_x = tfkl.Input(shape=(dim_x+1)) combined_layer = tfkl.Dense(dim_x)(input_x) for i in range(5): combined_layer = tfkl.Dense(dim_x)(combined_layer) combined_layer = tfkl.Dropout(0.1)(combined_layer) out = tfkl.Dense(1, activation='sigmoid')(combined_layer) model = tf.keras.Model(inputs = input_x, outputs=out) model.compile(loss = 'binary_crossentropy', optimizer=tf.keras.optimizers.RMSprop(lr=0.001)) return model" }, { "code": null, "e": 4251, "s": 4180, "text": "3. Compute the target probability density function using Bayes theory:" }, { "code": null, "e": 4438, "s": 4251, "text": "Thus, training the NN with the purposely augmented data set produces a neural function y(X) from which the unknown PDF p(X) can be inferred, by using an intermediate arbitrary PDF pr(X):" }, { "code": null, "e": 4698, "s": 4438, "text": "conditional_y = pdf_function_i(x).numpy()reference_dense = norm.pdf(x[:,-1]).reshape(-1, 1) #norm(loc = np.sum(x[:,0:-1],1)).pdf(x[:,-1]).reshape(-1, 1)conditional_dense = (conditional_y / np.clip(1 - conditional_y, a_min=1e-3, a_max=1.0)) * reference_dense" }, { "code": null, "e": 4769, "s": 4698, "text": "Now lets plot the estimated PDF (conditional_dense) with the true PDF:" }, { "code": null, "e": 4851, "s": 4769, "text": "Note here each individual point has a normal distribution conditioned on given X." }, { "code": null, "e": 4959, "s": 4851, "text": "Let’s see the estimations of a few other conditional distributions derived from standard density functions:" }, { "code": null, "e": 5477, "s": 4959, "text": "We are able to get fairly accurate estimation of individual PDFs from different original data generating process using the same standard normal prior. Are we able to further improve the estimation? Yes. In another work by Leonardo Reyneri et al.[5], authors suggested using the estimated PDF, p’(X), from the initial estimation as the prior for the adjustment estimation. That is, we repeat step 1 to 2, with the standard normal prior being replaced by the p’(X), and in step three we estimate the following quantity:" }, { "code": null, "e": 5731, "s": 5477, "text": "Thus, we can get the one step adjustment of the original estimation of PDF. The intuition behind this is similar as an autoencoder, where the estimated the PDF will be optimal if the neural network cannot distinguish the estimated PDF and the prior PDF." }, { "code": null, "e": 5868, "s": 5731, "text": "[1] Likas, A. (2001). Probability density estimation using artificial neural networks. Computer physics communications, 135(2), 167–175." }, { "code": null, "e": 6063, "s": 5868, "text": "[2] Combes, C., Dussauchoy, A.: Generalized extreme value distribution for fitting open- ing/closing asset prices and returns in stock-exchange. Springer Operational Re- search 6(1), 3–26 (2006)" }, { "code": null, "e": 6252, "s": 6063, "text": "[3] Zaharim, A., Razali, A.M., Abidin, R.Z., Sopian, K.: Fitting of Statistical Dis- tributions to Wind Speed Data in Malaysia. European Journal of Scientific Re- search 26(1), 6–12 (2009)" }, { "code": null, "e": 6439, "s": 6252, "text": "[4] Wendell Cropper Jr., P., Anderson, P.J.: Population dynamics of a tropical palm: use of a genetic algorithm for inverse parameter estimation. Ecological Modelling 177, 119–127 (2004)" } ]
numpy.insert
This function inserts values in the input array along the given axis and before the given index. If the type of values is converted to be inserted, it is different from the input array. Insertion is not done in place and the function returns a new array. Also, if the axis is not mentioned, the input array is flattened. The insert() function takes the following parameters − numpy.insert(arr, obj, values, axis) Where, arr Input array obj The index before which insertion is to be made values The array of values to be inserted axis The axis along which to insert. If not given, the input array is flattened import numpy as np a = np.array([[1,2],[3,4],[5,6]]) print 'First array:' print a print '\n' print 'Axis parameter not passed. The input array is flattened before insertion.' print np.insert(a,3,[11,12]) print '\n' print 'Axis parameter passed. The values array is broadcast to match input array.' print 'Broadcast along axis 0:' print np.insert(a,1,[11],axis = 0) print '\n' print 'Broadcast along axis 1:' print np.insert(a,1,11,axis = 1) Its output would be as follows − First array: [[1 2] [3 4] [5 6]] Axis parameter not passed. The input array is flattened before insertion. [ 1 2 3 11 12 4 5 6] Axis parameter passed. The values array is broadcast to match input array. Broadcast along axis 0: [[ 1 2] [11 11] [ 3 4] [ 5 6]] Broadcast along axis 1: [[ 1 11 2] [ 3 11 4] [ 5 11 6]] 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2564, "s": 2243, "text": "This function inserts values in the input array along the given axis and before the given index. If the type of values is converted to be inserted, it is different from the input array. Insertion is not done in place and the function returns a new array. Also, if the axis is not mentioned, the input array is flattened." }, { "code": null, "e": 2619, "s": 2564, "text": "The insert() function takes the following parameters −" }, { "code": null, "e": 2657, "s": 2619, "text": "numpy.insert(arr, obj, values, axis)\n" }, { "code": null, "e": 2664, "s": 2657, "text": "Where," }, { "code": null, "e": 2668, "s": 2664, "text": "arr" }, { "code": null, "e": 2680, "s": 2668, "text": "Input array" }, { "code": null, "e": 2684, "s": 2680, "text": "obj" }, { "code": null, "e": 2731, "s": 2684, "text": "The index before which insertion is to be made" }, { "code": null, "e": 2738, "s": 2731, "text": "values" }, { "code": null, "e": 2773, "s": 2738, "text": "The array of values to be inserted" }, { "code": null, "e": 2778, "s": 2773, "text": "axis" }, { "code": null, "e": 2853, "s": 2778, "text": "The axis along which to insert. If not given, the input array is flattened" }, { "code": null, "e": 3312, "s": 2853, "text": "import numpy as np \na = np.array([[1,2],[3,4],[5,6]]) \n\nprint 'First array:' \nprint a \nprint '\\n' \n\nprint 'Axis parameter not passed. The input array is flattened before insertion.'\nprint np.insert(a,3,[11,12]) \nprint '\\n' \nprint 'Axis parameter passed. The values array is broadcast to match input array.'\n\nprint 'Broadcast along axis 0:' \nprint np.insert(a,1,[11],axis = 0) \nprint '\\n' \n\nprint 'Broadcast along axis 1:' \nprint np.insert(a,1,11,axis = 1)" }, { "code": null, "e": 3345, "s": 3312, "text": "Its output would be as follows −" }, { "code": null, "e": 3670, "s": 3345, "text": "First array:\n[[1 2]\n [3 4]\n [5 6]]\n\nAxis parameter not passed. The input array is flattened before insertion.\n[ 1 2 3 11 12 4 5 6]\n\nAxis parameter passed. The values array is broadcast to match input array.\nBroadcast along axis 0:\n[[ 1 2]\n [11 11]\n [ 3 4]\n [ 5 6]]\n\nBroadcast along axis 1:\n[[ 1 11 2]\n [ 3 11 4]\n [ 5 11 6]]\n" }, { "code": null, "e": 3703, "s": 3670, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3720, "s": 3703, "text": " Abhilash Nelson" }, { "code": null, "e": 3753, "s": 3720, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 3788, "s": 3753, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3821, "s": 3788, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 3856, "s": 3821, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3891, "s": 3856, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3903, "s": 3891, "text": " Akbar Khan" }, { "code": null, "e": 3936, "s": 3903, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3951, "s": 3936, "text": " Pruthviraja L" }, { "code": null, "e": 3984, "s": 3951, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3991, "s": 3984, "text": " Anmol" }, { "code": null, "e": 3998, "s": 3991, "text": " Print" }, { "code": null, "e": 4009, "s": 3998, "text": " Add Notes" } ]
How to align pagination in Bootstrap 4 ? - GeeksforGeeks
10 Nov, 2021 In this article, we will learn how to align pagination on the website using the Bootstrap classes. The Pagination is a very useful component present in the Bootstrap. Pagination is used to enable navigation between pages in a website as it divides the document into different pages and provides them with numbers. This will create a large block of connected links which help to easily navigate to different pages. Thus, helps to enhance the user experience. Steps for creating Bootstrap Pagination: Step 1: Import the CDN bootstrap links for CSS and JavaScript from the official website of Bootstrap. <!– Bootstrap CSS –><link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css” integrity=”sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn” crossorigin=”anonymous”/> <!– Bootstrap JS –><script src=”https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js” integrity=”sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj” crossorigin=”anonymous”></script> <script src=”https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js” integrity=”sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF” crossorigin=”anonymous”></script> Step 2: Now make <ul> tag with the class name “pagination” inside the <body> tag. <ul class="pagination"> </ul> Step 3: Add all the page numbers inside the <ul> tag by using the <li> tags with the class name “page-item”. <ul> <li class="page-item"></li> <li class="page-item"></li> <li class="page-item"></li> </ul> Step 4: Inside each <li> tag, add the page no. using the <a> tag and giving the “href” attribute to each page. <ul class="pagination"> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul> At this stage, we have created a basic pagination structure using Bootstrap. We will understand the concept of pagination & the various available Bootstrap classes through the example. Example: This example illustrates the Bootstrap Pagination using the justify-content-evenly & page-item classes. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination justify-content-evenly"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: From the output, we can see the pagination that we have created is on the extreme left of the page. Pagination using the Bootstrap Aligning pagination using Bootstrap Classes: The pagination can be aligned on the web page using the flexbox-utilities classes in Bootstrap. flex-row: This class is added inside the component which helps to align the pagination in rows. This is the default value. Syntax: <ul class="pagination flex-row"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the flex-row class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination flex-row"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: flex-row-reverse: This class when added along inside the component helps to align the pagination in row format but in the reverse direction and to the extreme right of the page. Syntax: <ul class="pagination flex-row-reverse"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the flex-row-reverse class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination flex-row-reverse"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: flex-column: This class when added along inside the component helps to align the pagination in the column. Syntax: <ul class="pagination flex-column"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the flex-column class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination flex-column"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: flex-column-reverse: This class when added along inside the component helps to align the pagination in the column but in the reverse direction. Syntax: <ul class="pagination flex-column-reverse"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the flex-column-reverse class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination flex-column-reverse"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: justify-content-center: This class when added along inside the component helps to align the pagination in the center in row-wise format. Syntax: <ul class="pagination justify-content-center"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the justify-content-center class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: justify-content-start: This class when added along inside the component helps to align the pagination in the start in row-wise format. Syntax: <ul class="pagination Justify-content-start "> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the justify-content-start class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination justify-content-start"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: justify-content-end: This class when added along inside the component helps to align the pagination at the end of the page in row-wise format. Syntax: <ul class="pagination justify-content-end"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the justify-content-end class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination justify-content-end"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: align-items-start: This class when added along inside the component helps to align the pagination at the start of the page in column-wise format. Syntax: <ul class="pagination align-items-start"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the align-items-start class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination align-items-start"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: align-items-end: This class when added along inside the component helps to align the pagination at the end of the page in column-wise format. Syntax: <ul class="pagination align-items-end"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the align-items-end class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination flex-column align-items-end"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: align-items-center: This class when added along inside the component helps to align the pagination to the center of the page in column-wise format. Syntax: <ul class="pagination align-items-center"> <li class="page-item"></li> </ul> Example: This example illustrates the Bootstrap Pagination using the align-items-center class. HTML <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class="pagination flex-column align-items-center"> <li class="page-item"> <a class="page-link" href="#">Home</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> </ul></body> </html> Output: Note: Mostly pagination is done in row-wise format. In very rare, cases, pagination is given in column-wise format. The justify classes will only work when the pagination is done in row-wise format. The align-items will only work when the pagination is done in a column-wise format. So, we have to add the flex-column/ flex-column-reverse class with it. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-Questions HTML-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to keep gap between columns using Bootstrap? Tailwind CSS vs Bootstrap How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26863, "s": 26835, "text": "\n10 Nov, 2021" }, { "code": null, "e": 27321, "s": 26863, "text": "In this article, we will learn how to align pagination on the website using the Bootstrap classes. The Pagination is a very useful component present in the Bootstrap. Pagination is used to enable navigation between pages in a website as it divides the document into different pages and provides them with numbers. This will create a large block of connected links which help to easily navigate to different pages. Thus, helps to enhance the user experience." }, { "code": null, "e": 27362, "s": 27321, "text": "Steps for creating Bootstrap Pagination:" }, { "code": null, "e": 27464, "s": 27362, "text": "Step 1: Import the CDN bootstrap links for CSS and JavaScript from the official website of Bootstrap." }, { "code": null, "e": 27696, "s": 27464, "text": "<!– Bootstrap CSS –><link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css” integrity=”sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn” crossorigin=”anonymous”/>" }, { "code": null, "e": 27913, "s": 27696, "text": "<!– Bootstrap JS –><script src=”https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js” integrity=”sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj” crossorigin=”anonymous”></script>" }, { "code": null, "e": 28122, "s": 27913, "text": "<script src=”https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js” integrity=”sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF” crossorigin=”anonymous”></script>" }, { "code": null, "e": 28204, "s": 28122, "text": "Step 2: Now make <ul> tag with the class name “pagination” inside the <body> tag." }, { "code": null, "e": 28234, "s": 28204, "text": "<ul class=\"pagination\"> </ul>" }, { "code": null, "e": 28343, "s": 28234, "text": "Step 3: Add all the page numbers inside the <ul> tag by using the <li> tags with the class name “page-item”." }, { "code": null, "e": 28441, "s": 28343, "text": "<ul>\n <li class=\"page-item\"></li>\n <li class=\"page-item\"></li>\n <li class=\"page-item\"></li>\n</ul>" }, { "code": null, "e": 28552, "s": 28441, "text": "Step 4: Inside each <li> tag, add the page no. using the <a> tag and giving the “href” attribute to each page." }, { "code": null, "e": 28795, "s": 28552, "text": "<ul class=\"pagination\">\n <li class=\"page-item\">\n <a class=\"page-link\" href=\"#\">1</a>\n </li>\n <li class=\"page-item\">\n <a class=\"page-link\" href=\"#\">2</a>\n </li>\n <li class=\"page-item\">\n <a class=\"page-link\" href=\"#\">3</a>\n </li>\n</ul>" }, { "code": null, "e": 28872, "s": 28795, "text": "At this stage, we have created a basic pagination structure using Bootstrap." }, { "code": null, "e": 28980, "s": 28872, "text": "We will understand the concept of pagination & the various available Bootstrap classes through the example." }, { "code": null, "e": 29093, "s": 28980, "text": "Example: This example illustrates the Bootstrap Pagination using the justify-content-evenly & page-item classes." }, { "code": null, "e": 29098, "s": 29093, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination justify-content-evenly\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 30059, "s": 29098, "text": null }, { "code": null, "e": 30168, "s": 30059, "text": "Output: From the output, we can see the pagination that we have created is on the extreme left of the page." }, { "code": null, "e": 30199, "s": 30168, "text": "Pagination using the Bootstrap" }, { "code": null, "e": 30244, "s": 30199, "text": "Aligning pagination using Bootstrap Classes:" }, { "code": null, "e": 30340, "s": 30244, "text": "The pagination can be aligned on the web page using the flexbox-utilities classes in Bootstrap." }, { "code": null, "e": 30463, "s": 30340, "text": "flex-row: This class is added inside the component which helps to align the pagination in rows. This is the default value." }, { "code": null, "e": 30471, "s": 30463, "text": "Syntax:" }, { "code": null, "e": 30550, "s": 30471, "text": "<ul class=\"pagination flex-row\">\n <li class=\"page-item\"></li> \n</ul>" }, { "code": null, "e": 30635, "s": 30550, "text": "Example: This example illustrates the Bootstrap Pagination using the flex-row class." }, { "code": null, "e": 30640, "s": 30635, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination flex-row\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 31587, "s": 30640, "text": null }, { "code": null, "e": 31595, "s": 31587, "text": "Output:" }, { "code": null, "e": 31773, "s": 31595, "text": "flex-row-reverse: This class when added along inside the component helps to align the pagination in row format but in the reverse direction and to the extreme right of the page." }, { "code": null, "e": 31781, "s": 31773, "text": "Syntax:" }, { "code": null, "e": 31864, "s": 31781, "text": "<ul class=\"pagination flex-row-reverse\">\n <li class=\"page-item\"></li>\n</ul>" }, { "code": null, "e": 31957, "s": 31864, "text": "Example: This example illustrates the Bootstrap Pagination using the flex-row-reverse class." }, { "code": null, "e": 31962, "s": 31957, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination flex-row-reverse\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 32917, "s": 31962, "text": null }, { "code": null, "e": 32925, "s": 32917, "text": "Output:" }, { "code": null, "e": 33032, "s": 32925, "text": "flex-column: This class when added along inside the component helps to align the pagination in the column." }, { "code": null, "e": 33040, "s": 33032, "text": "Syntax:" }, { "code": null, "e": 33120, "s": 33040, "text": "<ul class=\"pagination flex-column\">\n <li class=\"page-item\"></li>\n</ul>" }, { "code": null, "e": 33208, "s": 33120, "text": "Example: This example illustrates the Bootstrap Pagination using the flex-column class." }, { "code": null, "e": 33213, "s": 33208, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination flex-column\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 34163, "s": 33213, "text": null }, { "code": null, "e": 34171, "s": 34163, "text": "Output:" }, { "code": null, "e": 34315, "s": 34171, "text": "flex-column-reverse: This class when added along inside the component helps to align the pagination in the column but in the reverse direction." }, { "code": null, "e": 34323, "s": 34315, "text": "Syntax:" }, { "code": null, "e": 34410, "s": 34323, "text": "<ul class=\"pagination flex-column-reverse\">\n <li class=\"page-item\"></li>\n </ul>" }, { "code": null, "e": 34506, "s": 34410, "text": "Example: This example illustrates the Bootstrap Pagination using the flex-column-reverse class." }, { "code": null, "e": 34511, "s": 34506, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination flex-column-reverse\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 35468, "s": 34511, "text": null }, { "code": null, "e": 35476, "s": 35468, "text": "Output:" }, { "code": null, "e": 35614, "s": 35476, "text": "justify-content-center: This class when added along inside the component helps to align the pagination in the center in row-wise format." }, { "code": null, "e": 35622, "s": 35614, "text": "Syntax:" }, { "code": null, "e": 35713, "s": 35622, "text": "<ul class=\"pagination justify-content-center\">\n <li class=\"page-item\"></li>\n </ul>" }, { "code": null, "e": 35812, "s": 35713, "text": "Example: This example illustrates the Bootstrap Pagination using the justify-content-center class." }, { "code": null, "e": 35817, "s": 35812, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 36777, "s": 35817, "text": null }, { "code": null, "e": 36786, "s": 36777, "text": "Output: " }, { "code": null, "e": 36921, "s": 36786, "text": "justify-content-start: This class when added along inside the component helps to align the pagination in the start in row-wise format." }, { "code": null, "e": 36929, "s": 36921, "text": "Syntax:" }, { "code": null, "e": 37021, "s": 36929, "text": "<ul class=\"pagination Justify-content-start \">\n <li class=\"page-item\"></li>\n </ul>" }, { "code": null, "e": 37119, "s": 37021, "text": "Example: This example illustrates the Bootstrap Pagination using the justify-content-start class." }, { "code": null, "e": 37124, "s": 37119, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination justify-content-start\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 38083, "s": 37124, "text": null }, { "code": null, "e": 38091, "s": 38083, "text": "Output:" }, { "code": null, "e": 38234, "s": 38091, "text": "justify-content-end: This class when added along inside the component helps to align the pagination at the end of the page in row-wise format." }, { "code": null, "e": 38242, "s": 38234, "text": "Syntax:" }, { "code": null, "e": 38328, "s": 38242, "text": " <ul class=\"pagination justify-content-end\">\n <li class=\"page-item\"></li>\n</ul>" }, { "code": null, "e": 38424, "s": 38328, "text": "Example: This example illustrates the Bootstrap Pagination using the justify-content-end class." }, { "code": null, "e": 38429, "s": 38424, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination justify-content-end\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 39387, "s": 38429, "text": null }, { "code": null, "e": 39395, "s": 39387, "text": "Output:" }, { "code": null, "e": 39541, "s": 39395, "text": "align-items-start: This class when added along inside the component helps to align the pagination at the start of the page in column-wise format." }, { "code": null, "e": 39549, "s": 39541, "text": "Syntax:" }, { "code": null, "e": 39633, "s": 39549, "text": "<ul class=\"pagination align-items-start\">\n <li class=\"page-item\"></li>\n </ul>" }, { "code": null, "e": 39727, "s": 39633, "text": "Example: This example illustrates the Bootstrap Pagination using the align-items-start class." }, { "code": null, "e": 39732, "s": 39727, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination align-items-start\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 40687, "s": 39732, "text": null }, { "code": null, "e": 40695, "s": 40687, "text": "Output:" }, { "code": null, "e": 40837, "s": 40695, "text": "align-items-end: This class when added along inside the component helps to align the pagination at the end of the page in column-wise format." }, { "code": null, "e": 40845, "s": 40837, "text": "Syntax:" }, { "code": null, "e": 40927, "s": 40845, "text": "<ul class=\"pagination align-items-end\">\n <li class=\"page-item\"></li>\n </ul>" }, { "code": null, "e": 41019, "s": 40927, "text": "Example: This example illustrates the Bootstrap Pagination using the align-items-end class." }, { "code": null, "e": 41024, "s": 41019, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination flex-column align-items-end\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 41990, "s": 41024, "text": null }, { "code": null, "e": 41998, "s": 41990, "text": "Output:" }, { "code": null, "e": 42146, "s": 41998, "text": "align-items-center: This class when added along inside the component helps to align the pagination to the center of the page in column-wise format." }, { "code": null, "e": 42154, "s": 42146, "text": "Syntax:" }, { "code": null, "e": 42237, "s": 42154, "text": "<ul class=\"pagination align-items-center\">\n <li class=\"page-item\"></li>\n </ul>" }, { "code": null, "e": 42332, "s": 42237, "text": "Example: This example illustrates the Bootstrap Pagination using the align-items-center class." }, { "code": null, "e": 42337, "s": 42332, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\"> <title>Pagination</title></head> <body> <h1>Home Page</h1> <ul class=\"pagination flex-column align-items-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Home</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> </ul></body> </html>", "e": 43305, "s": 42337, "text": null }, { "code": null, "e": 43313, "s": 43305, "text": "Output:" }, { "code": null, "e": 43319, "s": 43313, "text": "Note:" }, { "code": null, "e": 43429, "s": 43319, "text": "Mostly pagination is done in row-wise format. In very rare, cases, pagination is given in column-wise format." }, { "code": null, "e": 43512, "s": 43429, "text": "The justify classes will only work when the pagination is done in row-wise format." }, { "code": null, "e": 43667, "s": 43512, "text": "The align-items will only work when the pagination is done in a column-wise format. So, we have to add the flex-column/ flex-column-reverse class with it." }, { "code": null, "e": 43804, "s": 43667, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 43824, "s": 43804, "text": "Bootstrap-Questions" }, { "code": null, "e": 43839, "s": 43824, "text": "HTML-Questions" }, { "code": null, "e": 43846, "s": 43839, "text": "Picked" }, { "code": null, "e": 43856, "s": 43846, "text": "Bootstrap" }, { "code": null, "e": 43861, "s": 43856, "text": "HTML" }, { "code": null, "e": 43878, "s": 43861, "text": "Web Technologies" }, { "code": null, "e": 43883, "s": 43878, "text": "HTML" }, { "code": null, "e": 43981, "s": 43883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44022, "s": 43981, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 44085, "s": 44022, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 44118, "s": 44085, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 44167, "s": 44118, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 44193, "s": 44167, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 44243, "s": 44193, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 44305, "s": 44243, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 44353, "s": 44305, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 44413, "s": 44353, "text": "How to set the default value for an HTML <select> element ?" } ]
Pair with minimum absolute difference | BST - GeeksforGeeks
09 May, 2022 Given a binary search tree of size N > 1, the task is to find the minimum absolute difference between any two nodes. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 1 Difference between all the consecutive nodes if sorted is 1. Thus, the answer is 1. Input: 1 \ 6 Output: 5 Approach: We know that in-order traversal of a Binary Search Tree traverses it in sorted order. So, for every node, we will find its difference from the previous node in the in-order traversal of the tree. If this difference is smaller than the previous minimum difference, we will update the previous minimum difference. Following are the steps to follow: Create a variable ‘prev’ to store the pointer to the previous node in in-order traversal.Create a variable ‘ans’ to store the minimum difference.For every node in the in-order traversal, compare its absolute difference with the previous node and update the minimum absolute difference found so far. Create a variable ‘prev’ to store the pointer to the previous node in in-order traversal. Create a variable ‘ans’ to store the minimum difference. For every node in the in-order traversal, compare its absolute difference with the previous node and update the minimum absolute difference found so far. Below is the implementation of the above approach: C++ Java C# Javascript Python3 // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function for in-order traversal of the treevoid inorder(node* curr, node*& prev, int& ans){ // Base-case if (curr == NULL) return; // Calling in-order on the left sub-tree inorder(curr->left, prev, ans); if (prev != NULL) ans = min(curr->data - prev->data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr->right, prev, ans);} // Function to return the minimum// difference between any two nodes// of the given binary search treeint minDiff(node* root){ // Pointer to previous node in the // in-order traversal of the BST node* prev = NULL; // To store the final ans int ans = INT_MAX; // Call in-order for the BST inorder(root, prev, ans); // Returning the final answer return ans;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); cout << minDiff(root); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }};static node prev;static int ans; // Function for in-order traversal of the treestatic void inorder(node curr){ // Base-case if (curr == null) return; // Calling in-order on the left sub-tree inorder(curr.left); if (prev != null) ans = Math.min(curr.data - prev.data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr.right);} // Function to return the minimum// difference between any two nodes// of the given binary search treestatic int minDiff(node root){ // Pointer to previous node in the // in-order traversal of the BST prev = null; // To store the final ans ans = Integer.MAX_VALUE; // Call in-order for the BST inorder(root); // Returning the final answer return ans;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); System.out.println(minDiff(root));}} // This code is contributed by 29AjayKumar // C# implementation of the approachusing System; class GFG{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }};static node prev;static int ans; // Function for in-order traversal of the treestatic void inorder(node curr){ // Base-case if (curr == null) return; // Calling in-order on the left sub-tree inorder(curr.left); if (prev != null) ans = Math.Min(curr.data - prev.data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr.right);} // Function to return the minimum// difference between any two nodes// of the given binary search treestatic int minDiff(node root){ // Pointer to previous node in the // in-order traversal of the BST prev = null; // To store the final ans ans = int.MaxValue; // Call in-order for the BST inorder(root); // Returning the final answer return ans;} // Driver codepublic static void Main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); Console.WriteLine(minDiff(root));}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; var prev = null;var ans =0; // Function for in-order traversal of the treefunction inorder(curr){ // Base-case if (curr == null) return; // Calling in-order on the left sub-tree inorder(curr.left); if (prev != null) ans = Math.min(curr.data - prev.data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr.right);} // Function to return the minimum// difference between any two nodes// of the given binary search treefunction minDiff(root){ // Pointer to previous node in the // in-order traversal of the BST prev = null; // To store the final ans ans = 10000000000; // Call in-order for the BST inorder(root); // Returning the final answer return ans;} // Driver codevar root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); document.write(minDiff(root)); // This code is contributed by noob2000 </script> # Python 3 implementation of the approachimport math# Node of the binary tree class node: def __init__(self, data): self.data = data self.left = None self.right = None # Function for in-order traversal of the tree def inorder(curr, prev): global ans # Base-case if (curr == None): return # Calling in-order on the left sub-tree inorder(curr.left, prev) if (prev != None): ans = min(curr.data - prev.data, ans) prev = curr # Calling in-order on the right sub-tree inorder(curr.right, prev) # Function to return the minimum# difference between any two nodes# of the given binary search tree def minDiff(root): # Pointer to previous node in the # in-order traversal of the BST prev = None # To store the final ans global ans ans = math.inf # Call in-order for the BST inorder(root, prev) # Returning the final answer return ans # Driver codeif __name__ == '__main__': root = node(5) root.left = node(3) root.right = node(7) root.left.left = node(2) root.left.right = node(4) root.right.left = node(6) root.right.right = node(8) print(minDiff(root)) 1 Another Approach with O(N) Space Complexity: Python3 Javascript # Python 3 implementation of the approach # Node of the binary treeimport mathclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None#Set the target to infinitytarget=math.inf #Function to find the minimum absolute differencedef absolute_diff(root,target): if root is None: return target if root.left is not None: left=root.data-root.left.data target=min(target,left) if root.right is not None: right=root.right.data-root.data target=min(target,right) #Find the minimum in the left subtree p=absolute_diff(root.left,target) #Find the minimum in the right subtree q=absolute_diff(root.right,target) return min(p,q) // Driver coderoot=Node(5)root.left = Node(3)root.right = Node(7)root.left.left = Node(2)root.left.right = Node(4)root.right.left = Node(6)root.right.right = Node(8)print(absolute_diff(root,target)) <script> // JavaScript implementation of the approach // Node of the binary treeclass Node{ // Constructor to create a new node constructor(data){ this.data = data this.left = null this.right = null }} // Set the target to infinitylet target = Number.MAX_VALUE // Function to find the minimum absolute differencefunction absolute_diff(root, target){ if(root == null) return target if(root.left !== null){ let left = root.data - root.left.data target = Math.min(target, left) } if(root.right !== null){ let right = root.right.data - root.data target = Math.min(target, right) } // Find the minimum in the left subtree let p = absolute_diff(root.left, target) // Find the minimum in the right subtree let q = absolute_diff(root.right, target) return Math.min(p, q)} // Driver codelet root = new Node(5)root.left = new Node(3)root.right = new Node(7)root.left.left = new Node(2)root.left.right = new Node(4)root.right.left = new Node(6)root.right.right = new Node(8)document.write(absolute_diff(root,target),"</br>") // This code is contributed by shinjanpatra </script> 1 Time complexity: O(N) Additional Space: O(N) due to recursion. subhamchakra007 29AjayKumar princiraj1992 noob2000 ashutoshsinghgeeksforgeeks amartyaghoshgfg shinjanpatra Binary Search Tree Data Structures Tree Data Structures Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorted Array to Balanced BST Red-Black Tree | Set 2 (Insert) Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Find the node with minimum value in a Binary Search Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Introduction to Algorithms
[ { "code": null, "e": 26225, "s": 26197, "text": "\n09 May, 2022" }, { "code": null, "e": 26342, "s": 26225, "text": "Given a binary search tree of size N > 1, the task is to find the minimum absolute difference between any two nodes." }, { "code": null, "e": 26353, "s": 26342, "text": "Examples: " }, { "code": null, "e": 26575, "s": 26353, "text": "Input: \n 5 \n / \\ \n 3 7 \n / \\ / \\ \n 2 4 6 8\nOutput: 1\nDifference between all the consecutive nodes if sorted is 1.\nThus, the answer is 1.\n\nInput:\n 1\n \\\n 6\nOutput: 5" }, { "code": null, "e": 26934, "s": 26575, "text": "Approach: We know that in-order traversal of a Binary Search Tree traverses it in sorted order. So, for every node, we will find its difference from the previous node in the in-order traversal of the tree. If this difference is smaller than the previous minimum difference, we will update the previous minimum difference. Following are the steps to follow: " }, { "code": null, "e": 27233, "s": 26934, "text": "Create a variable ‘prev’ to store the pointer to the previous node in in-order traversal.Create a variable ‘ans’ to store the minimum difference.For every node in the in-order traversal, compare its absolute difference with the previous node and update the minimum absolute difference found so far." }, { "code": null, "e": 27323, "s": 27233, "text": "Create a variable ‘prev’ to store the pointer to the previous node in in-order traversal." }, { "code": null, "e": 27380, "s": 27323, "text": "Create a variable ‘ans’ to store the minimum difference." }, { "code": null, "e": 27534, "s": 27380, "text": "For every node in the in-order traversal, compare its absolute difference with the previous node and update the minimum absolute difference found so far." }, { "code": null, "e": 27587, "s": 27534, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27591, "s": 27587, "text": "C++" }, { "code": null, "e": 27596, "s": 27591, "text": "Java" }, { "code": null, "e": 27599, "s": 27596, "text": "C#" }, { "code": null, "e": 27610, "s": 27599, "text": "Javascript" }, { "code": null, "e": 27618, "s": 27610, "text": "Python3" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function for in-order traversal of the treevoid inorder(node* curr, node*& prev, int& ans){ // Base-case if (curr == NULL) return; // Calling in-order on the left sub-tree inorder(curr->left, prev, ans); if (prev != NULL) ans = min(curr->data - prev->data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr->right, prev, ans);} // Function to return the minimum// difference between any two nodes// of the given binary search treeint minDiff(node* root){ // Pointer to previous node in the // in-order traversal of the BST node* prev = NULL; // To store the final ans int ans = INT_MAX; // Call in-order for the BST inorder(root, prev, ans); // Returning the final answer return ans;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); cout << minDiff(root); return 0;}", "e": 28994, "s": 27618, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }};static node prev;static int ans; // Function for in-order traversal of the treestatic void inorder(node curr){ // Base-case if (curr == null) return; // Calling in-order on the left sub-tree inorder(curr.left); if (prev != null) ans = Math.min(curr.data - prev.data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr.right);} // Function to return the minimum// difference between any two nodes// of the given binary search treestatic int minDiff(node root){ // Pointer to previous node in the // in-order traversal of the BST prev = null; // To store the final ans ans = Integer.MAX_VALUE; // Call in-order for the BST inorder(root); // Returning the final answer return ans;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); System.out.println(minDiff(root));}} // This code is contributed by 29AjayKumar", "e": 30449, "s": 28994, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }};static node prev;static int ans; // Function for in-order traversal of the treestatic void inorder(node curr){ // Base-case if (curr == null) return; // Calling in-order on the left sub-tree inorder(curr.left); if (prev != null) ans = Math.Min(curr.data - prev.data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr.right);} // Function to return the minimum// difference between any two nodes// of the given binary search treestatic int minDiff(node root){ // Pointer to previous node in the // in-order traversal of the BST prev = null; // To store the final ans ans = int.MaxValue; // Call in-order for the BST inorder(root); // Returning the final answer return ans;} // Driver codepublic static void Main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); Console.WriteLine(minDiff(root));}} // This code is contributed by PrinciRaj1992", "e": 31924, "s": 30449, "text": null }, { "code": "<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; var prev = null;var ans =0; // Function for in-order traversal of the treefunction inorder(curr){ // Base-case if (curr == null) return; // Calling in-order on the left sub-tree inorder(curr.left); if (prev != null) ans = Math.min(curr.data - prev.data, ans); prev = curr; // Calling in-order on the right sub-tree inorder(curr.right);} // Function to return the minimum// difference between any two nodes// of the given binary search treefunction minDiff(root){ // Pointer to previous node in the // in-order traversal of the BST prev = null; // To store the final ans ans = 10000000000; // Call in-order for the BST inorder(root); // Returning the final answer return ans;} // Driver codevar root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); document.write(minDiff(root)); // This code is contributed by noob2000 </script>", "e": 33232, "s": 31924, "text": null }, { "code": "# Python 3 implementation of the approachimport math# Node of the binary tree class node: def __init__(self, data): self.data = data self.left = None self.right = None # Function for in-order traversal of the tree def inorder(curr, prev): global ans # Base-case if (curr == None): return # Calling in-order on the left sub-tree inorder(curr.left, prev) if (prev != None): ans = min(curr.data - prev.data, ans) prev = curr # Calling in-order on the right sub-tree inorder(curr.right, prev) # Function to return the minimum# difference between any two nodes# of the given binary search tree def minDiff(root): # Pointer to previous node in the # in-order traversal of the BST prev = None # To store the final ans global ans ans = math.inf # Call in-order for the BST inorder(root, prev) # Returning the final answer return ans # Driver codeif __name__ == '__main__': root = node(5) root.left = node(3) root.right = node(7) root.left.left = node(2) root.left.right = node(4) root.right.left = node(6) root.right.right = node(8) print(minDiff(root))", "e": 34411, "s": 33232, "text": null }, { "code": null, "e": 34413, "s": 34411, "text": "1" }, { "code": null, "e": 34458, "s": 34413, "text": "Another Approach with O(N) Space Complexity:" }, { "code": null, "e": 34466, "s": 34458, "text": "Python3" }, { "code": null, "e": 34477, "s": 34466, "text": "Javascript" }, { "code": "# Python 3 implementation of the approach # Node of the binary treeimport mathclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None#Set the target to infinitytarget=math.inf #Function to find the minimum absolute differencedef absolute_diff(root,target): if root is None: return target if root.left is not None: left=root.data-root.left.data target=min(target,left) if root.right is not None: right=root.right.data-root.data target=min(target,right) #Find the minimum in the left subtree p=absolute_diff(root.left,target) #Find the minimum in the right subtree q=absolute_diff(root.right,target) return min(p,q) // Driver coderoot=Node(5)root.left = Node(3)root.right = Node(7)root.left.left = Node(2)root.left.right = Node(4)root.right.left = Node(6)root.right.right = Node(8)print(absolute_diff(root,target))", "e": 35460, "s": 34477, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Node of the binary treeclass Node{ // Constructor to create a new node constructor(data){ this.data = data this.left = null this.right = null }} // Set the target to infinitylet target = Number.MAX_VALUE // Function to find the minimum absolute differencefunction absolute_diff(root, target){ if(root == null) return target if(root.left !== null){ let left = root.data - root.left.data target = Math.min(target, left) } if(root.right !== null){ let right = root.right.data - root.data target = Math.min(target, right) } // Find the minimum in the left subtree let p = absolute_diff(root.left, target) // Find the minimum in the right subtree let q = absolute_diff(root.right, target) return Math.min(p, q)} // Driver codelet root = new Node(5)root.left = new Node(3)root.right = new Node(7)root.left.left = new Node(2)root.left.right = new Node(4)root.right.left = new Node(6)root.right.right = new Node(8)document.write(absolute_diff(root,target),\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 36637, "s": 35460, "text": null }, { "code": null, "e": 36639, "s": 36637, "text": "1" }, { "code": null, "e": 36705, "s": 36641, "text": "Time complexity: O(N) Additional Space: O(N) due to recursion. " }, { "code": null, "e": 36721, "s": 36705, "text": "subhamchakra007" }, { "code": null, "e": 36733, "s": 36721, "text": "29AjayKumar" }, { "code": null, "e": 36747, "s": 36733, "text": "princiraj1992" }, { "code": null, "e": 36756, "s": 36747, "text": "noob2000" }, { "code": null, "e": 36783, "s": 36756, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 36799, "s": 36783, "text": "amartyaghoshgfg" }, { "code": null, "e": 36812, "s": 36799, "text": "shinjanpatra" }, { "code": null, "e": 36831, "s": 36812, "text": "Binary Search Tree" }, { "code": null, "e": 36847, "s": 36831, "text": "Data Structures" }, { "code": null, "e": 36852, "s": 36847, "text": "Tree" }, { "code": null, "e": 36868, "s": 36852, "text": "Data Structures" }, { "code": null, "e": 36887, "s": 36868, "text": "Binary Search Tree" }, { "code": null, "e": 36892, "s": 36887, "text": "Tree" }, { "code": null, "e": 36990, "s": 36892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37019, "s": 36990, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 37051, "s": 37019, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 37086, "s": 37051, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 37126, "s": 37086, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 37183, "s": 37126, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 37232, "s": 37183, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 37276, "s": 37232, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37301, "s": 37276, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37357, "s": 37301, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" } ]
Reverse substrings of given string according to specified array indices - GeeksforGeeks
18 Jun, 2021 Given string str of length N and an array arr[] of integers, for array element arr[i](1-based indexing), reverse the substring in indices [arr[i], N – arr[i] + 1]. The task is to print the string after every reversal. Examples: Input: str = “GeeksforGeeks”, arr[] = {2}Output: GkeeGrofskeesExplanation:For first element of the array is 2:Reverse the substring (2, 12). Now the updated string is “GkeeGrofskees”. Input: str = “abcdef”, arr[] = {1, 2, 3}Output: fbdceaExplanation:For first element of the array is 1:Reverse the substring (1, 6). Now the updated string is “fedcba”.For second element of the array is 2:Reverse the substring (2, 5). Now the updated string is “fbcdea”.For third element of the array is 3:Reverse the substring (3, 4). Now the updated string is “fbdcea”. Naive Approach: The simplest approach is to traverse the given array and for each array element arr[i] reverse the substring {s[arr[i]], ... s[N – arr[i] + 1]} and print the resultant string obtained after very update. Time Complexity: O(N * K), where N is the length of the string and K is the maximum length of the substring reversed.Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized by keeping the track of the number of times any character at an index has been reversed. If the count of reversal is even, then the character will come back to its original place, so there will be no change and if the count of reversal is odd, then the character has to be swapped. Below are the steps: Initialize an array count[] to store the number of reversals at any index of the string. Traverse the given array arr[] and increment the count of indices count[arr[i]] by 1. Now, traverse the array count[] over the range [1, N/2] using the variable i and do the following:Update the element at the current index as the sum of the current and previous index.Now, if current element count[i] is odd, then swap str[i] and str[N – i + 1]. Update the element at the current index as the sum of the current and previous index. Now, if current element count[i] is odd, then swap str[i] and str[N – i + 1]. Print the string after the above steps. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <iostream>using namespace std; // Function to perform the reversal// operation on the given stringstring modifyString(int A[], string str, int K){ // Size of string int N = str.size(); // Stores the count of indices int count[N + 1] = { 0 }; // Count the positions where // reversals will begin for (int i = 0; i < K; i++) { count[A[i]]++; } for (int i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if (count[i] & 1) { swap(str[i - 1], str[N - i]); } } // Return the updated string return str;} // Driver Codeint main(){ // Given string str string str = "abcdef"; // Given array of reversing index int arr[] = { 1, 2, 3 }; int K = sizeof(arr) / sizeof(arr[0]); // Function Call cout << modifyString(arr, str, K); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to perform the reversal// operation on the given Stringstatic String modifyString(int A[], String str, int K){ // Size of String int N = str.length(); // Stores the count of indices int count[] = new int[N + 1]; // Count the positions where // reversals will begin for(int i = 0; i < K; i++) { count[A[i]]++; } for(int i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if ((count[i] & 1) > 0) { str = swap(str, i - 1, N - i); } } // Return the updated String return str;} // Swap char of a stringstatic String swap(String str, int i, int j){ char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch);} // Driver Codepublic static void main(String[] args){ // Given String str String str = "abcdef"; // Given array of reversing index int arr[] = { 1, 2, 3 }; int K = arr.length; // Function Call System.out.print(modifyString(arr, str, K));}} // This code is contributed by Amit Katiyar # Python3 program for the above approach # Function to perform the reversal# operation on the given stringdef modifyString(A, str, K): # Size of string N = len(str) # Stores the count of indices count = [0] * (N + 1) # Count the positions where # reversals will begin for i in range(K): count[A[i]] += 1 for i in range(1, N // 2 + 1): # Store the count of reversals # beginning at position i count[i] = count[i] + count[i - 1] # Check if the count[i] is # odd the swap the character if (count[i] & 1): str[i - 1], str[N - i] = str[N - i], str[i - 1] # Return the updated string return "".join(str) # Driver Codeif __name__ == '__main__': # Given str str1 = "abcdef" str = [i for i in str1] # Given array of reversing index arr = [ 1, 2, 3 ] K = len(arr) # Function Call print(modifyString(arr, str, K)) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System; class GFG{ // Function to perform the reversal// operation on the given Stringstatic String modifyString(int []A, String str, int K){ // Size of String int N = str.Length; // Stores the count of indices int []count = new int[N + 1]; // Count the positions where // reversals will begin for(int i = 0; i < K; i++) { count[A[i]]++; } for(int i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if ((count[i] & 1) > 0) { str = swap(str, i - 1, N - i); } } // Return the updated String return str;} // Swap char of a stringstatic String swap(String str, int i, int j){ char []ch = str.ToCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.Join("", ch);} // Driver Codepublic static void Main(String[] args){ // Given String str String str = "abcdef"; // Given array of reversing index int []arr = { 1, 2, 3 }; int K = arr.Length; // Function Call Console.Write(modifyString(arr, str, K));}} // This code is contributed by Amit Katiyar <script> // JavaScript program for the above approach // Function to perform the reversal// operation on the given Stringfunction modifyString(A, str, K) { // Size of String str = str.split("") let N = str.length; // Stores the count of indices let count = new Array(N + 1).fill(0); // Count the positions where // reversals will begin for (let i = 0; i < K; i++) { count[A[i]] += 1; } for (let i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if (count[i] & 1) { let temp = str[i - 1]; str[i - 1] = str[N - i]; str[N - i] = temp } } // Return the updated String return str.join("");} // Driver Code // Given String strlet str = "abcdef"; // Given array of reversing indexlet arr = [1, 2, 3]; let K = arr.length; // Function Calldocument.write(modifyString(arr, str, K)); // This code is contributed by gfgking </script> fbdcea Time Complexity: O(N + K), where N is the length of the string and K is the maximum length of the substring reversed. Auxiliary Space: O(N) mohit kumar 29 amit143katiyar gfgking frequency-counting Hash Hash Mathematical Strings Hash Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rearrange an array such that arr[i] = i Design a data structure that supports insert, delete, search and getRandom in constant time Quadratic Probing in Hashing Hashing in Java What are Hash Functions and How to choose a good Hash Function? 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": 26403, "s": 26375, "text": "\n18 Jun, 2021" }, { "code": null, "e": 26621, "s": 26403, "text": "Given string str of length N and an array arr[] of integers, for array element arr[i](1-based indexing), reverse the substring in indices [arr[i], N – arr[i] + 1]. The task is to print the string after every reversal." }, { "code": null, "e": 26631, "s": 26621, "text": "Examples:" }, { "code": null, "e": 26815, "s": 26631, "text": "Input: str = “GeeksforGeeks”, arr[] = {2}Output: GkeeGrofskeesExplanation:For first element of the array is 2:Reverse the substring (2, 12). Now the updated string is “GkeeGrofskees”." }, { "code": null, "e": 27186, "s": 26815, "text": "Input: str = “abcdef”, arr[] = {1, 2, 3}Output: fbdceaExplanation:For first element of the array is 1:Reverse the substring (1, 6). Now the updated string is “fedcba”.For second element of the array is 2:Reverse the substring (2, 5). Now the updated string is “fbcdea”.For third element of the array is 3:Reverse the substring (3, 4). Now the updated string is “fbdcea”." }, { "code": null, "e": 27406, "s": 27186, "text": "Naive Approach: The simplest approach is to traverse the given array and for each array element arr[i] reverse the substring {s[arr[i]], ... s[N – arr[i] + 1]} and print the resultant string obtained after very update. " }, { "code": null, "e": 27545, "s": 27406, "text": "Time Complexity: O(N * K), where N is the length of the string and K is the maximum length of the substring reversed.Auxiliary Space: O(1)" }, { "code": null, "e": 27904, "s": 27545, "text": "Efficient Approach: The above approach can be optimized by keeping the track of the number of times any character at an index has been reversed. If the count of reversal is even, then the character will come back to its original place, so there will be no change and if the count of reversal is odd, then the character has to be swapped. Below are the steps:" }, { "code": null, "e": 27993, "s": 27904, "text": "Initialize an array count[] to store the number of reversals at any index of the string." }, { "code": null, "e": 28079, "s": 27993, "text": "Traverse the given array arr[] and increment the count of indices count[arr[i]] by 1." }, { "code": null, "e": 28340, "s": 28079, "text": "Now, traverse the array count[] over the range [1, N/2] using the variable i and do the following:Update the element at the current index as the sum of the current and previous index.Now, if current element count[i] is odd, then swap str[i] and str[N – i + 1]." }, { "code": null, "e": 28426, "s": 28340, "text": "Update the element at the current index as the sum of the current and previous index." }, { "code": null, "e": 28504, "s": 28426, "text": "Now, if current element count[i] is odd, then swap str[i] and str[N – i + 1]." }, { "code": null, "e": 28544, "s": 28504, "text": "Print the string after the above steps." }, { "code": null, "e": 28595, "s": 28544, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28599, "s": 28595, "text": "C++" }, { "code": null, "e": 28604, "s": 28599, "text": "Java" }, { "code": null, "e": 28612, "s": 28604, "text": "Python3" }, { "code": null, "e": 28615, "s": 28612, "text": "C#" }, { "code": null, "e": 28626, "s": 28615, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to perform the reversal// operation on the given stringstring modifyString(int A[], string str, int K){ // Size of string int N = str.size(); // Stores the count of indices int count[N + 1] = { 0 }; // Count the positions where // reversals will begin for (int i = 0; i < K; i++) { count[A[i]]++; } for (int i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if (count[i] & 1) { swap(str[i - 1], str[N - i]); } } // Return the updated string return str;} // Driver Codeint main(){ // Given string str string str = \"abcdef\"; // Given array of reversing index int arr[] = { 1, 2, 3 }; int K = sizeof(arr) / sizeof(arr[0]); // Function Call cout << modifyString(arr, str, K); return 0;}", "e": 29684, "s": 28626, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to perform the reversal// operation on the given Stringstatic String modifyString(int A[], String str, int K){ // Size of String int N = str.length(); // Stores the count of indices int count[] = new int[N + 1]; // Count the positions where // reversals will begin for(int i = 0; i < K; i++) { count[A[i]]++; } for(int i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if ((count[i] & 1) > 0) { str = swap(str, i - 1, N - i); } } // Return the updated String return str;} // Swap char of a stringstatic String swap(String str, int i, int j){ char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch);} // Driver Codepublic static void main(String[] args){ // Given String str String str = \"abcdef\"; // Given array of reversing index int arr[] = { 1, 2, 3 }; int K = arr.length; // Function Call System.out.print(modifyString(arr, str, K));}} // This code is contributed by Amit Katiyar", "e": 31032, "s": 29684, "text": null }, { "code": "# Python3 program for the above approach # Function to perform the reversal# operation on the given stringdef modifyString(A, str, K): # Size of string N = len(str) # Stores the count of indices count = [0] * (N + 1) # Count the positions where # reversals will begin for i in range(K): count[A[i]] += 1 for i in range(1, N // 2 + 1): # Store the count of reversals # beginning at position i count[i] = count[i] + count[i - 1] # Check if the count[i] is # odd the swap the character if (count[i] & 1): str[i - 1], str[N - i] = str[N - i], str[i - 1] # Return the updated string return \"\".join(str) # Driver Codeif __name__ == '__main__': # Given str str1 = \"abcdef\" str = [i for i in str1] # Given array of reversing index arr = [ 1, 2, 3 ] K = len(arr) # Function Call print(modifyString(arr, str, K)) # This code is contributed by mohit kumar 29", "e": 32025, "s": 31032, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to perform the reversal// operation on the given Stringstatic String modifyString(int []A, String str, int K){ // Size of String int N = str.Length; // Stores the count of indices int []count = new int[N + 1]; // Count the positions where // reversals will begin for(int i = 0; i < K; i++) { count[A[i]]++; } for(int i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if ((count[i] & 1) > 0) { str = swap(str, i - 1, N - i); } } // Return the updated String return str;} // Swap char of a stringstatic String swap(String str, int i, int j){ char []ch = str.ToCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.Join(\"\", ch);} // Driver Codepublic static void Main(String[] args){ // Given String str String str = \"abcdef\"; // Given array of reversing index int []arr = { 1, 2, 3 }; int K = arr.Length; // Function Call Console.Write(modifyString(arr, str, K));}} // This code is contributed by Amit Katiyar", "e": 33362, "s": 32025, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to perform the reversal// operation on the given Stringfunction modifyString(A, str, K) { // Size of String str = str.split(\"\") let N = str.length; // Stores the count of indices let count = new Array(N + 1).fill(0); // Count the positions where // reversals will begin for (let i = 0; i < K; i++) { count[A[i]] += 1; } for (let i = 1; i <= N / 2; i++) { // Store the count of reversals // beginning at position i count[i] = count[i] + count[i - 1]; // Check if the count[i] is // odd the swap the character if (count[i] & 1) { let temp = str[i - 1]; str[i - 1] = str[N - i]; str[N - i] = temp } } // Return the updated String return str.join(\"\");} // Driver Code // Given String strlet str = \"abcdef\"; // Given array of reversing indexlet arr = [1, 2, 3]; let K = arr.length; // Function Calldocument.write(modifyString(arr, str, K)); // This code is contributed by gfgking </script>", "e": 34451, "s": 33362, "text": null }, { "code": null, "e": 34458, "s": 34451, "text": "fbdcea" }, { "code": null, "e": 34600, "s": 34460, "text": "Time Complexity: O(N + K), where N is the length of the string and K is the maximum length of the substring reversed. Auxiliary Space: O(N)" }, { "code": null, "e": 34615, "s": 34600, "text": "mohit kumar 29" }, { "code": null, "e": 34630, "s": 34615, "text": "amit143katiyar" }, { "code": null, "e": 34638, "s": 34630, "text": "gfgking" }, { "code": null, "e": 34657, "s": 34638, "text": "frequency-counting" }, { "code": null, "e": 34662, "s": 34657, "text": "Hash" }, { "code": null, "e": 34667, "s": 34662, "text": "Hash" }, { "code": null, "e": 34680, "s": 34667, "text": "Mathematical" }, { "code": null, "e": 34688, "s": 34680, "text": "Strings" }, { "code": null, "e": 34693, "s": 34688, "text": "Hash" }, { "code": null, "e": 34701, "s": 34693, "text": "Strings" }, { "code": null, "e": 34714, "s": 34701, "text": "Mathematical" }, { "code": null, "e": 34812, "s": 34714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34852, "s": 34812, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 34944, "s": 34852, "text": "Design a data structure that supports insert, delete, search and getRandom in constant time" }, { "code": null, "e": 34973, "s": 34944, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 34989, "s": 34973, "text": "Hashing in Java" }, { "code": null, "e": 35053, "s": 34989, "text": "What are Hash Functions and How to choose a good Hash Function?" }, { "code": null, "e": 35083, "s": 35053, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35143, "s": 35083, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35158, "s": 35143, "text": "C++ Data Types" }, { "code": null, "e": 35201, "s": 35158, "text": "Set in C++ Standard Template Library (STL)" } ]
Scala Map exists() method with example - GeeksforGeeks
13 Aug, 2019 The exists() method is utilized to check if the given predicate satisfy the elements of the map or not. Method Definition: def exists(p: ((A, B)) => Boolean): Boolean Return Type: It returns true if the stated predicate holds true for some elements of the map else it returns false. Example #1: // Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map("geeks" -> 5, "for" -> 3) // Applying exists method val result = m1.exists(x => x._1 == "for" && x._2 == 3) // Displays output println(result) }} true So, here the stated predicate is true for the second key-value pair so true is returned.Example #2: // Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map("geeks" -> 5, "for" -> 3) // Applying exists method val result = m1.exists(x => x._1 == "geeks" && x._2 == 3) // Displays output println(result) }} false Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in Scala Scala | Traits Scala ListBuffer Scala | Case Class and Case Object Hello World in Scala Scala | Functions - Basics Scala | Try-Catch Exceptions Scala | Decision Making (if, if-else, Nested if-else, if-else if) Comments In Scala Scala List map() method with example
[ { "code": null, "e": 25301, "s": 25273, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25405, "s": 25301, "text": "The exists() method is utilized to check if the given predicate satisfy the elements of the map or not." }, { "code": null, "e": 25468, "s": 25405, "text": "Method Definition: def exists(p: ((A, B)) => Boolean): Boolean" }, { "code": null, "e": 25584, "s": 25468, "text": "Return Type: It returns true if the stated predicate holds true for some elements of the map else it returns false." }, { "code": null, "e": 25596, "s": 25584, "text": "Example #1:" }, { "code": "// Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3) // Applying exists method val result = m1.exists(x => x._1 == \"for\" && x._2 == 3) // Displays output println(result) }}", "e": 25975, "s": 25596, "text": null }, { "code": null, "e": 25981, "s": 25975, "text": "true\n" }, { "code": null, "e": 26081, "s": 25981, "text": "So, here the stated predicate is true for the second key-value pair so true is returned.Example #2:" }, { "code": "// Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3) // Applying exists method val result = m1.exists(x => x._1 == \"geeks\" && x._2 == 3) // Displays output println(result) }}", "e": 26462, "s": 26081, "text": null }, { "code": null, "e": 26469, "s": 26462, "text": "false\n" }, { "code": null, "e": 26475, "s": 26469, "text": "Scala" }, { "code": null, "e": 26485, "s": 26475, "text": "Scala-Map" }, { "code": null, "e": 26498, "s": 26485, "text": "Scala-Method" }, { "code": null, "e": 26504, "s": 26498, "text": "Scala" }, { "code": null, "e": 26602, "s": 26504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26623, "s": 26602, "text": "Inheritance in Scala" }, { "code": null, "e": 26638, "s": 26623, "text": "Scala | Traits" }, { "code": null, "e": 26655, "s": 26638, "text": "Scala ListBuffer" }, { "code": null, "e": 26690, "s": 26655, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 26711, "s": 26690, "text": "Hello World in Scala" }, { "code": null, "e": 26738, "s": 26711, "text": "Scala | Functions - Basics" }, { "code": null, "e": 26767, "s": 26738, "text": "Scala | Try-Catch Exceptions" }, { "code": null, "e": 26833, "s": 26767, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" }, { "code": null, "e": 26851, "s": 26833, "text": "Comments In Scala" } ]
CSS @keyframes Rule - GeeksforGeeks
05 Nov, 2021 The @keyframes rule in CSS is used to specify the animation rule. An animation is created by using changeable CSS styles. During the animation CSS property can change many times. We need to specify when there is a change in style that takes place in percent, or contains the keywords “from” and “to”, which is the same as 0% and 100% where 0% represents the beginning of the animation & 100% represents the completion of the animation. We can control the appearance of the animation by using animation properties & is possible to bind the animation to selectors. The keyframe ignores the !important rule in CSS. Note: For the best support of browser always specify both the 0% and the 100% selectors. Syntax: @keyframes animation-name {keyframes-selector {css-styles;}} Property value: This parameter accepts three values that mentioned above and described below: animation-name: The animation-name is required and it defines the animation name. keyframes-selector: The keyframes-selector defines the percentage of the animation. It lies between 0% to 100%. One animation can contain many selectors. css-styles: The css-styles defines the one or more legal or applicable CSS style properties. Example 1: This example describes the use of the @keyframe rule to add the animation to the element. HTML <!DOCTYPE html><html> <head> <style> h1 { color: white; text-align: center; } div { background: green; position: relative; animation: gfg 10s infinite; } /* keyframe CSS style */ @keyframes gfg { 0% { top: 0px; width: 00px; } 25% { top: 50px; background: LawnGreen; width: 50px; } 50% { top: 100px; background: LightGreen; width: 100px; } 75% { top: 150px; background: MediumSeaGreen; width: 150px; } 100% { top: 200px; color: white; background: Green; width: 200px; } } </style></head> <body> <div> <h1>GeeksforGeeks</h1> </div></body> </html> Output: Example 2: This example describes the use of the @keyframe rule using the !important rule in CSS. HTML <!DOCTYPE html><html> <head> <style> h1 { color: white; text-align: center; } div { background: green; position: relative; animation: gfg 7s infinite; } @keyframes gfg { 0% { top: 0px; width: 0px; } 25% { top: 50px !important; background: LawnGreen; } 50% { top: 100px !important; background: LightGreen; } 100% { top: 200px !important; color: white; background: Green; width: 210px; } } </style></head> <body> <center> <div> <h1>GeeksforGeeks</h1> </div> </center></body> </html> Output: Supported Browsers: The browser supported by @keyframes Rule are listed below: Google Chrome 43.0, 4.0 -webkit- Microsoft Edge 10.0 Firefox 16.0, 5.0 -moz- Safari 9.0, 4.0 -webkit- Opera 30.0, 15.0 -webkit-, 12.0 -o- shubham_singh bhaskargeeksforgeeks CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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": 24979, "s": 24951, "text": "\n05 Nov, 2021" }, { "code": null, "e": 25158, "s": 24979, "text": "The @keyframes rule in CSS is used to specify the animation rule. An animation is created by using changeable CSS styles. During the animation CSS property can change many times." }, { "code": null, "e": 25591, "s": 25158, "text": "We need to specify when there is a change in style that takes place in percent, or contains the keywords “from” and “to”, which is the same as 0% and 100% where 0% represents the beginning of the animation & 100% represents the completion of the animation. We can control the appearance of the animation by using animation properties & is possible to bind the animation to selectors. The keyframe ignores the !important rule in CSS." }, { "code": null, "e": 25680, "s": 25591, "text": "Note: For the best support of browser always specify both the 0% and the 100% selectors." }, { "code": null, "e": 25688, "s": 25680, "text": "Syntax:" }, { "code": null, "e": 25749, "s": 25688, "text": "@keyframes animation-name {keyframes-selector {css-styles;}}" }, { "code": null, "e": 25843, "s": 25749, "text": "Property value: This parameter accepts three values that mentioned above and described below:" }, { "code": null, "e": 25925, "s": 25843, "text": "animation-name: The animation-name is required and it defines the animation name." }, { "code": null, "e": 26079, "s": 25925, "text": "keyframes-selector: The keyframes-selector defines the percentage of the animation. It lies between 0% to 100%. One animation can contain many selectors." }, { "code": null, "e": 26172, "s": 26079, "text": "css-styles: The css-styles defines the one or more legal or applicable CSS style properties." }, { "code": null, "e": 26273, "s": 26172, "text": "Example 1: This example describes the use of the @keyframe rule to add the animation to the element." }, { "code": null, "e": 26278, "s": 26273, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { color: white; text-align: center; } div { background: green; position: relative; animation: gfg 10s infinite; } /* keyframe CSS style */ @keyframes gfg { 0% { top: 0px; width: 00px; } 25% { top: 50px; background: LawnGreen; width: 50px; } 50% { top: 100px; background: LightGreen; width: 100px; } 75% { top: 150px; background: MediumSeaGreen; width: 150px; } 100% { top: 200px; color: white; background: Green; width: 200px; } } </style></head> <body> <div> <h1>GeeksforGeeks</h1> </div></body> </html>", "e": 27148, "s": 26278, "text": null }, { "code": null, "e": 27156, "s": 27148, "text": "Output:" }, { "code": null, "e": 27254, "s": 27156, "text": "Example 2: This example describes the use of the @keyframe rule using the !important rule in CSS." }, { "code": null, "e": 27259, "s": 27254, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { color: white; text-align: center; } div { background: green; position: relative; animation: gfg 7s infinite; } @keyframes gfg { 0% { top: 0px; width: 0px; } 25% { top: 50px !important; background: LawnGreen; } 50% { top: 100px !important; background: LightGreen; } 100% { top: 200px !important; color: white; background: Green; width: 210px; } } </style></head> <body> <center> <div> <h1>GeeksforGeeks</h1> </div> </center></body> </html>", "e": 28012, "s": 27259, "text": null }, { "code": null, "e": 28020, "s": 28012, "text": "Output:" }, { "code": null, "e": 28099, "s": 28020, "text": "Supported Browsers: The browser supported by @keyframes Rule are listed below:" }, { "code": null, "e": 28132, "s": 28099, "text": "Google Chrome 43.0, 4.0 -webkit-" }, { "code": null, "e": 28152, "s": 28132, "text": "Microsoft Edge 10.0" }, { "code": null, "e": 28176, "s": 28152, "text": "Firefox 16.0, 5.0 -moz-" }, { "code": null, "e": 28201, "s": 28176, "text": "Safari 9.0, 4.0 -webkit-" }, { "code": null, "e": 28237, "s": 28201, "text": "Opera 30.0, 15.0 -webkit-, 12.0 -o-" }, { "code": null, "e": 28251, "s": 28237, "text": "shubham_singh" }, { "code": null, "e": 28272, "s": 28251, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28287, "s": 28272, "text": "CSS-Properties" }, { "code": null, "e": 28294, "s": 28287, "text": "Picked" }, { "code": null, "e": 28298, "s": 28294, "text": "CSS" }, { "code": null, "e": 28315, "s": 28298, "text": "Web Technologies" }, { "code": null, "e": 28413, "s": 28315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28463, "s": 28413, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28525, "s": 28463, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28573, "s": 28525, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28631, "s": 28573, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28686, "s": 28631, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28726, "s": 28686, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28759, "s": 28726, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28804, "s": 28759, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28847, "s": 28804, "text": "How to fetch data from an API in ReactJS ?" } ]
final Keyword in Java - GeeksforGeeks
24 Apr, 2022 final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a variable, a method, or a class. The following are different contexts where final is used. When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but the internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from the final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words. Illustration: final int THRESHOLD = 5; // Final variable final int THRESHOLD; // Blank final variable static final double PI = 3.141592653589793; // Final static variable PI static final double PI; // Blank final static variable We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable can only be initialized once, either via an initializer or an assignment statement. There are three ways to initialize a final variable: You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.A blank final static variable can be initialized inside a static block. You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable. A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown. A blank final static variable can be initialized inside a static block. Let us see these two different ways of initializing a final variable: Java // Java Program to demonstrate Different// Ways of Initializing a final Variable // Main classclass GFG { // a final variable // direct initialize final int THRESHOLD = 5; // a blank final variable final int CAPACITY; // another blank final variable final int MINIMUM; // a final static variable PI // direct initialize static final double PI = 3.141592653589793; // a blank final static variable static final double EULERCONSTANT; // instance initializer block for // initializing CAPACITY { CAPACITY = 25; } // static initializer block for // initializing EULERCONSTANT static{ EULERCONSTANT = 2.3; } // constructor for initializing MINIMUM // Note that if there are more than one // constructor, you must initialize MINIMUM // in them also public GFG() { MINIMUM = -1; } } Geeks there was no main method in the above code as it was simply for illustration purposes to get a better understanding in order to draw conclusions: Observation 1: When to use a final variable? The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program. Observation 2: Reference final variable? When a final variable is a reference to an object, then this final variable is called the reference final variable. For example, a final StringBuffer variable looks defined below as follows: final StringBuffer sb; As we all know that a final variable cannot be re-assign. But in the case of a reference final variable, the internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity. To understand what is meant by the internal state of the object as shown in the below example as follows: Example 1: Java // Java Program to demonstrate// Reference of Final Variable // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating sn object of StringBuilder class // Final reference variable final StringBuilder sb = new StringBuilder("Geeks"); // Printing the element in StringBuilder object System.out.println(sb); // changing internal state of object reference by // final reference variable sb sb.append("ForGeeks"); // Again printing the element in StringBuilder // object after appending above element in it System.out.println(sb); }} Geeks GeeksForGeeks The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays with the final keyword are also called final arrays. Note: As discussed above, a final variable cannot be reassign, doing it will throw compile-time error. Example 2: Java // Java Program to Demonstrate Re-assigning// Final Variable will throw Compile-time Error // Main classclass GFG { // Declaring and customly initializing // static final variable static final int CAPACITY = 4; // Main driver method public static void main(String args[]) { // Re-assigning final variable // will throw compile-time error CAPACITY = 5; }} Output: Remember: When a final variable is created inside a method/constructor/block, it is called local final variable, and it must initialize once where it is created. See below program for local final variable. Example: Java // Java program to demonstrate// local final variable // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring local final variable final int i; // Now initializing it with integer value i = 20; // Printing the value on console System.out.println(i); }} 20 Remember the below key points as perceived before moving forward as listed below as follows: Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in the above examples. A final variable can be assigned value later, but only once.final with foreach loop: final with for-each statement is a legal statement. Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in the above examples. A final variable can be assigned value later, but only once. final with foreach loop: final with for-each statement is a legal statement. Example: Java // Java Program to demonstrate Final// with for-each Statement // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing // custom integer array int arr[] = { 1, 2, 3 }; // final with for-each statement // legal statement for (final int i : arr) System.out.print(i + " "); }} 1 2 3 Output explanation: Since the “i” variable goes out of scope with each iteration of the loop, it is actually re-declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables. When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited). There are two uses of a final class: Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer, Float, etc. are final classes. We can not extend them. final class A { // methods and fields } // The following class is illegal class B extends A { // COMPILE-ERROR! Can't subclass A } Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can not make a class immutable without making it final. When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final. We must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes. Illustration: Final keyword with a method class A { final void m1() { System.out.println("This is a final method."); } } class B extends A { void m1() { // Compile-error! We can not override System.out.println("Illegal!"); } } For more examples and behavior of final methods and final classes, please see Using final with inheritance. Please see the abstract in java article for differences between the final and abstract. Related Interview Question(Important): Difference between final, finally, and finalize in Java YouTubeGeeksforGeeks508K subscribersUses of final Keyword (Java Programming) | GeeksforGeeksWatch 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:000:00 / 3:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yz-BIVvLR9w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Gaurav Miglani. 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 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. solankimayank surinderdawra388 Java-keyword Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Stream In Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 30195, "s": 30167, "text": "\n24 Apr, 2022" }, { "code": null, "e": 30396, "s": 30195, "text": "final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a variable, a method, or a class. The following are different contexts where final is used." }, { "code": null, "e": 30944, "s": 30396, "text": "When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but the internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from the final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words." }, { "code": null, "e": 30958, "s": 30944, "text": "Illustration:" }, { "code": null, "e": 31001, "s": 30958, "text": "final int THRESHOLD = 5;\n// Final variable" }, { "code": null, "e": 31046, "s": 31001, "text": "final int THRESHOLD;\n// Blank final variable" }, { "code": null, "e": 31118, "s": 31046, "text": "static final double PI = 3.141592653589793;\n// Final static variable PI" }, { "code": null, "e": 31174, "s": 31118, "text": "static final double PI;\n// Blank final static variable" }, { "code": null, "e": 31423, "s": 31174, "text": "We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable can only be initialized once, either via an initializer or an assignment statement. There are three ways to initialize a final variable: " }, { "code": null, "e": 31989, "s": 31423, "text": "You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.A blank final static variable can be initialized inside a static block." }, { "code": null, "e": 32235, "s": 31989, "text": "You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable." }, { "code": null, "e": 32485, "s": 32235, "text": "A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown." }, { "code": null, "e": 32557, "s": 32485, "text": "A blank final static variable can be initialized inside a static block." }, { "code": null, "e": 32627, "s": 32557, "text": "Let us see these two different ways of initializing a final variable:" }, { "code": null, "e": 32632, "s": 32627, "text": "Java" }, { "code": "// Java Program to demonstrate Different// Ways of Initializing a final Variable // Main classclass GFG { // a final variable // direct initialize final int THRESHOLD = 5; // a blank final variable final int CAPACITY; // another blank final variable final int MINIMUM; // a final static variable PI // direct initialize static final double PI = 3.141592653589793; // a blank final static variable static final double EULERCONSTANT; // instance initializer block for // initializing CAPACITY { CAPACITY = 25; } // static initializer block for // initializing EULERCONSTANT static{ EULERCONSTANT = 2.3; } // constructor for initializing MINIMUM // Note that if there are more than one // constructor, you must initialize MINIMUM // in them also public GFG() { MINIMUM = -1; } }", "e": 33559, "s": 32632, "text": null }, { "code": null, "e": 33712, "s": 33559, "text": " Geeks there was no main method in the above code as it was simply for illustration purposes to get a better understanding in order to draw conclusions:" }, { "code": null, "e": 33757, "s": 33712, "text": "Observation 1: When to use a final variable?" }, { "code": null, "e": 34074, "s": 33757, "text": "The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program." }, { "code": null, "e": 34116, "s": 34074, "text": "Observation 2: Reference final variable? " }, { "code": null, "e": 34307, "s": 34116, "text": "When a final variable is a reference to an object, then this final variable is called the reference final variable. For example, a final StringBuffer variable looks defined below as follows:" }, { "code": null, "e": 34330, "s": 34307, "text": "final StringBuffer sb;" }, { "code": null, "e": 34712, "s": 34330, "text": "As we all know that a final variable cannot be re-assign. But in the case of a reference final variable, the internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity. To understand what is meant by the internal state of the object as shown in the below example as follows:" }, { "code": null, "e": 34723, "s": 34712, "text": "Example 1:" }, { "code": null, "e": 34728, "s": 34723, "text": "Java" }, { "code": "// Java Program to demonstrate// Reference of Final Variable // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating sn object of StringBuilder class // Final reference variable final StringBuilder sb = new StringBuilder(\"Geeks\"); // Printing the element in StringBuilder object System.out.println(sb); // changing internal state of object reference by // final reference variable sb sb.append(\"ForGeeks\"); // Again printing the element in StringBuilder // object after appending above element in it System.out.println(sb); }}", "e": 35393, "s": 34728, "text": null }, { "code": null, "e": 35413, "s": 35393, "text": "Geeks\nGeeksForGeeks" }, { "code": null, "e": 35563, "s": 35413, "text": "The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays with the final keyword are also called final arrays." }, { "code": null, "e": 35666, "s": 35563, "text": "Note: As discussed above, a final variable cannot be reassign, doing it will throw compile-time error." }, { "code": null, "e": 35677, "s": 35666, "text": "Example 2:" }, { "code": null, "e": 35682, "s": 35677, "text": "Java" }, { "code": "// Java Program to Demonstrate Re-assigning// Final Variable will throw Compile-time Error // Main classclass GFG { // Declaring and customly initializing // static final variable static final int CAPACITY = 4; // Main driver method public static void main(String args[]) { // Re-assigning final variable // will throw compile-time error CAPACITY = 5; }}", "e": 36082, "s": 35682, "text": null }, { "code": null, "e": 36091, "s": 36082, "text": "Output: " }, { "code": null, "e": 36297, "s": 36091, "text": "Remember: When a final variable is created inside a method/constructor/block, it is called local final variable, and it must initialize once where it is created. See below program for local final variable." }, { "code": null, "e": 36306, "s": 36297, "text": "Example:" }, { "code": null, "e": 36311, "s": 36306, "text": "Java" }, { "code": "// Java program to demonstrate// local final variable // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring local final variable final int i; // Now initializing it with integer value i = 20; // Printing the value on console System.out.println(i); }}", "e": 36666, "s": 36311, "text": null }, { "code": null, "e": 36669, "s": 36666, "text": "20" }, { "code": null, "e": 36762, "s": 36669, "text": "Remember the below key points as perceived before moving forward as listed below as follows:" }, { "code": null, "e": 37118, "s": 36762, "text": "Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in the above examples. A final variable can be assigned value later, but only once.final with foreach loop: final with for-each statement is a legal statement." }, { "code": null, "e": 37398, "s": 37118, "text": "Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in the above examples. A final variable can be assigned value later, but only once." }, { "code": null, "e": 37475, "s": 37398, "text": "final with foreach loop: final with for-each statement is a legal statement." }, { "code": null, "e": 37484, "s": 37475, "text": "Example:" }, { "code": null, "e": 37489, "s": 37484, "text": "Java" }, { "code": "// Java Program to demonstrate Final// with for-each Statement // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing // custom integer array int arr[] = { 1, 2, 3 }; // final with for-each statement // legal statement for (final int i : arr) System.out.print(i + \" \"); }}", "e": 37893, "s": 37489, "text": null }, { "code": null, "e": 37900, "s": 37893, "text": "1 2 3 " }, { "code": null, "e": 38118, "s": 37900, "text": "Output explanation: Since the “i” variable goes out of scope with each iteration of the loop, it is actually re-declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables. " }, { "code": null, "e": 38237, "s": 38118, "text": "When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited). " }, { "code": null, "e": 38275, "s": 38237, "text": "There are two uses of a final class: " }, { "code": null, "e": 38465, "s": 38275, "text": "Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer, Float, etc. are final classes. We can not extend them." }, { "code": null, "e": 38607, "s": 38465, "text": "final class A\n{\n // methods and fields\n}\n// The following class is illegal\nclass B extends A \n{ \n // COMPILE-ERROR! Can't subclass A\n}" }, { "code": null, "e": 38778, "s": 38607, "text": "Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can not make a class immutable without making it final." }, { "code": null, "e": 39096, "s": 38778, "text": "When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final. We must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes. " }, { "code": null, "e": 39139, "s": 39096, "text": "Illustration: Final keyword with a method " }, { "code": null, "e": 39377, "s": 39139, "text": "class A \n{\n final void m1() \n {\n System.out.println(\"This is a final method.\");\n }\n}\n\nclass B extends A \n{\n void m1()\n { \n // Compile-error! We can not override\n System.out.println(\"Illegal!\");\n }\n}" }, { "code": null, "e": 39670, "s": 39379, "text": "For more examples and behavior of final methods and final classes, please see Using final with inheritance. Please see the abstract in java article for differences between the final and abstract. Related Interview Question(Important): Difference between final, finally, and finalize in Java" }, { "code": null, "e": 40509, "s": 39670, "text": "YouTubeGeeksforGeeks508K subscribersUses of final Keyword (Java Programming) | GeeksforGeeksWatch 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:000:00 / 3:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=yz-BIVvLR9w\" 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": 40932, "s": 40509, "text": "This article is contributed by Gaurav Miglani. 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 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": 40946, "s": 40932, "text": "solankimayank" }, { "code": null, "e": 40963, "s": 40946, "text": "surinderdawra388" }, { "code": null, "e": 40976, "s": 40963, "text": "Java-keyword" }, { "code": null, "e": 40981, "s": 40976, "text": "Java" }, { "code": null, "e": 41000, "s": 40981, "text": "School Programming" }, { "code": null, "e": 41005, "s": 41000, "text": "Java" }, { "code": null, "e": 41103, "s": 41005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41147, "s": 41103, "text": "Split() String method in Java with examples" }, { "code": null, "e": 41183, "s": 41147, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 41208, "s": 41183, "text": "Reverse a string in Java" }, { "code": null, "e": 41223, "s": 41208, "text": "Stream In Java" }, { "code": null, "e": 41254, "s": 41223, "text": "How to iterate any Map in Java" }, { "code": null, "e": 41272, "s": 41254, "text": "Python Dictionary" }, { "code": null, "e": 41288, "s": 41272, "text": "Arrays in C/C++" }, { "code": null, "e": 41307, "s": 41288, "text": "Inheritance in C++" }, { "code": null, "e": 41332, "s": 41307, "text": "Reverse a string in Java" } ]
Difference between Cost Variance and Schedule Variance - GeeksforGeeks
16 May, 2019 Prerequisite – Cost Variance (CV) and Schedule Variance (SV)Cost Variance (CV):Cost variance is basically related with the budget of the project. Cost variance is the difference of the actual cost and the expected cost. Cost Variance is calculated by taking the difference of the Earned Value and the Actual Cost. Schedule Variance (SV):Schedule variance basically related with the scheduled time for the project. Schedule variance is the measurement of deviation of consumed time from the scheduled time. Scheduled Variance is calculated by taking difference between Earned Value and Planned Value. Example:The budget of a project is at 1, 00, 000 dollar. It has to be completed in 9 months but after one month it is found that only 10 percent of the project is completed and the cost at the end of one month is 10, 000 dollar. The planned completion should have been 15 percent. Then the Cost Variance (CV) and Schedule Variance (SV) will be: Actual Cost, = 1, 00, 000 dollar Planned Value, = 15% * 1, 00, 000 = 15, 000 dollar Earned Value, = 10% * Rs. 1, 00, 000 = 10, 000 dollar Cost Variance (CV), = Earned Value – Actual Cost = 10, 000 - 1, 00, 000 = - 90, 000 Schedule Variance (SV), = Earned Value - Planned Value = 10, 000 - 15, 000 = -5, 000 Conclusion: Cost Variance (CV) is negative which means the project is over budget and Schedule Variance (SV) is negative that means the project is behind the schedule. Difference between Cost Variance and Schedule Variance: CV = EV - AC SV = EV - PV Difference Between Software Engineering 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 IPv4 and IPv6 Difference Between Method Overloading and Method Overriding in Java Stack vs Heap Memory Allocation Differences between JDK, JRE and JVM Types of Software Testing Software Engineering | COCOMO Model Functional vs Non Functional Requirements Software Engineering | Coupling and Cohesion Software Engineering | Spiral Model
[ { "code": null, "e": 26067, "s": 26039, "text": "\n16 May, 2019" }, { "code": null, "e": 26381, "s": 26067, "text": "Prerequisite – Cost Variance (CV) and Schedule Variance (SV)Cost Variance (CV):Cost variance is basically related with the budget of the project. Cost variance is the difference of the actual cost and the expected cost. Cost Variance is calculated by taking the difference of the Earned Value and the Actual Cost." }, { "code": null, "e": 26667, "s": 26381, "text": "Schedule Variance (SV):Schedule variance basically related with the scheduled time for the project. Schedule variance is the measurement of deviation of consumed time from the scheduled time. Scheduled Variance is calculated by taking difference between Earned Value and Planned Value." }, { "code": null, "e": 26948, "s": 26667, "text": "Example:The budget of a project is at 1, 00, 000 dollar. It has to be completed in 9 months but after one month it is found that only 10 percent of the project is completed and the cost at the end of one month is 10, 000 dollar. The planned completion should have been 15 percent." }, { "code": null, "e": 27012, "s": 26948, "text": "Then the Cost Variance (CV) and Schedule Variance (SV) will be:" }, { "code": null, "e": 27332, "s": 27012, "text": "Actual Cost, \n= 1, 00, 000 dollar\n\nPlanned Value, \n= 15% * 1, 00, 000 \n= 15, 000 dollar\n\nEarned Value, \n= 10% * Rs. 1, 00, 000 \n= 10, 000 dollar\n\nCost Variance (CV), \n= Earned Value – Actual Cost \n= 10, 000 - 1, 00, 000\n= - 90, 000\n\nSchedule Variance (SV), \n= Earned Value - Planned Value\n= 10, 000 - 15, 000\n= -5, 000 " }, { "code": null, "e": 27500, "s": 27332, "text": "Conclusion: Cost Variance (CV) is negative which means the project is over budget and Schedule Variance (SV) is negative that means the project is behind the schedule." }, { "code": null, "e": 27556, "s": 27500, "text": "Difference between Cost Variance and Schedule Variance:" }, { "code": null, "e": 27569, "s": 27556, "text": "CV = EV - AC" }, { "code": null, "e": 27582, "s": 27569, "text": "SV = EV - PV" }, { "code": null, "e": 27601, "s": 27582, "text": "Difference Between" }, { "code": null, "e": 27622, "s": 27601, "text": "Software Engineering" }, { "code": null, "e": 27720, "s": 27622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27781, "s": 27720, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27815, "s": 27781, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27883, "s": 27815, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27915, "s": 27883, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 27952, "s": 27915, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 27978, "s": 27952, "text": "Types of Software Testing" }, { "code": null, "e": 28014, "s": 27978, "text": "Software Engineering | COCOMO Model" }, { "code": null, "e": 28056, "s": 28014, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 28101, "s": 28056, "text": "Software Engineering | Coupling and Cohesion" } ]
Quickselect Algorithm - GeeksforGeeks
10 Aug, 2021 Quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quick sort sorting algorithm.Examples: Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10 The algorithm is similar to QuickSort. The difference is, instead of recurring for both sides (after finding pivot), it recurs only for the part that contains the k-th smallest element. The logic is simple, if index of partitioned element is more than k, then we recur for left part. If index is same as k, we have found the k-th smallest element and we return. If index is less than k, then we recur for right part. This reduces the expected complexity from O(n log n) to O(n), with a worst case of O(n^2). function quickSelect(list, left, right, k) if left = right return list[left] Select a pivotIndex between left and right pivotIndex := partition(list, left, right, pivotIndex) if k = pivotIndex return list[k] else if k < pivotIndex right := pivotIndex - 1 else left := pivotIndex + 1 C++14 Java Python3 C# Javascript // CPP program for implementation of QuickSelect#include <bits/stdc++.h>using namespace std; // Standard partition process of QuickSort().// It considers the last element as pivot// and moves all smaller element to left of// it and greater elements to rightint partition(int arr[], int l, int r){ int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr[i], arr[j]); i++; } } swap(arr[i], arr[r]); return i;} // This function returns k'th smallest// element in arr[l..r] using QuickSort// based method. ASSUMPTION: ALL ELEMENTS// IN ARR[] ARE DISTINCTint kthSmallest(int arr[], int l, int r, int k){ // If k is smaller than number of // elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int index = partition(arr, l, r); // If position is same as k if (index - l == k - 1) return arr[index]; // If position is more, recur // for left subarray if (index - l > k - 1) return kthSmallest(arr, l, index - 1, k); // Else recur for right subarray return kthSmallest(arr, index + 1, r, k - index + l - 1); } // If k is more than number of // elements in array return INT_MAX;} // Driver program to test above methodsint main(){ int arr[] = { 10, 4, 5, 8, 6, 11, 26 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "K-th smallest element is " << kthSmallest(arr, 0, n - 1, k); return 0;} // Java program of Quick Selectimport java.util.Arrays; class GFG { // partition function similar to quick sort // Considers last element as pivot and adds // elements with less value to the left and // high value to the right and also changes // the pivot position to its respective position // in the final array. public static int partition(int[] arr, int low, int high) { int pivot = arr[high], pivotloc = low; for (int i = low; i <= high; i++) { // inserting elements of less value // to the left of the pivot location if (arr[i] < pivot) { int temp = arr[i]; arr[i] = arr[pivotloc]; arr[pivotloc] = temp; pivotloc++; } } // swapping pivot to the final pivot location int temp = arr[high]; arr[high] = arr[pivotloc]; arr[pivotloc] = temp; return pivotloc; } // finds the kth position (of the sorted array) // in a given unsorted array i.e this function // can be used to find both kth largest and // kth smallest element in the array. // ASSUMPTION: all elements in arr[] are distinct public static int kthSmallest(int[] arr, int low, int high, int k) { // find the partition int partition = partition(arr, low, high); // if partition value is equal to the kth position, // return value at k. if (partition == k - 1) return arr[partition]; // if partition value is less than kth position, // search right side of the array. else if (partition < k - 1) return kthSmallest(arr, partition + 1, high, k); // if partition value is more than kth position, // search left side of the array. else return kthSmallest(arr, low, partition - 1, k); } // Driver Code public static void main(String[] args) { int[] array = new int[] { 10, 4, 5, 8, 6, 11, 26 }; int[] arraycopy = new int[] { 10, 4, 5, 8, 6, 11, 26 }; int kPosition = 3; int length = array.length; if (kPosition > length) { System.out.println("Index out of bound"); } else { // find kth smallest value System.out.println( "K-th smallest element in array : " + kthSmallest(arraycopy, 0, length - 1, kPosition)); } }} // This code is contributed by Saiteja Pamulapati # Python3 program of Quick Select # Standard partition process of QuickSort().# It considers the last element as pivot# and moves all smaller element to left of# it and greater elements to rightdef partition(arr, l, r): x = arr[r] i = l for j in range(l, r): if arr[j] <= x: arr[i], arr[j] = arr[j], arr[i] i += 1 arr[i], arr[r] = arr[r], arr[i] return i # finds the kth position (of the sorted array)# in a given unsorted array i.e this function# can be used to find both kth largest and# kth smallest element in the array.# ASSUMPTION: all elements in arr[] are distinctdef kthSmallest(arr, l, r, k): # if k is smaller than number of # elements in array if (k > 0 and k <= r - l + 1): # Partition the array around last # element and get position of pivot # element in sorted array index = partition(arr, l, r) # if position is same as k if (index - l == k - 1): return arr[index] # If position is more, recur # for left subarray if (index - l > k - 1): return kthSmallest(arr, l, index - 1, k) # Else recur for right subarray return kthSmallest(arr, index + 1, r, k - index + l - 1) print("Index out of bound") # Driver Codearr = [ 10, 4, 5, 8, 6, 11, 26 ]n = len(arr)k = 3print("K-th smallest element is ", end = "")print(kthSmallest(arr, 0, n - 1, k)) # This code is contributed by Muskan Kalra. // C# program of Quick Selectusing System; class GFG{ // partition function similar to quick sort // Considers last element as pivot and adds // elements with less value to the left and // high value to the right and also changes // the pivot position to its respective position // in the readonly array. static int partitions(int []arr,int low, int high) { int pivot = arr[high], pivotloc = low, temp; for (int i = low; i <= high; i++) { // inserting elements of less value // to the left of the pivot location if(arr[i] < pivot) { temp = arr[i]; arr[i] = arr[pivotloc]; arr[pivotloc] = temp; pivotloc++; } } // swapping pivot to the readonly pivot location temp = arr[high]; arr[high] = arr[pivotloc]; arr[pivotloc] = temp; return pivotloc; } // finds the kth position (of the sorted array) // in a given unsorted array i.e this function // can be used to find both kth largest and // kth smallest element in the array. // ASSUMPTION: all elements in []arr are distinct static int kthSmallest(int[] arr, int low, int high, int k) { // find the partition int partition = partitions(arr,low,high); // if partition value is equal to the kth position, // return value at k. if(partition == k) return arr[partition]; // if partition value is less than kth position, // search right side of the array. else if(partition < k ) return kthSmallest(arr, partition + 1, high, k ); // if partition value is more than kth position, // search left side of the array. else return kthSmallest(arr, low, partition - 1, k ); } // Driver Code public static void Main(String[] args) { int[] array = {10, 4, 5, 8, 6, 11, 26}; int[] arraycopy = {10, 4, 5, 8, 6, 11, 26}; int kPosition = 3; int length = array.Length; if(kPosition > length) { Console.WriteLine("Index out of bound"); } else { // find kth smallest value Console.WriteLine("K-th smallest element in array : " + kthSmallest(arraycopy, 0, length - 1, kPosition - 1)); } }} // This code is contributed by 29AjayKumar <script>// Javascript program of Quick Select // partition function similar to quick sort // Considers last element as pivot and adds // elements with less value to the left and // high value to the right and also changes // the pivot position to its respective position // in the final array.function _partition(arr, low, high){ let pivot = arr[high], pivotloc = low; for (let i = low; i <= high; i++) { // inserting elements of less value // to the left of the pivot location if (arr[i] < pivot) { let temp = arr[i]; arr[i] = arr[pivotloc]; arr[pivotloc] = temp; pivotloc++; } } // swapping pivot to the final pivot location let temp = arr[high]; arr[high] = arr[pivotloc]; arr[pivotloc] = temp; return pivotloc;} // finds the kth position (of the sorted array) // in a given unsorted array i.e this function // can be used to find both kth largest and // kth smallest element in the array. // ASSUMPTION: all elements in arr[] are distinctfunction kthSmallest(arr, low, high, k){ // find the partition let partition = _partition(arr, low, high); // if partition value is equal to the kth position, // return value at k. if (partition == k - 1) return arr[partition]; // if partition value is less than kth position, // search right side of the array. else if (partition < k - 1) return kthSmallest(arr, partition + 1, high, k); // if partition value is more than kth position, // search left side of the array. else return kthSmallest(arr, low, partition - 1, k);} // Driver Codelet array = [ 10, 4, 5, 8, 6, 11, 26];let arraycopy = [10, 4, 5, 8, 6, 11, 26 ];let kPosition = 3;let length = array.length; if (kPosition > length) { document.write("Index out of bound<br>");}else{ // find kth smallest valuedocument.write("K-th smallest element in array : "+ kthSmallest(arraycopy, 0, length - 1, kPosition)+"<br>");} // This code is contributed by rag2127</script> Output: K-th smallest element is 6 Important Points: Like quicksort, it is fast in practice, but has poor worst-case performance. It is used inThe partition process is same as QuickSort, only recursive code differs.There exists an algorithm that finds k-th smallest element in O(n) in worst case, but QuickSelect performs better on average. Like quicksort, it is fast in practice, but has poor worst-case performance. It is used in The partition process is same as QuickSort, only recursive code differs. There exists an algorithm that finds k-th smallest element in O(n) in worst case, but QuickSelect performs better on average. Related C++ function : std::nth_element in C++This article is contributed by Sahil Chhabra . 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 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. ChandanKumar44 Saiteja Pamulapati MuskanKalra1 29AjayKumar code_ayush Hasanul Islam kziomek rag2127 Order-Statistics Quick Sort Searching Sorting Searching Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Search an element in a sorted and rotated array Program to find largest element in an array k largest(or smallest) elements in an array Given an array of size n and a number k, find all elements that appear more than n/k times Median of two sorted arrays of different sizes Bubble Sort Insertion Sort Selection Sort std::sort() in C++ STL Time Complexities of all Sorting Algorithms
[ { "code": null, "e": 25393, "s": 25365, "text": "\n10 Aug, 2021" }, { "code": null, "e": 25547, "s": 25393, "text": "Quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quick sort sorting algorithm.Examples: " }, { "code": null, "e": 25677, "s": 25547, "text": "Input: arr[] = {7, 10, 4, 3, 20, 15}\n k = 3\nOutput: 7\n\nInput: arr[] = {7, 10, 4, 3, 20, 15}\n k = 4\nOutput: 10" }, { "code": null, "e": 26185, "s": 25677, "text": "The algorithm is similar to QuickSort. The difference is, instead of recurring for both sides (after finding pivot), it recurs only for the part that contains the k-th smallest element. The logic is simple, if index of partitioned element is more than k, then we recur for left part. If index is same as k, we have found the k-th smallest element and we return. If index is less than k, then we recur for right part. This reduces the expected complexity from O(n log n) to O(n), with a worst case of O(n^2)." }, { "code": null, "e": 26549, "s": 26185, "text": "function quickSelect(list, left, right, k)\n\n if left = right\n return list[left]\n\n Select a pivotIndex between left and right\n\n pivotIndex := partition(list, left, right, \n pivotIndex)\n if k = pivotIndex\n return list[k]\n else if k < pivotIndex\n right := pivotIndex - 1\n else\n left := pivotIndex + 1 " }, { "code": null, "e": 26555, "s": 26549, "text": "C++14" }, { "code": null, "e": 26560, "s": 26555, "text": "Java" }, { "code": null, "e": 26568, "s": 26560, "text": "Python3" }, { "code": null, "e": 26571, "s": 26568, "text": "C#" }, { "code": null, "e": 26582, "s": 26571, "text": "Javascript" }, { "code": "// CPP program for implementation of QuickSelect#include <bits/stdc++.h>using namespace std; // Standard partition process of QuickSort().// It considers the last element as pivot// and moves all smaller element to left of// it and greater elements to rightint partition(int arr[], int l, int r){ int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr[i], arr[j]); i++; } } swap(arr[i], arr[r]); return i;} // This function returns k'th smallest// element in arr[l..r] using QuickSort// based method. ASSUMPTION: ALL ELEMENTS// IN ARR[] ARE DISTINCTint kthSmallest(int arr[], int l, int r, int k){ // If k is smaller than number of // elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int index = partition(arr, l, r); // If position is same as k if (index - l == k - 1) return arr[index]; // If position is more, recur // for left subarray if (index - l > k - 1) return kthSmallest(arr, l, index - 1, k); // Else recur for right subarray return kthSmallest(arr, index + 1, r, k - index + l - 1); } // If k is more than number of // elements in array return INT_MAX;} // Driver program to test above methodsint main(){ int arr[] = { 10, 4, 5, 8, 6, 11, 26 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << \"K-th smallest element is \" << kthSmallest(arr, 0, n - 1, k); return 0;}", "e": 28226, "s": 26582, "text": null }, { "code": "// Java program of Quick Selectimport java.util.Arrays; class GFG { // partition function similar to quick sort // Considers last element as pivot and adds // elements with less value to the left and // high value to the right and also changes // the pivot position to its respective position // in the final array. public static int partition(int[] arr, int low, int high) { int pivot = arr[high], pivotloc = low; for (int i = low; i <= high; i++) { // inserting elements of less value // to the left of the pivot location if (arr[i] < pivot) { int temp = arr[i]; arr[i] = arr[pivotloc]; arr[pivotloc] = temp; pivotloc++; } } // swapping pivot to the final pivot location int temp = arr[high]; arr[high] = arr[pivotloc]; arr[pivotloc] = temp; return pivotloc; } // finds the kth position (of the sorted array) // in a given unsorted array i.e this function // can be used to find both kth largest and // kth smallest element in the array. // ASSUMPTION: all elements in arr[] are distinct public static int kthSmallest(int[] arr, int low, int high, int k) { // find the partition int partition = partition(arr, low, high); // if partition value is equal to the kth position, // return value at k. if (partition == k - 1) return arr[partition]; // if partition value is less than kth position, // search right side of the array. else if (partition < k - 1) return kthSmallest(arr, partition + 1, high, k); // if partition value is more than kth position, // search left side of the array. else return kthSmallest(arr, low, partition - 1, k); } // Driver Code public static void main(String[] args) { int[] array = new int[] { 10, 4, 5, 8, 6, 11, 26 }; int[] arraycopy = new int[] { 10, 4, 5, 8, 6, 11, 26 }; int kPosition = 3; int length = array.length; if (kPosition > length) { System.out.println(\"Index out of bound\"); } else { // find kth smallest value System.out.println( \"K-th smallest element in array : \" + kthSmallest(arraycopy, 0, length - 1, kPosition)); } }} // This code is contributed by Saiteja Pamulapati", "e": 30814, "s": 28226, "text": null }, { "code": "# Python3 program of Quick Select # Standard partition process of QuickSort().# It considers the last element as pivot# and moves all smaller element to left of# it and greater elements to rightdef partition(arr, l, r): x = arr[r] i = l for j in range(l, r): if arr[j] <= x: arr[i], arr[j] = arr[j], arr[i] i += 1 arr[i], arr[r] = arr[r], arr[i] return i # finds the kth position (of the sorted array)# in a given unsorted array i.e this function# can be used to find both kth largest and# kth smallest element in the array.# ASSUMPTION: all elements in arr[] are distinctdef kthSmallest(arr, l, r, k): # if k is smaller than number of # elements in array if (k > 0 and k <= r - l + 1): # Partition the array around last # element and get position of pivot # element in sorted array index = partition(arr, l, r) # if position is same as k if (index - l == k - 1): return arr[index] # If position is more, recur # for left subarray if (index - l > k - 1): return kthSmallest(arr, l, index - 1, k) # Else recur for right subarray return kthSmallest(arr, index + 1, r, k - index + l - 1) print(\"Index out of bound\") # Driver Codearr = [ 10, 4, 5, 8, 6, 11, 26 ]n = len(arr)k = 3print(\"K-th smallest element is \", end = \"\")print(kthSmallest(arr, 0, n - 1, k)) # This code is contributed by Muskan Kalra.", "e": 32328, "s": 30814, "text": null }, { "code": "// C# program of Quick Selectusing System; class GFG{ // partition function similar to quick sort // Considers last element as pivot and adds // elements with less value to the left and // high value to the right and also changes // the pivot position to its respective position // in the readonly array. static int partitions(int []arr,int low, int high) { int pivot = arr[high], pivotloc = low, temp; for (int i = low; i <= high; i++) { // inserting elements of less value // to the left of the pivot location if(arr[i] < pivot) { temp = arr[i]; arr[i] = arr[pivotloc]; arr[pivotloc] = temp; pivotloc++; } } // swapping pivot to the readonly pivot location temp = arr[high]; arr[high] = arr[pivotloc]; arr[pivotloc] = temp; return pivotloc; } // finds the kth position (of the sorted array) // in a given unsorted array i.e this function // can be used to find both kth largest and // kth smallest element in the array. // ASSUMPTION: all elements in []arr are distinct static int kthSmallest(int[] arr, int low, int high, int k) { // find the partition int partition = partitions(arr,low,high); // if partition value is equal to the kth position, // return value at k. if(partition == k) return arr[partition]; // if partition value is less than kth position, // search right side of the array. else if(partition < k ) return kthSmallest(arr, partition + 1, high, k ); // if partition value is more than kth position, // search left side of the array. else return kthSmallest(arr, low, partition - 1, k ); } // Driver Code public static void Main(String[] args) { int[] array = {10, 4, 5, 8, 6, 11, 26}; int[] arraycopy = {10, 4, 5, 8, 6, 11, 26}; int kPosition = 3; int length = array.Length; if(kPosition > length) { Console.WriteLine(\"Index out of bound\"); } else { // find kth smallest value Console.WriteLine(\"K-th smallest element in array : \" + kthSmallest(arraycopy, 0, length - 1, kPosition - 1)); } }} // This code is contributed by 29AjayKumar", "e": 34959, "s": 32328, "text": null }, { "code": "<script>// Javascript program of Quick Select // partition function similar to quick sort // Considers last element as pivot and adds // elements with less value to the left and // high value to the right and also changes // the pivot position to its respective position // in the final array.function _partition(arr, low, high){ let pivot = arr[high], pivotloc = low; for (let i = low; i <= high; i++) { // inserting elements of less value // to the left of the pivot location if (arr[i] < pivot) { let temp = arr[i]; arr[i] = arr[pivotloc]; arr[pivotloc] = temp; pivotloc++; } } // swapping pivot to the final pivot location let temp = arr[high]; arr[high] = arr[pivotloc]; arr[pivotloc] = temp; return pivotloc;} // finds the kth position (of the sorted array) // in a given unsorted array i.e this function // can be used to find both kth largest and // kth smallest element in the array. // ASSUMPTION: all elements in arr[] are distinctfunction kthSmallest(arr, low, high, k){ // find the partition let partition = _partition(arr, low, high); // if partition value is equal to the kth position, // return value at k. if (partition == k - 1) return arr[partition]; // if partition value is less than kth position, // search right side of the array. else if (partition < k - 1) return kthSmallest(arr, partition + 1, high, k); // if partition value is more than kth position, // search left side of the array. else return kthSmallest(arr, low, partition - 1, k);} // Driver Codelet array = [ 10, 4, 5, 8, 6, 11, 26];let arraycopy = [10, 4, 5, 8, 6, 11, 26 ];let kPosition = 3;let length = array.length; if (kPosition > length) { document.write(\"Index out of bound<br>\");}else{ // find kth smallest valuedocument.write(\"K-th smallest element in array : \"+ kthSmallest(arraycopy, 0, length - 1, kPosition)+\"<br>\");} // This code is contributed by rag2127</script>", "e": 37168, "s": 34959, "text": null }, { "code": null, "e": 37177, "s": 37168, "text": "Output: " }, { "code": null, "e": 37204, "s": 37177, "text": "K-th smallest element is 6" }, { "code": null, "e": 37224, "s": 37204, "text": "Important Points: " }, { "code": null, "e": 37514, "s": 37224, "text": "Like quicksort, it is fast in practice, but has poor worst-case performance. It is used inThe partition process is same as QuickSort, only recursive code differs.There exists an algorithm that finds k-th smallest element in O(n) in worst case, but QuickSelect performs better on average. " }, { "code": null, "e": 37605, "s": 37514, "text": "Like quicksort, it is fast in practice, but has poor worst-case performance. It is used in" }, { "code": null, "e": 37678, "s": 37605, "text": "The partition process is same as QuickSort, only recursive code differs." }, { "code": null, "e": 37806, "s": 37678, "text": "There exists an algorithm that finds k-th smallest element in O(n) in worst case, but QuickSelect performs better on average. " }, { "code": null, "e": 38275, "s": 37806, "text": "Related C++ function : std::nth_element in C++This article is contributed by Sahil Chhabra . 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 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": 38290, "s": 38275, "text": "ChandanKumar44" }, { "code": null, "e": 38309, "s": 38290, "text": "Saiteja Pamulapati" }, { "code": null, "e": 38322, "s": 38309, "text": "MuskanKalra1" }, { "code": null, "e": 38334, "s": 38322, "text": "29AjayKumar" }, { "code": null, "e": 38345, "s": 38334, "text": "code_ayush" }, { "code": null, "e": 38359, "s": 38345, "text": "Hasanul Islam" }, { "code": null, "e": 38367, "s": 38359, "text": "kziomek" }, { "code": null, "e": 38375, "s": 38367, "text": "rag2127" }, { "code": null, "e": 38392, "s": 38375, "text": "Order-Statistics" }, { "code": null, "e": 38403, "s": 38392, "text": "Quick Sort" }, { "code": null, "e": 38413, "s": 38403, "text": "Searching" }, { "code": null, "e": 38421, "s": 38413, "text": "Sorting" }, { "code": null, "e": 38431, "s": 38421, "text": "Searching" }, { "code": null, "e": 38439, "s": 38431, "text": "Sorting" }, { "code": null, "e": 38537, "s": 38439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38585, "s": 38537, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 38629, "s": 38585, "text": "Program to find largest element in an array" }, { "code": null, "e": 38673, "s": 38629, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 38764, "s": 38673, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 38811, "s": 38764, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 38823, "s": 38811, "text": "Bubble Sort" }, { "code": null, "e": 38838, "s": 38823, "text": "Insertion Sort" }, { "code": null, "e": 38853, "s": 38838, "text": "Selection Sort" }, { "code": null, "e": 38876, "s": 38853, "text": "std::sort() in C++ STL" } ]
Stack Data Structure (Introduction and Program) - GeeksforGeeks
24 Apr, 2022 Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). Mainly the following four basic operations are performed in the stack: Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition. Algorithm for push: begin if stack is full return endif else increment top stack[top] assign value end else end procedure Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition. Algorithm for pop: begin if stack is empty return endif else store value of stack[top] decrement top return value end else end procedure Peek or Top: Returns the top element of the stack. Algorithm for peek: begin return stack[top] end procedure isEmpty: Returns true if the stack is empty, else false. Algorithm for isEmpty: begin if top < 1 return true else return false end procedure How to understand a stack practically? There are many real-life examples of a stack. Consider the simple example of plates stacked over one another in a canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow the LIFO/FILO order. Time Complexities of operations on the stack: push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of these operations. Applications of the stack: Balancing of symbols Infix to Postfix /Prefix conversion Redo-undo features at many places like editors, photoshop. Forward and backward features in web browsers Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and histogram problems. Backtracking is one of the algorithm designing techniques. Some examples of backtracking are the Knight-Tour problem, N-Queen problem, find your way through a maze, and game-like chess or checkers in all these problems we dive into someway if that way is not efficient we come back to the previous state and go into some another path. To get back from a current state we need to store the previous state for that purpose we need a stack. In Graph Algorithms like Topological Sorting and Strongly Connected Components In Memory management, any modern computer uses a stack as the primary management for a running purpose. Each program that is running in a computer system has its own memory allocations String reversal is also another application of stack. Here one by one each character gets inserted into the stack. So the first character of the string is on the bottom of the stack and the last element of a string is on the top of the stack. After Performing the pop operations on the stack we get a string in reverse order. Implementation: There are two ways to implement a stack: Using array Using linked list Implementing Stack using Arrays C++ C Java Python3 C# Javascript /* C++ program to implement basic stack operations */#include <bits/stdc++.h> using namespace std; #define MAX 1000 class Stack { int top; public: int a[MAX]; // Maximum size of Stack Stack() { top = -1; } bool push(int x); int pop(); int peek(); bool isEmpty();}; bool Stack::push(int x){ if (top >= (MAX - 1)) { cout << "Stack Overflow"; return false; } else { a[++top] = x; cout << x << " pushed into stack\n"; return true; }} int Stack::pop(){ if (top < 0) { cout << "Stack Underflow"; return 0; } else { int x = a[top--]; return x; }}int Stack::peek(){ if (top < 0) { cout << "Stack is Empty"; return 0; } else { int x = a[top]; return x; }} bool Stack::isEmpty(){ return (top < 0);} // Driver program to test above functionsint main(){ class Stack s; s.push(10); s.push(20); s.push(30); cout << s.pop() << " Popped from stack\n"; //print all elements in stack : cout<<"Elements present in stack : "; while(!s.isEmpty()) { // print top element in stack cout<<s.peek()<<" "; // remove top element in stack s.pop(); } return 0;} // C program for array implementation of stack#include <limits.h>#include <stdio.h>#include <stdlib.h> // A structure to represent a stackstruct Stack { int top; unsigned capacity; int* array;}; // function to create a stack of given capacity. It initializes size of// stack as 0struct Stack* createStack(unsigned capacity){ struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*)malloc(stack->capacity * sizeof(int)); return stack;} // Stack is full when top is equal to the last indexint isFull(struct Stack* stack){ return stack->top == stack->capacity - 1;} // Stack is empty when top is equal to -1int isEmpty(struct Stack* stack){ return stack->top == -1;} // Function to add an item to stack. It increases top by 1void push(struct Stack* stack, int item){ if (isFull(stack)) return; stack->array[++stack->top] = item; printf("%d pushed to stack\n", item);} // Function to remove an item from stack. It decreases top by 1int pop(struct Stack* stack){ if (isEmpty(stack)) return INT_MIN; return stack->array[stack->top--];} // Function to return the top from stack without removing itint peek(struct Stack* stack){ if (isEmpty(stack)) return INT_MIN; return stack->array[stack->top];} // Driver program to test above functionsint main(){ struct Stack* stack = createStack(100); push(stack, 10); push(stack, 20); push(stack, 30); printf("%d popped from stack\n", pop(stack)); return 0;} /* Java program to implement basic stackoperations */class Stack { static final int MAX = 1000; int top; int a[] = new int[MAX]; // Maximum size of Stack boolean isEmpty() { return (top < 0); } Stack() { top = -1; } boolean push(int x) { if (top >= (MAX - 1)) { System.out.println("Stack Overflow"); return false; } else { a[++top] = x; System.out.println(x + " pushed into stack"); return true; } } int pop() { if (top < 0) { System.out.println("Stack Underflow"); return 0; } else { int x = a[top--]; return x; } } int peek() { if (top < 0) { System.out.println("Stack Underflow"); return 0; } else { int x = a[top]; return x; } } void print(){ for(int i = top;i>-1;i--){ System.out.print(" "+ a[i]); } }} // Driver codeclass Main { public static void main(String args[]) { Stack s = new Stack(); s.push(10); s.push(20); s.push(30); System.out.println(s.pop() + " Popped from stack"); System.out.println("Top element is :" + s.peek()); System.out.print("Elements present in stack :"); s.print(); }} # Python program for implementation of stack # import maxsize from sys module# Used to return -infinite when stack is emptyfrom sys import maxsize # Function to create a stack. It initializes size of stack as 0def createStack(): stack = [] return stack # Stack is empty when stack size is 0def isEmpty(stack): return len(stack) == 0 # Function to add an item to stack. It increases size by 1def push(stack, item): stack.append(item) print(item + " pushed to stack ") # Function to remove an item from stack. It decreases size by 1def pop(stack): if (isEmpty(stack)): return str(-maxsize -1) # return minus infinite return stack.pop() # Function to return the top from stack without removing itdef peek(stack): if (isEmpty(stack)): return str(-maxsize -1) # return minus infinite return stack[len(stack) - 1] # Driver program to test above functions stack = createStack()push(stack, str(10))push(stack, str(20))push(stack, str(30))print(pop(stack) + " popped from stack") // C# program to implement basic stack// operationsusing System; namespace ImplementStack {class Stack { private int[] ele; private int top; private int max; public Stack(int size) { ele = new int[size]; // Maximum size of Stack top = -1; max = size; } public void push(int item) { if (top == max - 1) { Console.WriteLine("Stack Overflow"); return; } else { ele[++top] = item; } } public int pop() { if (top == -1) { Console.WriteLine("Stack is Empty"); return -1; } else { Console.WriteLine("{0} popped from stack ", ele[top]); return ele[top--]; } } public int peek() { if (top == -1) { Console.WriteLine("Stack is Empty"); return -1; } else { Console.WriteLine("{0} popped from stack ", ele[top]); return ele[top]; } } public void printStack() { if (top == -1) { Console.WriteLine("Stack is Empty"); return; } else { for (int i = 0; i <= top; i++) { Console.WriteLine("{0} pushed into stack", ele[i]); } } }} // Driver program to test above functionsclass Program { static void Main() { Stack p = new Stack(5); p.push(10); p.push(20); p.push(30); p.printStack(); p.pop(); }}} <script>/* javascript program to implement basic stackoperations*/ var t = -1; var MAX = 1000; var a = Array(MAX).fill(0); // Maximum size of Stack function isEmpty() { return (t < 0); } function push(x) { if (t >= (MAX - 1)) { document.write("Stack Overflow"); return false; } else { t+=1; a[t] = x; document.write(x + " pushed into stack<br/>"); return true; } } function pop() { if (t < 0) { document.write("Stack Underflow"); return 0; } else { var x = a[t]; t-=1; return x; } } function peek() { if (t < 0) { document.write("Stack Underflow"); return 0; } else { var x = a[t]; return x; } } function print() { for (i = t; i > -1; i--) { document.write(" " + a[i]); } } push(10); push(20); push(30); document.write(pop() + " Popped from stack"); document.write("<br/>Top element is :" + peek()); document.write("<br/>Elements present in stack : "); print(); // This code is contributed by Rajput-Ji</script> Output : 10 pushed into stack 20 pushed into stack 30 pushed into stack 30 Popped from stack Top element is : 20 Elements present in stack : 20 10 Pros: Easy to implement. Memory is saved as pointers are not involved. Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime. Implementing Stack using Linked List: C++ C Java Python3 C# Javascript // C++ program for linked list implementation of stack#include <bits/stdc++.h>using namespace std; // A structure to represent a stackclass StackNode {public: int data; StackNode* next;}; StackNode* newNode(int data){ StackNode* stackNode = new StackNode(); stackNode->data = data; stackNode->next = NULL; return stackNode;} int isEmpty(StackNode* root){ return !root;} void push(StackNode** root, int data){ StackNode* stackNode = newNode(data); stackNode->next = *root; *root = stackNode; cout << data << " pushed to stack\n";} int pop(StackNode** root){ if (isEmpty(*root)) return INT_MIN; StackNode* temp = *root; *root = (*root)->next; int popped = temp->data; free(temp); return popped;} int peek(StackNode* root){ if (isEmpty(root)) return INT_MIN; return root->data;} // Driver codeint main(){ StackNode* root = NULL; push(&root, 10); push(&root, 20); push(&root, 30); cout << pop(&root) << " popped from stack\n"; cout << "Top element is " << peek(root) << endl; cout<<"Elements present in stack : "; //print all elements in stack : while(!isEmpty(root)) { // print top element in stack cout<<peek(root)<<" "; // remove top element in stack pop(&root); } return 0;} // This is code is contributed by rathbhupendra // C program for linked list implementation of stack#include <limits.h>#include <stdio.h>#include <stdlib.h> // A structure to represent a stackstruct StackNode { int data; struct StackNode* next;}; struct StackNode* newNode(int data){ struct StackNode* stackNode = (struct StackNode*) malloc(sizeof(struct StackNode)); stackNode->data = data; stackNode->next = NULL; return stackNode;} int isEmpty(struct StackNode* root){ return !root;} void push(struct StackNode** root, int data){ struct StackNode* stackNode = newNode(data); stackNode->next = *root; *root = stackNode; printf("%d pushed to stack\n", data);} int pop(struct StackNode** root){ if (isEmpty(*root)) return INT_MIN; struct StackNode* temp = *root; *root = (*root)->next; int popped = temp->data; free(temp); return popped;} int peek(struct StackNode* root){ if (isEmpty(root)) return INT_MIN; return root->data;} int main(){ struct StackNode* root = NULL; push(&root, 10); push(&root, 20); push(&root, 30); printf("%d popped from stack\n", pop(&root)); printf("Top element is %d\n", peek(root)); return 0;} // Java Code for Linked List Implementation public class StackAsLinkedList { StackNode root; static class StackNode { int data; StackNode next; StackNode(int data) { this.data = data; } } public boolean isEmpty() { if (root == null) { return true; } else return false; } public void push(int data) { StackNode newNode = new StackNode(data); if (root == null) { root = newNode; } else { StackNode temp = root; root = newNode; newNode.next = temp; } System.out.println(data + " pushed to stack"); } public int pop() { int popped = Integer.MIN_VALUE; if (root == null) { System.out.println("Stack is Empty"); } else { popped = root.data; root = root.next; } return popped; } public int peek() { if (root == null) { System.out.println("Stack is empty"); return Integer.MIN_VALUE; } else { return root.data; } } // Driver code public static void main(String[] args) { StackAsLinkedList sll = new StackAsLinkedList(); sll.push(10); sll.push(20); sll.push(30); System.out.println(sll.pop() + " popped from stack"); System.out.println("Top element is " + sll.peek()); }} # Python program for linked list implementation of stack # Class to represent a node class StackNode: # Constructor to initialize a node def __init__(self, data): self.data = data self.next = None class Stack: # Constructor to initialize the root of linked list def __init__(self): self.root = None def isEmpty(self): return True if self.root is None else False def push(self, data): newNode = StackNode(data) newNode.next = self.root self.root = newNode print ("% d pushed to stack" % (data)) def pop(self): if (self.isEmpty()): return float("-inf") temp = self.root self.root = self.root.next popped = temp.data return popped def peek(self): if self.isEmpty(): return float("-inf") return self.root.data # Driver codestack = Stack()stack.push(10)stack.push(20)stack.push(30) print ("% d popped from stack" % (stack.pop()))print ("Top element is % d " % (stack.peek())) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# Code for Linked List Implementationusing System; public class StackAsLinkedList { StackNode root; public class StackNode { public int data; public StackNode next; public StackNode(int data) { this.data = data; } } public bool isEmpty() { if (root == null) { return true; } else return false; } public void push(int data) { StackNode newNode = new StackNode(data); if (root == null) { root = newNode; } else { StackNode temp = root; root = newNode; newNode.next = temp; } Console.WriteLine(data + " pushed to stack"); } public int pop() { int popped = int.MinValue; if (root == null) { Console.WriteLine("Stack is Empty"); } else { popped = root.data; root = root.next; } return popped; } public int peek() { if (root == null) { Console.WriteLine("Stack is empty"); return int.MinValue; } else { return root.data; } } // Driver code public static void Main(String[] args) { StackAsLinkedList sll = new StackAsLinkedList(); sll.push(10); sll.push(20); sll.push(30); Console.WriteLine(sll.pop() + " popped from stack"); Console.WriteLine("Top element is " + sll.peek()); }} /* This code contributed by PrinciRaj1992 */ <script>// javascript Code for Linked List Implementation var root; class StackNode { constructor(data) { this.data = data; this.next = null; } } function isEmpty() { if (root == null) { return true; } else return false; } function push(data) { var newNode = new StackNode(data); if (root == null) { root = newNode; } else { var temp = root; root = newNode; newNode.next = temp; } document.write(data + " pushed to stack<br/>"); } function pop() { var popped = Number.MIN_VALUE; if (root == null) { document.write("Stack is Empty"); } else { popped = root.data; root = root.next; } return popped; } function peek() { if (root == null) { document.write("Stack is empty"); return Number.MIN_VALUE; } else { return root.data; } } // Driver code push(10); push(20); push(30); document.write(pop() + " popped from stack<br/>"); document.write("Top element is " + peek()); // This code is contributed by Rajput-Ji</script> Output: 10 pushed to stack 20 pushed to stack 30 pushed to stack 30 popped from stack Top element is 20 Elements present in stack : 20 10 Pros: The linked list implementation of a stack can grow and shrink according to the needs at runtime. Cons: Requires extra memory due to involvement of pointers. https://youtu.be/vZEuSFXSMDI We will cover the implementation of applications of the stack in separate posts. Stack Set -2 (Infix to Postfix) Quiz: Stack Questions References: http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29#Problem_Description Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mr_processor SoumikMondal SahilSharma19 Ankit Rai rathbhupendra princiraj1992 KIRTANPATEL2 gp6 sidhijain deepak710agarwal asdhamidi akashjindal06 vaibhavsinghtanwar amartyaghoshgfg Rajput-Ji datomarjanidze guptavivek0503 Codenation FactSet Goldman Sachs Kritikal Solutions Microsoft Qualcomm Samsung Visa Arrays Linked List Stack Microsoft Samsung FactSet Visa Goldman Sachs Qualcomm Codenation Kritikal Solutions Linked List Arrays Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Linear Search Reverse a linked list LinkedList in Java Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists Detect loop in a linked list
[ { "code": null, "e": 39003, "s": 38975, "text": "\n24 Apr, 2022" }, { "code": null, "e": 39176, "s": 39003, "text": "Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out)." }, { "code": null, "e": 39247, "s": 39176, "text": "Mainly the following four basic operations are performed in the stack:" }, { "code": null, "e": 39347, "s": 39247, "text": "Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition." }, { "code": null, "e": 39367, "s": 39347, "text": "Algorithm for push:" }, { "code": null, "e": 39479, "s": 39367, "text": "begin\n if stack is full\n return\n endif\nelse \n increment top\n stack[top] assign value\nend else\nend procedure" }, { "code": null, "e": 39654, "s": 39479, "text": "Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition." }, { "code": null, "e": 39673, "s": 39654, "text": "Algorithm for pop:" }, { "code": null, "e": 39800, "s": 39673, "text": "begin\n if stack is empty\n return\n endif\nelse\n store value of stack[top]\n decrement top\n return value\nend else\nend procedure" }, { "code": null, "e": 39851, "s": 39800, "text": "Peek or Top: Returns the top element of the stack." }, { "code": null, "e": 39871, "s": 39851, "text": "Algorithm for peek:" }, { "code": null, "e": 39912, "s": 39871, "text": "begin \n return stack[top]\nend procedure" }, { "code": null, "e": 39969, "s": 39912, "text": "isEmpty: Returns true if the stack is empty, else false." }, { "code": null, "e": 39992, "s": 39969, "text": "Algorithm for isEmpty:" }, { "code": null, "e": 40063, "s": 39992, "text": "begin\n if top < 1\n return true\n else\n return false\nend procedure" }, { "code": null, "e": 40461, "s": 40063, "text": "How to understand a stack practically? There are many real-life examples of a stack. Consider the simple example of plates stacked over one another in a canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow the LIFO/FILO order." }, { "code": null, "e": 40507, "s": 40461, "text": "Time Complexities of operations on the stack:" }, { "code": null, "e": 40615, "s": 40507, "text": "push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of these operations. " }, { "code": null, "e": 40642, "s": 40615, "text": "Applications of the stack:" }, { "code": null, "e": 40663, "s": 40642, "text": "Balancing of symbols" }, { "code": null, "e": 40699, "s": 40663, "text": "Infix to Postfix /Prefix conversion" }, { "code": null, "e": 40758, "s": 40699, "text": "Redo-undo features at many places like editors, photoshop." }, { "code": null, "e": 40804, "s": 40758, "text": "Forward and backward features in web browsers" }, { "code": null, "e": 40911, "s": 40804, "text": "Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and histogram problems." }, { "code": null, "e": 41349, "s": 40911, "text": "Backtracking is one of the algorithm designing techniques. Some examples of backtracking are the Knight-Tour problem, N-Queen problem, find your way through a maze, and game-like chess or checkers in all these problems we dive into someway if that way is not efficient we come back to the previous state and go into some another path. To get back from a current state we need to store the previous state for that purpose we need a stack." }, { "code": null, "e": 41428, "s": 41349, "text": "In Graph Algorithms like Topological Sorting and Strongly Connected Components" }, { "code": null, "e": 41613, "s": 41428, "text": "In Memory management, any modern computer uses a stack as the primary management for a running purpose. Each program that is running in a computer system has its own memory allocations" }, { "code": null, "e": 41939, "s": 41613, "text": "String reversal is also another application of stack. Here one by one each character gets inserted into the stack. So the first character of the string is on the bottom of the stack and the last element of a string is on the top of the stack. After Performing the pop operations on the stack we get a string in reverse order." }, { "code": null, "e": 41997, "s": 41939, "text": "Implementation: There are two ways to implement a stack: " }, { "code": null, "e": 42009, "s": 41997, "text": "Using array" }, { "code": null, "e": 42027, "s": 42009, "text": "Using linked list" }, { "code": null, "e": 42059, "s": 42027, "text": "Implementing Stack using Arrays" }, { "code": null, "e": 42063, "s": 42059, "text": "C++" }, { "code": null, "e": 42065, "s": 42063, "text": "C" }, { "code": null, "e": 42070, "s": 42065, "text": "Java" }, { "code": null, "e": 42078, "s": 42070, "text": "Python3" }, { "code": null, "e": 42081, "s": 42078, "text": "C#" }, { "code": null, "e": 42092, "s": 42081, "text": "Javascript" }, { "code": "/* C++ program to implement basic stack operations */#include <bits/stdc++.h> using namespace std; #define MAX 1000 class Stack { int top; public: int a[MAX]; // Maximum size of Stack Stack() { top = -1; } bool push(int x); int pop(); int peek(); bool isEmpty();}; bool Stack::push(int x){ if (top >= (MAX - 1)) { cout << \"Stack Overflow\"; return false; } else { a[++top] = x; cout << x << \" pushed into stack\\n\"; return true; }} int Stack::pop(){ if (top < 0) { cout << \"Stack Underflow\"; return 0; } else { int x = a[top--]; return x; }}int Stack::peek(){ if (top < 0) { cout << \"Stack is Empty\"; return 0; } else { int x = a[top]; return x; }} bool Stack::isEmpty(){ return (top < 0);} // Driver program to test above functionsint main(){ class Stack s; s.push(10); s.push(20); s.push(30); cout << s.pop() << \" Popped from stack\\n\"; //print all elements in stack : cout<<\"Elements present in stack : \"; while(!s.isEmpty()) { // print top element in stack cout<<s.peek()<<\" \"; // remove top element in stack s.pop(); } return 0;}", "e": 43340, "s": 42092, "text": null }, { "code": "// C program for array implementation of stack#include <limits.h>#include <stdio.h>#include <stdlib.h> // A structure to represent a stackstruct Stack { int top; unsigned capacity; int* array;}; // function to create a stack of given capacity. It initializes size of// stack as 0struct Stack* createStack(unsigned capacity){ struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*)malloc(stack->capacity * sizeof(int)); return stack;} // Stack is full when top is equal to the last indexint isFull(struct Stack* stack){ return stack->top == stack->capacity - 1;} // Stack is empty when top is equal to -1int isEmpty(struct Stack* stack){ return stack->top == -1;} // Function to add an item to stack. It increases top by 1void push(struct Stack* stack, int item){ if (isFull(stack)) return; stack->array[++stack->top] = item; printf(\"%d pushed to stack\\n\", item);} // Function to remove an item from stack. It decreases top by 1int pop(struct Stack* stack){ if (isEmpty(stack)) return INT_MIN; return stack->array[stack->top--];} // Function to return the top from stack without removing itint peek(struct Stack* stack){ if (isEmpty(stack)) return INT_MIN; return stack->array[stack->top];} // Driver program to test above functionsint main(){ struct Stack* stack = createStack(100); push(stack, 10); push(stack, 20); push(stack, 30); printf(\"%d popped from stack\\n\", pop(stack)); return 0;}", "e": 44904, "s": 43340, "text": null }, { "code": "/* Java program to implement basic stackoperations */class Stack { static final int MAX = 1000; int top; int a[] = new int[MAX]; // Maximum size of Stack boolean isEmpty() { return (top < 0); } Stack() { top = -1; } boolean push(int x) { if (top >= (MAX - 1)) { System.out.println(\"Stack Overflow\"); return false; } else { a[++top] = x; System.out.println(x + \" pushed into stack\"); return true; } } int pop() { if (top < 0) { System.out.println(\"Stack Underflow\"); return 0; } else { int x = a[top--]; return x; } } int peek() { if (top < 0) { System.out.println(\"Stack Underflow\"); return 0; } else { int x = a[top]; return x; } } void print(){ for(int i = top;i>-1;i--){ System.out.print(\" \"+ a[i]); } }} // Driver codeclass Main { public static void main(String args[]) { Stack s = new Stack(); s.push(10); s.push(20); s.push(30); System.out.println(s.pop() + \" Popped from stack\"); System.out.println(\"Top element is :\" + s.peek()); System.out.print(\"Elements present in stack :\"); s.print(); }}", "e": 46288, "s": 44904, "text": null }, { "code": "# Python program for implementation of stack # import maxsize from sys module# Used to return -infinite when stack is emptyfrom sys import maxsize # Function to create a stack. It initializes size of stack as 0def createStack(): stack = [] return stack # Stack is empty when stack size is 0def isEmpty(stack): return len(stack) == 0 # Function to add an item to stack. It increases size by 1def push(stack, item): stack.append(item) print(item + \" pushed to stack \") # Function to remove an item from stack. It decreases size by 1def pop(stack): if (isEmpty(stack)): return str(-maxsize -1) # return minus infinite return stack.pop() # Function to return the top from stack without removing itdef peek(stack): if (isEmpty(stack)): return str(-maxsize -1) # return minus infinite return stack[len(stack) - 1] # Driver program to test above functions stack = createStack()push(stack, str(10))push(stack, str(20))push(stack, str(30))print(pop(stack) + \" popped from stack\")", "e": 47311, "s": 46288, "text": null }, { "code": "// C# program to implement basic stack// operationsusing System; namespace ImplementStack {class Stack { private int[] ele; private int top; private int max; public Stack(int size) { ele = new int[size]; // Maximum size of Stack top = -1; max = size; } public void push(int item) { if (top == max - 1) { Console.WriteLine(\"Stack Overflow\"); return; } else { ele[++top] = item; } } public int pop() { if (top == -1) { Console.WriteLine(\"Stack is Empty\"); return -1; } else { Console.WriteLine(\"{0} popped from stack \", ele[top]); return ele[top--]; } } public int peek() { if (top == -1) { Console.WriteLine(\"Stack is Empty\"); return -1; } else { Console.WriteLine(\"{0} popped from stack \", ele[top]); return ele[top]; } } public void printStack() { if (top == -1) { Console.WriteLine(\"Stack is Empty\"); return; } else { for (int i = 0; i <= top; i++) { Console.WriteLine(\"{0} pushed into stack\", ele[i]); } } }} // Driver program to test above functionsclass Program { static void Main() { Stack p = new Stack(5); p.push(10); p.push(20); p.push(30); p.printStack(); p.pop(); }}}", "e": 48813, "s": 47311, "text": null }, { "code": "<script>/* javascript program to implement basic stackoperations*/ var t = -1; var MAX = 1000; var a = Array(MAX).fill(0); // Maximum size of Stack function isEmpty() { return (t < 0); } function push(x) { if (t >= (MAX - 1)) { document.write(\"Stack Overflow\"); return false; } else { t+=1; a[t] = x; document.write(x + \" pushed into stack<br/>\"); return true; } } function pop() { if (t < 0) { document.write(\"Stack Underflow\"); return 0; } else { var x = a[t]; t-=1; return x; } } function peek() { if (t < 0) { document.write(\"Stack Underflow\"); return 0; } else { var x = a[t]; return x; } } function print() { for (i = t; i > -1; i--) { document.write(\" \" + a[i]); } } push(10); push(20); push(30); document.write(pop() + \" Popped from stack\"); document.write(\"<br/>Top element is :\" + peek()); document.write(\"<br/>Elements present in stack : \"); print(); // This code is contributed by Rajput-Ji</script>", "e": 50087, "s": 48813, "text": null }, { "code": null, "e": 50097, "s": 50087, "text": "Output : " }, { "code": null, "e": 50237, "s": 50097, "text": "10 pushed into stack\n20 pushed into stack\n30 pushed into stack\n30 Popped from stack\nTop element is : 20\nElements present in stack : 20 10 " }, { "code": null, "e": 50429, "s": 50237, "text": "Pros: Easy to implement. Memory is saved as pointers are not involved. Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime. Implementing Stack using Linked List:" }, { "code": null, "e": 50433, "s": 50429, "text": "C++" }, { "code": null, "e": 50435, "s": 50433, "text": "C" }, { "code": null, "e": 50440, "s": 50435, "text": "Java" }, { "code": null, "e": 50448, "s": 50440, "text": "Python3" }, { "code": null, "e": 50451, "s": 50448, "text": "C#" }, { "code": null, "e": 50462, "s": 50451, "text": "Javascript" }, { "code": "// C++ program for linked list implementation of stack#include <bits/stdc++.h>using namespace std; // A structure to represent a stackclass StackNode {public: int data; StackNode* next;}; StackNode* newNode(int data){ StackNode* stackNode = new StackNode(); stackNode->data = data; stackNode->next = NULL; return stackNode;} int isEmpty(StackNode* root){ return !root;} void push(StackNode** root, int data){ StackNode* stackNode = newNode(data); stackNode->next = *root; *root = stackNode; cout << data << \" pushed to stack\\n\";} int pop(StackNode** root){ if (isEmpty(*root)) return INT_MIN; StackNode* temp = *root; *root = (*root)->next; int popped = temp->data; free(temp); return popped;} int peek(StackNode* root){ if (isEmpty(root)) return INT_MIN; return root->data;} // Driver codeint main(){ StackNode* root = NULL; push(&root, 10); push(&root, 20); push(&root, 30); cout << pop(&root) << \" popped from stack\\n\"; cout << \"Top element is \" << peek(root) << endl; cout<<\"Elements present in stack : \"; //print all elements in stack : while(!isEmpty(root)) { // print top element in stack cout<<peek(root)<<\" \"; // remove top element in stack pop(&root); } return 0;} // This is code is contributed by rathbhupendra", "e": 51831, "s": 50462, "text": null }, { "code": "// C program for linked list implementation of stack#include <limits.h>#include <stdio.h>#include <stdlib.h> // A structure to represent a stackstruct StackNode { int data; struct StackNode* next;}; struct StackNode* newNode(int data){ struct StackNode* stackNode = (struct StackNode*) malloc(sizeof(struct StackNode)); stackNode->data = data; stackNode->next = NULL; return stackNode;} int isEmpty(struct StackNode* root){ return !root;} void push(struct StackNode** root, int data){ struct StackNode* stackNode = newNode(data); stackNode->next = *root; *root = stackNode; printf(\"%d pushed to stack\\n\", data);} int pop(struct StackNode** root){ if (isEmpty(*root)) return INT_MIN; struct StackNode* temp = *root; *root = (*root)->next; int popped = temp->data; free(temp); return popped;} int peek(struct StackNode* root){ if (isEmpty(root)) return INT_MIN; return root->data;} int main(){ struct StackNode* root = NULL; push(&root, 10); push(&root, 20); push(&root, 30); printf(\"%d popped from stack\\n\", pop(&root)); printf(\"Top element is %d\\n\", peek(root)); return 0;}", "e": 53012, "s": 51831, "text": null }, { "code": "// Java Code for Linked List Implementation public class StackAsLinkedList { StackNode root; static class StackNode { int data; StackNode next; StackNode(int data) { this.data = data; } } public boolean isEmpty() { if (root == null) { return true; } else return false; } public void push(int data) { StackNode newNode = new StackNode(data); if (root == null) { root = newNode; } else { StackNode temp = root; root = newNode; newNode.next = temp; } System.out.println(data + \" pushed to stack\"); } public int pop() { int popped = Integer.MIN_VALUE; if (root == null) { System.out.println(\"Stack is Empty\"); } else { popped = root.data; root = root.next; } return popped; } public int peek() { if (root == null) { System.out.println(\"Stack is empty\"); return Integer.MIN_VALUE; } else { return root.data; } } // Driver code public static void main(String[] args) { StackAsLinkedList sll = new StackAsLinkedList(); sll.push(10); sll.push(20); sll.push(30); System.out.println(sll.pop() + \" popped from stack\"); System.out.println(\"Top element is \" + sll.peek()); }}", "e": 54499, "s": 53012, "text": null }, { "code": "# Python program for linked list implementation of stack # Class to represent a node class StackNode: # Constructor to initialize a node def __init__(self, data): self.data = data self.next = None class Stack: # Constructor to initialize the root of linked list def __init__(self): self.root = None def isEmpty(self): return True if self.root is None else False def push(self, data): newNode = StackNode(data) newNode.next = self.root self.root = newNode print (\"% d pushed to stack\" % (data)) def pop(self): if (self.isEmpty()): return float(\"-inf\") temp = self.root self.root = self.root.next popped = temp.data return popped def peek(self): if self.isEmpty(): return float(\"-inf\") return self.root.data # Driver codestack = Stack()stack.push(10)stack.push(20)stack.push(30) print (\"% d popped from stack\" % (stack.pop()))print (\"Top element is % d \" % (stack.peek())) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 55593, "s": 54499, "text": null }, { "code": "// C# Code for Linked List Implementationusing System; public class StackAsLinkedList { StackNode root; public class StackNode { public int data; public StackNode next; public StackNode(int data) { this.data = data; } } public bool isEmpty() { if (root == null) { return true; } else return false; } public void push(int data) { StackNode newNode = new StackNode(data); if (root == null) { root = newNode; } else { StackNode temp = root; root = newNode; newNode.next = temp; } Console.WriteLine(data + \" pushed to stack\"); } public int pop() { int popped = int.MinValue; if (root == null) { Console.WriteLine(\"Stack is Empty\"); } else { popped = root.data; root = root.next; } return popped; } public int peek() { if (root == null) { Console.WriteLine(\"Stack is empty\"); return int.MinValue; } else { return root.data; } } // Driver code public static void Main(String[] args) { StackAsLinkedList sll = new StackAsLinkedList(); sll.push(10); sll.push(20); sll.push(30); Console.WriteLine(sll.pop() + \" popped from stack\"); Console.WriteLine(\"Top element is \" + sll.peek()); }} /* This code contributed by PrinciRaj1992 */", "e": 57113, "s": 55593, "text": null }, { "code": "<script>// javascript Code for Linked List Implementation var root; class StackNode { constructor(data) { this.data = data; this.next = null; } } function isEmpty() { if (root == null) { return true; } else return false; } function push(data) { var newNode = new StackNode(data); if (root == null) { root = newNode; } else { var temp = root; root = newNode; newNode.next = temp; } document.write(data + \" pushed to stack<br/>\"); } function pop() { var popped = Number.MIN_VALUE; if (root == null) { document.write(\"Stack is Empty\"); } else { popped = root.data; root = root.next; } return popped; } function peek() { if (root == null) { document.write(\"Stack is empty\"); return Number.MIN_VALUE; } else { return root.data; } } // Driver code push(10); push(20); push(30); document.write(pop() + \" popped from stack<br/>\"); document.write(\"Top element is \" + peek()); // This code is contributed by Rajput-Ji</script>", "e": 58386, "s": 57113, "text": null }, { "code": null, "e": 58394, "s": 58386, "text": "Output:" }, { "code": null, "e": 58525, "s": 58394, "text": "10 pushed to stack\n20 pushed to stack\n30 pushed to stack\n30 popped from stack\nTop element is 20\nElements present in stack : 20 10 " }, { "code": null, "e": 58688, "s": 58525, "text": "Pros: The linked list implementation of a stack can grow and shrink according to the needs at runtime. Cons: Requires extra memory due to involvement of pointers." }, { "code": null, "e": 58799, "s": 58688, "text": "https://youtu.be/vZEuSFXSMDI We will cover the implementation of applications of the stack in separate posts." }, { "code": null, "e": 58833, "s": 58799, "text": "Stack Set -2 (Infix to Postfix) " }, { "code": null, "e": 58855, "s": 58833, "text": "Quiz: Stack Questions" }, { "code": null, "e": 58947, "s": 58855, "text": "References: http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29#Problem_Description" }, { "code": null, "e": 59072, "s": 58947, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 59085, "s": 59072, "text": "mr_processor" }, { "code": null, "e": 59098, "s": 59085, "text": "SoumikMondal" }, { "code": null, "e": 59112, "s": 59098, "text": "SahilSharma19" }, { "code": null, "e": 59122, "s": 59112, "text": "Ankit Rai" }, { "code": null, "e": 59136, "s": 59122, "text": "rathbhupendra" }, { "code": null, "e": 59150, "s": 59136, "text": "princiraj1992" }, { "code": null, "e": 59163, "s": 59150, "text": "KIRTANPATEL2" }, { "code": null, "e": 59167, "s": 59163, "text": "gp6" }, { "code": null, "e": 59177, "s": 59167, "text": "sidhijain" }, { "code": null, "e": 59194, "s": 59177, "text": "deepak710agarwal" }, { "code": null, "e": 59204, "s": 59194, "text": "asdhamidi" }, { "code": null, "e": 59218, "s": 59204, "text": "akashjindal06" }, { "code": null, "e": 59237, "s": 59218, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 59253, "s": 59237, "text": "amartyaghoshgfg" }, { "code": null, "e": 59263, "s": 59253, "text": "Rajput-Ji" }, { "code": null, "e": 59278, "s": 59263, "text": "datomarjanidze" }, { "code": null, "e": 59293, "s": 59278, "text": "guptavivek0503" }, { "code": null, "e": 59304, "s": 59293, "text": "Codenation" }, { "code": null, "e": 59312, "s": 59304, "text": "FactSet" }, { "code": null, "e": 59326, "s": 59312, "text": "Goldman Sachs" }, { "code": null, "e": 59345, "s": 59326, "text": "Kritikal Solutions" }, { "code": null, "e": 59355, "s": 59345, "text": "Microsoft" }, { "code": null, "e": 59364, "s": 59355, "text": "Qualcomm" }, { "code": null, "e": 59372, "s": 59364, "text": "Samsung" }, { "code": null, "e": 59377, "s": 59372, "text": "Visa" }, { "code": null, "e": 59384, "s": 59377, "text": "Arrays" }, { "code": null, "e": 59396, "s": 59384, "text": "Linked List" }, { "code": null, "e": 59402, "s": 59396, "text": "Stack" }, { "code": null, "e": 59412, "s": 59402, "text": "Microsoft" }, { "code": null, "e": 59420, "s": 59412, "text": "Samsung" }, { "code": null, "e": 59428, "s": 59420, "text": "FactSet" }, { "code": null, "e": 59433, "s": 59428, "text": "Visa" }, { "code": null, "e": 59447, "s": 59433, "text": "Goldman Sachs" }, { "code": null, "e": 59456, "s": 59447, "text": "Qualcomm" }, { "code": null, "e": 59467, "s": 59456, "text": "Codenation" }, { "code": null, "e": 59486, "s": 59467, "text": "Kritikal Solutions" }, { "code": null, "e": 59498, "s": 59486, "text": "Linked List" }, { "code": null, "e": 59505, "s": 59498, "text": "Arrays" }, { "code": null, "e": 59511, "s": 59505, "text": "Stack" }, { "code": null, "e": 59609, "s": 59511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 59677, "s": 59609, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 59709, "s": 59677, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 59753, "s": 59709, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 59785, "s": 59753, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 59799, "s": 59785, "text": "Linear Search" }, { "code": null, "e": 59821, "s": 59799, "text": "Reverse a linked list" }, { "code": null, "e": 59840, "s": 59821, "text": "LinkedList in Java" }, { "code": null, "e": 59896, "s": 59840, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 59926, "s": 59896, "text": "Merge two sorted linked lists" } ]
How to set the input field value dynamically in AngularJS ? - GeeksforGeeks
29 Sep, 2020 Given an input field and the task is to set the input field value dynamically with the help of AngularJS. Approach: A value is being set to the input field despite the user enter something or not. ng-click event is used to call a function that sets the value to ‘This is GeeksForGeeks’ with the help of ng-model. Example 1: In this example, the input field is read-only So the user can not modify it and the value is set dynamically. HTML <!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.nameText = ''; $scope.setVal = function () { $scope.nameText = "This is GeeksForGeeks"; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to set the <input> field value dynamically in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Input field: <input type="text" readonly name="mytext" ng-model="nameText"> <br><br> <input type="button" ng-click="setVal()" value="Set Dynamically"> <br> </div> </div></body> </html> Output: Example 2: In this example, user can modify the input field but the value entered by user can be set dynamically. HTML <!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.nameText = ''; $scope.setVal = function () { $scope.nameText = "This is GeeksForGeeks"; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to set the <input> field value dynamically in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Input field: <input type="text" name="mytext" ng-model="nameText"> <br> <br> <input type="button" ng-click="setVal()" value="Set Dynamically"> <br> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. AngularJS-Misc HTML-Misc AngularJS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? How to bundle an Angular app for production? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26254, "s": 26226, "text": "\n29 Sep, 2020" }, { "code": null, "e": 26360, "s": 26254, "text": "Given an input field and the task is to set the input field value dynamically with the help of AngularJS." }, { "code": null, "e": 26371, "s": 26360, "text": "Approach: " }, { "code": null, "e": 26453, "s": 26371, "text": "A value is being set to the input field despite the user enter something or not. " }, { "code": null, "e": 26569, "s": 26453, "text": "ng-click event is used to call a function that sets the value to ‘This is GeeksForGeeks’ with the help of ng-model." }, { "code": null, "e": 26690, "s": 26569, "text": "Example 1: In this example, the input field is read-only So the user can not modify it and the value is set dynamically." }, { "code": null, "e": 26695, "s": 26690, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.nameText = ''; $scope.setVal = function () { $scope.nameText = \"This is GeeksForGeeks\"; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to set the <input> field value dynamically in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Input field: <input type=\"text\" readonly name=\"mytext\" ng-model=\"nameText\"> <br><br> <input type=\"button\" ng-click=\"setVal()\" value=\"Set Dynamically\"> <br> </div> </div></body> </html>", "e": 27677, "s": 26695, "text": null }, { "code": null, "e": 27685, "s": 27677, "text": "Output:" }, { "code": null, "e": 27799, "s": 27685, "text": "Example 2: In this example, user can modify the input field but the value entered by user can be set dynamically." }, { "code": null, "e": 27804, "s": 27799, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.nameText = ''; $scope.setVal = function () { $scope.nameText = \"This is GeeksForGeeks\"; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to set the <input> field value dynamically in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Input field: <input type=\"text\" name=\"mytext\" ng-model=\"nameText\"> <br> <br> <input type=\"button\" ng-click=\"setVal()\" value=\"Set Dynamically\"> <br> </div> </div></body> </html>", "e": 28773, "s": 27804, "text": null }, { "code": null, "e": 28781, "s": 28773, "text": "Output:" }, { "code": null, "e": 28918, "s": 28781, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28933, "s": 28918, "text": "AngularJS-Misc" }, { "code": null, "e": 28943, "s": 28933, "text": "HTML-Misc" }, { "code": null, "e": 28953, "s": 28943, "text": "AngularJS" }, { "code": null, "e": 28958, "s": 28953, "text": "HTML" }, { "code": null, "e": 28975, "s": 28958, "text": "Web Technologies" }, { "code": null, "e": 29002, "s": 28975, "text": "Web technologies Questions" }, { "code": null, "e": 29007, "s": 29002, "text": "HTML" }, { "code": null, "e": 29105, "s": 29007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29140, "s": 29105, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29171, "s": 29140, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29206, "s": 29171, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29248, "s": 29206, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 29293, "s": 29248, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 29355, "s": 29293, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29405, "s": 29355, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29453, "s": 29405, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29513, "s": 29453, "text": "How to set the default value for an HTML <select> element ?" } ]
Kotlin Reflection - GeeksforGeeks
09 Sep, 2021 Reflection is a set of language and library features that provides the feature of introspecting a given program at runtime. Kotlin reflection is used to utilize class and its members like properties, functions, constructors, etc. at runtime. Along with Java reflection API, Kotlin also provides its own set of reflection API, in a simple functional style. The standard Java Reflection constructs are also available in Kotlin and work perfectly with its code. Kotlin reflections are available in: kotlin.reflect package It gives access to properties and nullable typesKotlin reflection has some additional features to Java reflection.kotlin reflection helps in accessing the JVM code, written by a language It gives access to properties and nullable types Kotlin reflection has some additional features to Java reflection. kotlin reflection helps in accessing the JVM code, written by a language To obtain, a class reference at runtime which is statically known, use the class reference operator. Also, the reference to a class can also be obtained from the instances of the class, such references are known as bounded class references. Using instances, you obtain the reference to the exact type to which the object conforms to, in case of inheritance. Example to demonstrate Class references Java // A sample empty classclass ReflectionDemo {} fun main(){ // Reference obtained using class name val abc = ReflectionDemo::class println("This is a class reference $abc") // Reference obtained using object val obj = ReflectionDemo() println("This is a bounded class reference ${obj::class}")} Output This is a class reference class kotlin1.com.programmingKotlin.chapter1.ReflectionDemo This is a bounded class reference class kotlin1.com.programmingKotlin.chapter1.ReflectionDemo We can obtain a functional reference to every named function that is defined in Kotlin. This can be done by preceding the function name, with the :: operator. These functional references can then be used as parameters to other functions. In the case of overloaded functions, we can either explicitly specify the type of the function, or it can be implicitly determined from the content.Example to demonstrate Functional References Java fun add(a: Int,b: Int) : Int{ return a+b;} fun add(a: String,b: String): String{ return """$a$b"""} fun isDivisibleBy3(a: Int): Boolean{ return a%3 == 0}fun main(){ // Function reference obtained using :: operator val ref1 = ::isDivisibleBy3 val array = listOf<Int>(1,2,3,4,5,6,7,8,9) println(array.filter(ref1)) // Function reference obtained for an overloaded function // By explicitly specifying the type val ref2: (String,String) -> String = ::add; println(ref2) // Function reference obtained implicitly val x = add(3,5) println(x)} Output [3, 6, 9] fun add(kotlin.String, kotlin.String): kotlin.String 8 We can obtain property reference in a similar fashion as that of function, using the :: operator. If the property belongs to a class than the classname should also be specified with the :: operator. These property references allow us to treat a property as an object that is, we can obtain there values using get function or modify it using set function.Example to demonstrate Property References Java class Property(var a: Float){} val x = 10; fun main(){ // Property Reference for a package level property val z = ::x println(z.get()) println(z.name) // Property Reference for a class property val y = Property::a println(y.get(Property(5.899f)))} Output 10 x 5.899 The references to constructors of a class can be obtained in a similar manner as the references for methods and properties. These references can be used as references to a function which returns an object of that type. However, these uses are rare.Example to demonstrate Constructor References Java class Property(var a: Float){}fun main(){ // Constructor Reference val y = ::Property println(y.name)} Output <init> abhishek0719kadiyan Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android How to Add and Customize Back Button of Action Bar in Android? How to Get Current Location in Android? Kotlin Setters and Getters Kotlin Android Tutorial How to Change the Color of Status Bar in an Android App? Kotlin when expression
[ { "code": null, "e": 25161, "s": 25133, "text": "\n09 Sep, 2021" }, { "code": null, "e": 25658, "s": 25161, "text": "Reflection is a set of language and library features that provides the feature of introspecting a given program at runtime. Kotlin reflection is used to utilize class and its members like properties, functions, constructors, etc. at runtime. Along with Java reflection API, Kotlin also provides its own set of reflection API, in a simple functional style. The standard Java Reflection constructs are also available in Kotlin and work perfectly with its code. Kotlin reflections are available in: " }, { "code": null, "e": 25681, "s": 25658, "text": "kotlin.reflect package" }, { "code": null, "e": 25869, "s": 25681, "text": "It gives access to properties and nullable typesKotlin reflection has some additional features to Java reflection.kotlin reflection helps in accessing the JVM code, written by a language " }, { "code": null, "e": 25918, "s": 25869, "text": "It gives access to properties and nullable types" }, { "code": null, "e": 25985, "s": 25918, "text": "Kotlin reflection has some additional features to Java reflection." }, { "code": null, "e": 26059, "s": 25985, "text": "kotlin reflection helps in accessing the JVM code, written by a language " }, { "code": null, "e": 26458, "s": 26059, "text": "To obtain, a class reference at runtime which is statically known, use the class reference operator. Also, the reference to a class can also be obtained from the instances of the class, such references are known as bounded class references. Using instances, you obtain the reference to the exact type to which the object conforms to, in case of inheritance. Example to demonstrate Class references " }, { "code": null, "e": 26463, "s": 26458, "text": "Java" }, { "code": "// A sample empty classclass ReflectionDemo {} fun main(){ // Reference obtained using class name val abc = ReflectionDemo::class println(\"This is a class reference $abc\") // Reference obtained using object val obj = ReflectionDemo() println(\"This is a bounded class reference ${obj::class}\")}", "e": 26776, "s": 26463, "text": null }, { "code": null, "e": 26784, "s": 26776, "text": "Output " }, { "code": null, "e": 26965, "s": 26784, "text": "This is a class reference class kotlin1.com.programmingKotlin.chapter1.ReflectionDemo\nThis is a bounded class reference class kotlin1.com.programmingKotlin.chapter1.ReflectionDemo " }, { "code": null, "e": 27397, "s": 26965, "text": "We can obtain a functional reference to every named function that is defined in Kotlin. This can be done by preceding the function name, with the :: operator. These functional references can then be used as parameters to other functions. In the case of overloaded functions, we can either explicitly specify the type of the function, or it can be implicitly determined from the content.Example to demonstrate Functional References " }, { "code": null, "e": 27402, "s": 27397, "text": "Java" }, { "code": "fun add(a: Int,b: Int) : Int{ return a+b;} fun add(a: String,b: String): String{ return \"\"\"$a$b\"\"\"} fun isDivisibleBy3(a: Int): Boolean{ return a%3 == 0}fun main(){ // Function reference obtained using :: operator val ref1 = ::isDivisibleBy3 val array = listOf<Int>(1,2,3,4,5,6,7,8,9) println(array.filter(ref1)) // Function reference obtained for an overloaded function // By explicitly specifying the type val ref2: (String,String) -> String = ::add; println(ref2) // Function reference obtained implicitly val x = add(3,5) println(x)}", "e": 27988, "s": 27402, "text": null }, { "code": null, "e": 27996, "s": 27988, "text": "Output " }, { "code": null, "e": 28062, "s": 27996, "text": "[3, 6, 9]\nfun add(kotlin.String, kotlin.String): kotlin.String\n8 " }, { "code": null, "e": 28460, "s": 28062, "text": "We can obtain property reference in a similar fashion as that of function, using the :: operator. If the property belongs to a class than the classname should also be specified with the :: operator. These property references allow us to treat a property as an object that is, we can obtain there values using get function or modify it using set function.Example to demonstrate Property References " }, { "code": null, "e": 28465, "s": 28460, "text": "Java" }, { "code": "class Property(var a: Float){} val x = 10; fun main(){ // Property Reference for a package level property val z = ::x println(z.get()) println(z.name) // Property Reference for a class property val y = Property::a println(y.get(Property(5.899f)))}", "e": 28738, "s": 28465, "text": null }, { "code": null, "e": 28746, "s": 28738, "text": "Output " }, { "code": null, "e": 28758, "s": 28746, "text": "10\nx\n5.899 " }, { "code": null, "e": 29053, "s": 28758, "text": "The references to constructors of a class can be obtained in a similar manner as the references for methods and properties. These references can be used as references to a function which returns an object of that type. However, these uses are rare.Example to demonstrate Constructor References " }, { "code": null, "e": 29058, "s": 29053, "text": "Java" }, { "code": "class Property(var a: Float){}fun main(){ // Constructor Reference val y = ::Property println(y.name)}", "e": 29170, "s": 29058, "text": null }, { "code": null, "e": 29178, "s": 29170, "text": "Output " }, { "code": null, "e": 29185, "s": 29178, "text": "<init>" }, { "code": null, "e": 29205, "s": 29185, "text": "abhishek0719kadiyan" }, { "code": null, "e": 29212, "s": 29205, "text": "Picked" }, { "code": null, "e": 29219, "s": 29212, "text": "Kotlin" }, { "code": null, "e": 29317, "s": 29219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29360, "s": 29317, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29391, "s": 29360, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29433, "s": 29391, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29475, "s": 29433, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29538, "s": 29475, "text": "How to Add and Customize Back Button of Action Bar in Android?" }, { "code": null, "e": 29578, "s": 29538, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 29605, "s": 29578, "text": "Kotlin Setters and Getters" }, { "code": null, "e": 29629, "s": 29605, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 29686, "s": 29629, "text": "How to Change the Color of Status Bar in an Android App?" } ]
How to Write DSA Articles on GeeksforGeeks? - GeeksforGeeks
03 Jan, 2022 GeeksforGeeks provides all the coding enthusiasts an opportunity to showcase their programming and Data Structures & Algorithms skills by writing coding or DSA-based articles. However, a lot of individuals (especially college students or beginners) find it difficult to articulate their learnings & skills and contribute at GeeksforGeeks. But now the problem has got solved as this article will guide you through the entire process and guidelines of writing Programming/DSA articles at GeeksforGeeks. Let’s get started: First and foremost, you need to know how to get started with article writing at GFG along with various other fundamental aspects like why should you contribute, where to write, etc. You can check out this link to know all these details in a comprehensive manner. Now, you need to check whether you can write an article on a particular topic/problem or not. You can do the same by following the below-mentioned steps: Search the title and problem statement in the Custom search on GeeksforGeeks. If existing, don’t write.Then search the title, problem statement, and examples (together and/or individually) on Google to find related existing links from other websites. If the same content is available somewhere as well, such as Codility, Codeforces, etc, this will lead to plagiarism and hence cannot be accepted.Search some basic variations or generalized problem statements. If found, it will be considered plagiarism. Search the title and problem statement in the Custom search on GeeksforGeeks. If existing, don’t write. Then search the title, problem statement, and examples (together and/or individually) on Google to find related existing links from other websites. If the same content is available somewhere as well, such as Codility, Codeforces, etc, this will lead to plagiarism and hence cannot be accepted. Search some basic variations or generalized problem statements. If found, it will be considered plagiarism. If the article passes the above points, the article can be written. Moving further, let’s check out the format and guidelines that you need to follow while writing a coding article at GeeksforGeeks. The programming articles should contain the following points: Problem StatementExamples (Two). Explanation of examples to get a proper understanding of how we achieved the result.Links of prerequisites for the approach if there are any.The approach used to solve the problem.First, a basic idea or intuitionThen the step by step points regarding how this approach will workHighlight any important observation or point using bold, blockquote, or pre.Implementation / Code. If there are codes in multiple languages, the order should be C++, Java, Python3, C#. Please note that Python 2 codes are not accepted but Python 3 codes are accepted.Time Complexity and Auxiliary Space, with the explanation of the terms used to express these. Problem Statement Examples (Two). Explanation of examples to get a proper understanding of how we achieved the result. Links of prerequisites for the approach if there are any. The approach used to solve the problem.First, a basic idea or intuitionThen the step by step points regarding how this approach will workHighlight any important observation or point using bold, blockquote, or pre. First, a basic idea or intuitionThen the step by step points regarding how this approach will workHighlight any important observation or point using bold, blockquote, or pre. First, a basic idea or intuition Then the step by step points regarding how this approach will work Highlight any important observation or point using bold, blockquote, or pre. Implementation / Code. If there are codes in multiple languages, the order should be C++, Java, Python3, C#. Please note that Python 2 codes are not accepted but Python 3 codes are accepted. Time Complexity and Auxiliary Space, with the explanation of the terms used to express these. Please try to keep the language simple, specific, and free from pronouns like I, you, we, etc If the approach is: We create a mark[] array of Boolean type. We iterate through all the characters of our string and whenever we see a character we mark it. Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25. The above can be written as: This approach is based on Hashing. A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’, and so on.Traverse the string character by character and mark the particular character as present in the Hash.After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False. A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’, and so on. Traverse the string character by character and mark the particular character as present in the Hash. After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False. Problem – Print all unique combinations of setting N pieces on an NxN board Approach: This problem can be solved by using recursion to generate all possible solutions. Now, follow the steps below to solve this problem: Create a function named allCombinations, which will generate all possible solutions.It will take an integer piecesPlaced denoting the number of total pieces placed, integer N denoting the number of pieces needed to be placed, two integers row and col denoting the row and column where the current piece is going to be placed and a string ans for storing the matrix where pieces are placed, as arguments.Now, the initial call to allCombinations will pass 0 as piecesPlaced, N, 0 and 0 as row and col and an empty string as ans.In each call, check for the base case, that is:If row becomes N and all pieces are placed, i.e. piecesPlaced=N. Then print the ans and return. Else if piecesPlaced is not N, then just return from this call.Now make two calls:One to add a ‘*’ at the current position, and one to leave that position and add ‘-‘.After this, the recursive calls will print all the possible solutions. Create a function named allCombinations, which will generate all possible solutions. It will take an integer piecesPlaced denoting the number of total pieces placed, integer N denoting the number of pieces needed to be placed, two integers row and col denoting the row and column where the current piece is going to be placed and a string ans for storing the matrix where pieces are placed, as arguments. Now, the initial call to allCombinations will pass 0 as piecesPlaced, N, 0 and 0 as row and col and an empty string as ans. In each call, check for the base case, that is:If row becomes N and all pieces are placed, i.e. piecesPlaced=N. Then print the ans and return. Else if piecesPlaced is not N, then just return from this call. If row becomes N and all pieces are placed, i.e. piecesPlaced=N. Then print the ans and return. Else if piecesPlaced is not N, then just return from this call. Now make two calls:One to add a ‘*’ at the current position, and one to leave that position and add ‘-‘. One to add a ‘*’ at the current position, and one to leave that position and add ‘-‘. After this, the recursive calls will print all the possible solutions. Moving further, now you need to understand the process of adding the code in the article. It is as follows: You can use the ‘Add Code’ button to add the code. To add code in multiple programming languages you can choose Add Another Language option as shown below. After that click on Proceed Button. In case your code does not compile or run due to any reason like libraries not supported by the compiler, you wish to demonstrate errors, etc, please uncheck Enable Run on Ide option to remove run buttons from the code. This button also avoids errors when your try to append output using the “Append Output” button which is just next to the ‘Add Code‘ button. You need to ensure that you’re following the below-mentioned coding standards: 1) Function and variable names follow the camel case. For example, getMin(), getMax() and removeDuplicates(), isPresent, etc. 2) Driver code (or main function) does not contain any logic. It contains only input/output and function call. 3) Indentation should be done using 4 spaces. 4) Maximum 60 characters in a line so that the program is readable on mobile devices without much horizontal scrolling. C // Below style should be avoidedint fun(int a, int sumSoFar, int currSum, char val, int *result) // The above should be written asint fun(int a, int sumSoFar, int currSum, char val, int *result) C++ // Below style should be avoided cout << "Sample code to understand coding style for more readability of millions of readers" << val; // The above should be written ascout << "Sample code to understand coding style for" << " more readability of millions of readers" << val; 5) In case the code is written in multiple languages like Python, Java, and C/C++, the output of all codes should be the same. 6) Avoid the use of scanf (or cin) statements. 7) Spaces in while, if, else, for C // There should be one space after while, no other// spaceswhile (i < 0) if (x < y){ } 8) There should not be any spaces for a function call or function declaration C // No spaces after "reverse" or after "("void reverse(char* str, int low, int high){ while (low < high) { swap(&str[low], &str[high]); ++low; --high; }} // Driver program to test above functionint main(){ char str[] = "geeksforgeeks"; reverse(str); return 0;} 9) Avoid the use of typdef. 10) Function names should be of the form “maxOfTwo()”, variable names should be of the form “max_of_two” or same as function name style. Class/Struct names should be of the form “ComplexNumber” or “SuffixTreeNode”. Macro names should be in capital letters like MAX_SIZE. 11) Avoid the use of static and global variables. 12) When we use cout, we must use a space between cout and “<<” and space between two “<<“. For example: C++ cout << "Sample" << "Example" 13) There should be space after comma in the declaration list and parameter passing. C int x, y, z; fun(x, y, z); 14) There should be spaces in assignment operators C // Should be avoidedint x, y=0; // Should be followedint x, y = 0; // Should be avoidedx+=10; // Should be followedx += 10; 15) At the beginning of every program, please write a line to tell the purpose of the program: Java // Java program to illustrate sum of two numbers Note: It is strongly recommended to add time complexity after your code in data structures/algorithm articles. The image creation guidelines are as follows: The name of the image must be Relevant. For example, if an image depicts”: “Adding of two numbers using Linked List”, the title of the image must be: Adding of two numbers using Linked List. In case of images being built using the packet tracer, please send the screen recording in place of the image if possible. In case of screenshots, please add GeeksforGeeks (or GFG) somewhere in output. For example, it may be folder name, image title, etc. It is mandatory to create your own images using some image drawing tool (For ex: Google Drawings, MS Paint, https://www.draw.io/). Images MUST NOT be taken from any other source to avoid any copyright issue. You can follow the below guidelines to create images in GeeksforGeeks style:The boundary/outline of the image should be of black color.The text to be written should be of green color.Our priority should be to use a white background, if other background colors are needed, please use green as background and white color in the text.Red color should be used to show movements, representations, variations, and other things.If more colors are required in the image, Please contact GeeksforGeeks’s reviewers to guide you. The boundary/outline of the image should be of black color. The text to be written should be of green color. Our priority should be to use a white background, if other background colors are needed, please use green as background and white color in the text. Red color should be used to show movements, representations, variations, and other things. If more colors are required in the image, Please contact GeeksforGeeks’s reviewers to guide you. Please see below the example image, to get a clear idea about the image creation of an Array: 1. If the approach is quite simple or concise then there is no need to mention step-by-step points for solving the problem – the steps to solve the problem can be covered in that single paragraph itself. For example – check out this article: Sort a linked list after converting elements to their square 2. Add Time Complexity and Auxiliary Space after your code in data structures/algorithm articles. Check out the article for reference purposes: Print all unique combinations of setting N pieces on an NxN board 3. While using an Efficient Approach for solving a problem, you first need to tell why it is better than the Naive/Old Approach. For example – check out this article: Count of pairs (arr[i], arr[j]) such that arr[i] + j and arr[j] + i are equal 4. A few more sample articles: Maximize the sum of elements arr[i] selected by jumping index by value i Find if 0 is removed more or 1 by deleting middle element if consecutive triplet is divisible by 3 in given Binary Array Check if a number can be expressed as product of a prime and a composite number Note: Problem directly taken from Codility & Codeforces cannot be published due to copyright issues. Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Start Learning DSA? Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions What Should I Learn First: Data Structures or Algorithms? Shortest path in a directed graph by Dijkstra’s algorithm Insertion in a B+ tree Find the parent of a node in the given binary tree Finding in and out degrees of all vertices in a graph Why Data Structures and Algorithms Are Important to Learn?
[ { "code": null, "e": 26273, "s": 26245, "text": "\n03 Jan, 2022" }, { "code": null, "e": 26774, "s": 26273, "text": "GeeksforGeeks provides all the coding enthusiasts an opportunity to showcase their programming and Data Structures & Algorithms skills by writing coding or DSA-based articles. However, a lot of individuals (especially college students or beginners) find it difficult to articulate their learnings & skills and contribute at GeeksforGeeks. But now the problem has got solved as this article will guide you through the entire process and guidelines of writing Programming/DSA articles at GeeksforGeeks." }, { "code": null, "e": 26793, "s": 26774, "text": "Let’s get started:" }, { "code": null, "e": 27056, "s": 26793, "text": "First and foremost, you need to know how to get started with article writing at GFG along with various other fundamental aspects like why should you contribute, where to write, etc. You can check out this link to know all these details in a comprehensive manner." }, { "code": null, "e": 27210, "s": 27056, "text": "Now, you need to check whether you can write an article on a particular topic/problem or not. You can do the same by following the below-mentioned steps:" }, { "code": null, "e": 27714, "s": 27210, "text": "Search the title and problem statement in the Custom search on GeeksforGeeks. If existing, don’t write.Then search the title, problem statement, and examples (together and/or individually) on Google to find related existing links from other websites. If the same content is available somewhere as well, such as Codility, Codeforces, etc, this will lead to plagiarism and hence cannot be accepted.Search some basic variations or generalized problem statements. If found, it will be considered plagiarism." }, { "code": null, "e": 27818, "s": 27714, "text": "Search the title and problem statement in the Custom search on GeeksforGeeks. If existing, don’t write." }, { "code": null, "e": 28112, "s": 27818, "text": "Then search the title, problem statement, and examples (together and/or individually) on Google to find related existing links from other websites. If the same content is available somewhere as well, such as Codility, Codeforces, etc, this will lead to plagiarism and hence cannot be accepted." }, { "code": null, "e": 28220, "s": 28112, "text": "Search some basic variations or generalized problem statements. If found, it will be considered plagiarism." }, { "code": null, "e": 28288, "s": 28220, "text": "If the article passes the above points, the article can be written." }, { "code": null, "e": 28481, "s": 28288, "text": "Moving further, let’s check out the format and guidelines that you need to follow while writing a coding article at GeeksforGeeks. The programming articles should contain the following points:" }, { "code": null, "e": 29152, "s": 28481, "text": "Problem StatementExamples (Two). Explanation of examples to get a proper understanding of how we achieved the result.Links of prerequisites for the approach if there are any.The approach used to solve the problem.First, a basic idea or intuitionThen the step by step points regarding how this approach will workHighlight any important observation or point using bold, blockquote, or pre.Implementation / Code. If there are codes in multiple languages, the order should be C++, Java, Python3, C#. Please note that Python 2 codes are not accepted but Python 3 codes are accepted.Time Complexity and Auxiliary Space, with the explanation of the terms used to express these." }, { "code": null, "e": 29170, "s": 29152, "text": "Problem Statement" }, { "code": null, "e": 29271, "s": 29170, "text": "Examples (Two). Explanation of examples to get a proper understanding of how we achieved the result." }, { "code": null, "e": 29329, "s": 29271, "text": "Links of prerequisites for the approach if there are any." }, { "code": null, "e": 29543, "s": 29329, "text": "The approach used to solve the problem.First, a basic idea or intuitionThen the step by step points regarding how this approach will workHighlight any important observation or point using bold, blockquote, or pre." }, { "code": null, "e": 29718, "s": 29543, "text": "First, a basic idea or intuitionThen the step by step points regarding how this approach will workHighlight any important observation or point using bold, blockquote, or pre." }, { "code": null, "e": 29751, "s": 29718, "text": "First, a basic idea or intuition" }, { "code": null, "e": 29818, "s": 29751, "text": "Then the step by step points regarding how this approach will work" }, { "code": null, "e": 29895, "s": 29818, "text": "Highlight any important observation or point using bold, blockquote, or pre." }, { "code": null, "e": 30086, "s": 29895, "text": "Implementation / Code. If there are codes in multiple languages, the order should be C++, Java, Python3, C#. Please note that Python 2 codes are not accepted but Python 3 codes are accepted." }, { "code": null, "e": 30180, "s": 30086, "text": "Time Complexity and Auxiliary Space, with the explanation of the terms used to express these." }, { "code": null, "e": 30274, "s": 30180, "text": "Please try to keep the language simple, specific, and free from pronouns like I, you, we, etc" }, { "code": null, "e": 30294, "s": 30274, "text": "If the approach is:" }, { "code": null, "e": 30568, "s": 30294, "text": "We create a mark[] array of Boolean type. We iterate through all the characters of our string and whenever we see a character we mark it. Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25." }, { "code": null, "e": 30597, "s": 30568, "text": "The above can be written as:" }, { "code": null, "e": 30634, "s": 30597, "text": "This approach is based on Hashing. " }, { "code": null, "e": 31073, "s": 30634, "text": "A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’, and so on.Traverse the string character by character and mark the particular character as present in the Hash.After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False." }, { "code": null, "e": 31228, "s": 31073, "text": "A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’, and so on." }, { "code": null, "e": 31329, "s": 31228, "text": "Traverse the string character by character and mark the particular character as present in the Hash." }, { "code": null, "e": 31514, "s": 31329, "text": "After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False." }, { "code": null, "e": 31590, "s": 31514, "text": "Problem – Print all unique combinations of setting N pieces on an NxN board" }, { "code": null, "e": 31733, "s": 31590, "text": "Approach: This problem can be solved by using recursion to generate all possible solutions. Now, follow the steps below to solve this problem:" }, { "code": null, "e": 32640, "s": 31733, "text": "Create a function named allCombinations, which will generate all possible solutions.It will take an integer piecesPlaced denoting the number of total pieces placed, integer N denoting the number of pieces needed to be placed, two integers row and col denoting the row and column where the current piece is going to be placed and a string ans for storing the matrix where pieces are placed, as arguments.Now, the initial call to allCombinations will pass 0 as piecesPlaced, N, 0 and 0 as row and col and an empty string as ans.In each call, check for the base case, that is:If row becomes N and all pieces are placed, i.e. piecesPlaced=N. Then print the ans and return. Else if piecesPlaced is not N, then just return from this call.Now make two calls:One to add a ‘*’ at the current position, and one to leave that position and add ‘-‘.After this, the recursive calls will print all the possible solutions." }, { "code": null, "e": 32725, "s": 32640, "text": "Create a function named allCombinations, which will generate all possible solutions." }, { "code": null, "e": 33045, "s": 32725, "text": "It will take an integer piecesPlaced denoting the number of total pieces placed, integer N denoting the number of pieces needed to be placed, two integers row and col denoting the row and column where the current piece is going to be placed and a string ans for storing the matrix where pieces are placed, as arguments." }, { "code": null, "e": 33169, "s": 33045, "text": "Now, the initial call to allCombinations will pass 0 as piecesPlaced, N, 0 and 0 as row and col and an empty string as ans." }, { "code": null, "e": 33376, "s": 33169, "text": "In each call, check for the base case, that is:If row becomes N and all pieces are placed, i.e. piecesPlaced=N. Then print the ans and return. Else if piecesPlaced is not N, then just return from this call." }, { "code": null, "e": 33536, "s": 33376, "text": "If row becomes N and all pieces are placed, i.e. piecesPlaced=N. Then print the ans and return. Else if piecesPlaced is not N, then just return from this call." }, { "code": null, "e": 33641, "s": 33536, "text": "Now make two calls:One to add a ‘*’ at the current position, and one to leave that position and add ‘-‘." }, { "code": null, "e": 33727, "s": 33641, "text": "One to add a ‘*’ at the current position, and one to leave that position and add ‘-‘." }, { "code": null, "e": 33798, "s": 33727, "text": "After this, the recursive calls will print all the possible solutions." }, { "code": null, "e": 33906, "s": 33798, "text": "Moving further, now you need to understand the process of adding the code in the article. It is as follows:" }, { "code": null, "e": 33957, "s": 33906, "text": "You can use the ‘Add Code’ button to add the code." }, { "code": null, "e": 34098, "s": 33957, "text": "To add code in multiple programming languages you can choose Add Another Language option as shown below. After that click on Proceed Button." }, { "code": null, "e": 34458, "s": 34098, "text": "In case your code does not compile or run due to any reason like libraries not supported by the compiler, you wish to demonstrate errors, etc, please uncheck Enable Run on Ide option to remove run buttons from the code. This button also avoids errors when your try to append output using the “Append Output” button which is just next to the ‘Add Code‘ button." }, { "code": null, "e": 34537, "s": 34458, "text": "You need to ensure that you’re following the below-mentioned coding standards:" }, { "code": null, "e": 34663, "s": 34537, "text": "1) Function and variable names follow the camel case. For example, getMin(), getMax() and removeDuplicates(), isPresent, etc." }, { "code": null, "e": 34774, "s": 34663, "text": "2) Driver code (or main function) does not contain any logic. It contains only input/output and function call." }, { "code": null, "e": 34820, "s": 34774, "text": "3) Indentation should be done using 4 spaces." }, { "code": null, "e": 34940, "s": 34820, "text": "4) Maximum 60 characters in a line so that the program is readable on mobile devices without much horizontal scrolling." }, { "code": null, "e": 34942, "s": 34940, "text": "C" }, { "code": "// Below style should be avoidedint fun(int a, int sumSoFar, int currSum, char val, int *result) // The above should be written asint fun(int a, int sumSoFar, int currSum, char val, int *result)", "e": 35146, "s": 34942, "text": null }, { "code": null, "e": 35150, "s": 35146, "text": "C++" }, { "code": "// Below style should be avoided cout << \"Sample code to understand coding style for more readability of millions of readers\" << val; // The above should be written ascout << \"Sample code to understand coding style for\" << \" more readability of millions of readers\" << val;", "e": 35434, "s": 35150, "text": null }, { "code": null, "e": 35561, "s": 35434, "text": "5) In case the code is written in multiple languages like Python, Java, and C/C++, the output of all codes should be the same." }, { "code": null, "e": 35608, "s": 35561, "text": "6) Avoid the use of scanf (or cin) statements." }, { "code": null, "e": 35642, "s": 35608, "text": "7) Spaces in while, if, else, for" }, { "code": null, "e": 35644, "s": 35642, "text": "C" }, { "code": "// There should be one space after while, no other// spaceswhile (i < 0) if (x < y){ }", "e": 35738, "s": 35644, "text": null }, { "code": null, "e": 35816, "s": 35738, "text": "8) There should not be any spaces for a function call or function declaration" }, { "code": null, "e": 35818, "s": 35816, "text": "C" }, { "code": "// No spaces after \"reverse\" or after \"(\"void reverse(char* str, int low, int high){ while (low < high) { swap(&str[low], &str[high]); ++low; --high; }} // Driver program to test above functionint main(){ char str[] = \"geeksforgeeks\"; reverse(str); return 0;}", "e": 36120, "s": 35818, "text": null }, { "code": null, "e": 36148, "s": 36120, "text": "9) Avoid the use of typdef." }, { "code": null, "e": 36419, "s": 36148, "text": "10) Function names should be of the form “maxOfTwo()”, variable names should be of the form “max_of_two” or same as function name style. Class/Struct names should be of the form “ComplexNumber” or “SuffixTreeNode”. Macro names should be in capital letters like MAX_SIZE." }, { "code": null, "e": 36469, "s": 36419, "text": "11) Avoid the use of static and global variables." }, { "code": null, "e": 36574, "s": 36469, "text": "12) When we use cout, we must use a space between cout and “<<” and space between two “<<“. For example:" }, { "code": null, "e": 36578, "s": 36574, "text": "C++" }, { "code": "cout << \"Sample\" << \"Example\"", "e": 36608, "s": 36578, "text": null }, { "code": null, "e": 36693, "s": 36608, "text": "13) There should be space after comma in the declaration list and parameter passing." }, { "code": null, "e": 36695, "s": 36693, "text": "C" }, { "code": "int x, y, z; fun(x, y, z);", "e": 36723, "s": 36695, "text": null }, { "code": null, "e": 36774, "s": 36723, "text": "14) There should be spaces in assignment operators" }, { "code": null, "e": 36776, "s": 36774, "text": "C" }, { "code": "// Should be avoidedint x, y=0; // Should be followedint x, y = 0; // Should be avoidedx+=10; // Should be followedx += 10;", "e": 36906, "s": 36776, "text": null }, { "code": null, "e": 37001, "s": 36906, "text": "15) At the beginning of every program, please write a line to tell the purpose of the program:" }, { "code": null, "e": 37006, "s": 37001, "text": "Java" }, { "code": "// Java program to illustrate sum of two numbers", "e": 37055, "s": 37006, "text": null }, { "code": null, "e": 37166, "s": 37055, "text": "Note: It is strongly recommended to add time complexity after your code in data structures/algorithm articles." }, { "code": null, "e": 37212, "s": 37166, "text": "The image creation guidelines are as follows:" }, { "code": null, "e": 37403, "s": 37212, "text": "The name of the image must be Relevant. For example, if an image depicts”: “Adding of two numbers using Linked List”, the title of the image must be: Adding of two numbers using Linked List." }, { "code": null, "e": 37526, "s": 37403, "text": "In case of images being built using the packet tracer, please send the screen recording in place of the image if possible." }, { "code": null, "e": 37659, "s": 37526, "text": "In case of screenshots, please add GeeksforGeeks (or GFG) somewhere in output. For example, it may be folder name, image title, etc." }, { "code": null, "e": 38385, "s": 37659, "text": "It is mandatory to create your own images using some image drawing tool (For ex: Google Drawings, MS Paint, https://www.draw.io/). Images MUST NOT be taken from any other source to avoid any copyright issue. You can follow the below guidelines to create images in GeeksforGeeks style:The boundary/outline of the image should be of black color.The text to be written should be of green color.Our priority should be to use a white background, if other background colors are needed, please use green as background and white color in the text.Red color should be used to show movements, representations, variations, and other things.If more colors are required in the image, Please contact GeeksforGeeks’s reviewers to guide you." }, { "code": null, "e": 38445, "s": 38385, "text": "The boundary/outline of the image should be of black color." }, { "code": null, "e": 38494, "s": 38445, "text": "The text to be written should be of green color." }, { "code": null, "e": 38643, "s": 38494, "text": "Our priority should be to use a white background, if other background colors are needed, please use green as background and white color in the text." }, { "code": null, "e": 38734, "s": 38643, "text": "Red color should be used to show movements, representations, variations, and other things." }, { "code": null, "e": 38831, "s": 38734, "text": "If more colors are required in the image, Please contact GeeksforGeeks’s reviewers to guide you." }, { "code": null, "e": 38925, "s": 38831, "text": "Please see below the example image, to get a clear idea about the image creation of an Array:" }, { "code": null, "e": 39230, "s": 38927, "text": "1. If the approach is quite simple or concise then there is no need to mention step-by-step points for solving the problem – the steps to solve the problem can be covered in that single paragraph itself. For example – check out this article: Sort a linked list after converting elements to their square" }, { "code": null, "e": 39440, "s": 39230, "text": "2. Add Time Complexity and Auxiliary Space after your code in data structures/algorithm articles. Check out the article for reference purposes: Print all unique combinations of setting N pieces on an NxN board" }, { "code": null, "e": 39686, "s": 39440, "text": "3. While using an Efficient Approach for solving a problem, you first need to tell why it is better than the Naive/Old Approach. For example – check out this article: Count of pairs (arr[i], arr[j]) such that arr[i] + j and arr[j] + i are equal" }, { "code": null, "e": 39717, "s": 39686, "text": "4. A few more sample articles:" }, { "code": null, "e": 39790, "s": 39717, "text": "Maximize the sum of elements arr[i] selected by jumping index by value i" }, { "code": null, "e": 39911, "s": 39790, "text": "Find if 0 is removed more or 1 by deleting middle element if consecutive triplet is divisible by 3 in given Binary Array" }, { "code": null, "e": 39991, "s": 39911, "text": "Check if a number can be expressed as product of a prime and a composite number" }, { "code": null, "e": 40092, "s": 39991, "text": "Note: Problem directly taken from Codility & Codeforces cannot be published due to copyright issues." }, { "code": null, "e": 40108, "s": 40092, "text": "Data Structures" }, { "code": null, "e": 40124, "s": 40108, "text": "Data Structures" }, { "code": null, "e": 40222, "s": 40124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40249, "s": 40222, "text": "How to Start Learning DSA?" }, { "code": null, "e": 40285, "s": 40249, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 40344, "s": 40285, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 40392, "s": 40344, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 40450, "s": 40392, "text": "What Should I Learn First: Data Structures or Algorithms?" }, { "code": null, "e": 40508, "s": 40450, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 40531, "s": 40508, "text": "Insertion in a B+ tree" }, { "code": null, "e": 40582, "s": 40531, "text": "Find the parent of a node in the given binary tree" }, { "code": null, "e": 40636, "s": 40582, "text": "Finding in and out degrees of all vertices in a graph" } ]
Print numbers 1 to N using Indirect recursion - GeeksforGeeks
13 May, 2022 Given a number N, we need to print numbers from 1 to N with out direct recursion, loops, labels. Basically we need to insert in above code snippet so that it can be able to print numbers from 1 to N? C #include <stdio.h>#define N 20;int main(){ // Your code goes Here.} Examples : Input : 10 Output : 1 2 3 4 5 6 7 8 9 10 Input : 5 Output : 1 2 3 4 5 We have already discussed solutions in below posts : Print 1 to 100 in C++, without loop and recursion How will you print numbers from 1 to 100 without using loop? Here’s the code that can print the numbers from 1 to 100 with out direct recursion, loops and labels. The code uses indirect recursion. C++ C Java Python3 C# PHP Javascript // C++ program to print from 1 to N using// indirect recursion/#include<bits/stdc++.h>using namespace std; // We can avoid use of these using referencesint N = 20;int n = 1; void fun1();void fun2(); // Prints n, increments n and calls fun1()void fun1(){ if (n <= N) { cout << n << " "; n++; fun2(); } else return;} // Prints n, increments n and calls fun2()void fun2(){ if (n <= N) { cout << n << " "; n++; fun1(); } else return;} // Driver Programint main(){ fun1(); return 0;} // This code is contributed by pankajsharmagfg. // C program to print from 1 to N using// indirect recursion/#include<stdio.h> // We can avoid use of these using references#define N 20;int n = 1; // Prints n, increments n and calls fun1()void fun1(){ if (n <= N) { printf("%d", n); n++; fun2(); } else return;} // Prints n, increments n and calls fun2()void fun2(){ if (n <= N) { printf("%d", n); n++; fun1(); } else return;} // Driver Programint main(void){ fun1(); return 0;} // Java program to print from 1 to N using// indirect recursionclass GFG{ // We can avoid use of these using references static final int N = 20; static int n = 1; // Prints n, increments n and calls fun1() static void fun1() { if (n <= N) { System.out.printf("%d ", n); n++; fun2(); } else { return; } } // Prints n, increments n and calls fun2() static void fun2() { if (n <= N) { System.out.printf("%d ", n); n++; fun1(); } else { return; } } // Driver Program public static void main(String[] args) { fun1(); }} // This code is contributed by Rajput-Ji # Python program to print from 1 to N using# indirect recursion # We can avoid use of these using referencesN = 20;n = 1; # Prints n, increments n and calls fun1()def fun1(): global N, n; if (n <= N): print(n, end = " "); n += 1; fun2(); else: return; # Prints n, increments n and calls fun2()def fun2(): global N, n; if (n <= N): print(n, end = " "); n += 1; fun1(); else: return; # Driver Programif __name__ == '__main__': fun1(); # This code is contributed by 29AjayKumar // C# program to print from 1 to N using// indirect recursionusing System; class GFG{ // We can avoid use of these using references static readonly int N = 20; static int n = 1; // Prints n, increments n and calls fun1() static void fun1() { if (n <= N) { Console.Write("{0} ", n); n++; fun2(); } else { return; } } // Prints n, increments n and calls fun2() static void fun2() { if (n <= N) { Console.Write("{0} ", n); n++; fun1(); } else { return; } } // Driver Code public static void Main(String[] args) { fun1(); }} // This code is contributed by Rajput-Ji <?php// PHP program to print// from 1 to N using// indirect recursion // We can avoid use of// these using references$N = 20;$n = 1; // Prints n, increments// n and calls fun1()function fun1(){ global $N; global $n; if ($n <= $N) { echo $n, " "; $n++; fun2(); } else return;} // Prints n, increments// n and calls fun2()function fun2(){ global $N; global $n; if ($n <= $N) { echo $n, " "; $n++; fun1(); } else return;} // Driver Codefun1(); // This code is contributed// by m_kit?> <script> // Javascript program to print from 1 to N using// indirect recursion // We can avoid use of these using referenceslet N = 20;let n = 1 // Prints n, increments n and calls fun1()function fun1(){ if (n <= N) { document.write( n+" "); n++; fun2(); } else { return; }} // Prints n, increments n and calls fun2()function fun2(){ if (n <= N) { document.write(n+" "); n++; fun1(); } else { return; }} // Driver codefun1(); // This code is contributed by rag2127 </script> Output : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 How This works?: In above program, we just used two functions. One calls others and other one calls previous one, therefore indirect recursion. Exercise : Modify the above program to use N as a parameter instead of making it global. This article is contributed by Umamaheswararao Tumma of Jntuh college of Engineering Hyderabad. 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 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. jit_t Rajput-Ji 29AjayKumar rag2127 pankajsharmagfg simmytarika5 sagartomar9927 Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing What are Hash Functions and How to choose a good Hash Function? Difference between Informed and Uninformed Search in AI
[ { "code": null, "e": 25943, "s": 25915, "text": "\n13 May, 2022" }, { "code": null, "e": 26144, "s": 25943, "text": "Given a number N, we need to print numbers from 1 to N with out direct recursion, loops, labels. Basically we need to insert in above code snippet so that it can be able to print numbers from 1 to N? " }, { "code": null, "e": 26146, "s": 26144, "text": "C" }, { "code": "#include <stdio.h>#define N 20;int main(){ // Your code goes Here.}", "e": 26216, "s": 26146, "text": null }, { "code": null, "e": 26229, "s": 26216, "text": "Examples : " }, { "code": null, "e": 26302, "s": 26229, "text": "Input : 10\nOutput : 1 2 3 4 5 6 7 8 9 10\n\nInput : 5\nOutput : 1 2 3 4 5" }, { "code": null, "e": 26467, "s": 26302, "text": "We have already discussed solutions in below posts : Print 1 to 100 in C++, without loop and recursion How will you print numbers from 1 to 100 without using loop? " }, { "code": null, "e": 26604, "s": 26467, "text": "Here’s the code that can print the numbers from 1 to 100 with out direct recursion, loops and labels. The code uses indirect recursion. " }, { "code": null, "e": 26608, "s": 26604, "text": "C++" }, { "code": null, "e": 26610, "s": 26608, "text": "C" }, { "code": null, "e": 26615, "s": 26610, "text": "Java" }, { "code": null, "e": 26623, "s": 26615, "text": "Python3" }, { "code": null, "e": 26626, "s": 26623, "text": "C#" }, { "code": null, "e": 26630, "s": 26626, "text": "PHP" }, { "code": null, "e": 26641, "s": 26630, "text": "Javascript" }, { "code": "// C++ program to print from 1 to N using// indirect recursion/#include<bits/stdc++.h>using namespace std; // We can avoid use of these using referencesint N = 20;int n = 1; void fun1();void fun2(); // Prints n, increments n and calls fun1()void fun1(){ if (n <= N) { cout << n << \" \"; n++; fun2(); } else return;} // Prints n, increments n and calls fun2()void fun2(){ if (n <= N) { cout << n << \" \"; n++; fun1(); } else return;} // Driver Programint main(){ fun1(); return 0;} // This code is contributed by pankajsharmagfg.", "e": 27254, "s": 26641, "text": null }, { "code": "// C program to print from 1 to N using// indirect recursion/#include<stdio.h> // We can avoid use of these using references#define N 20;int n = 1; // Prints n, increments n and calls fun1()void fun1(){ if (n <= N) { printf(\"%d\", n); n++; fun2(); } else return;} // Prints n, increments n and calls fun2()void fun2(){ if (n <= N) { printf(\"%d\", n); n++; fun1(); } else return;} // Driver Programint main(void){ fun1(); return 0;}", "e": 27770, "s": 27254, "text": null }, { "code": "// Java program to print from 1 to N using// indirect recursionclass GFG{ // We can avoid use of these using references static final int N = 20; static int n = 1; // Prints n, increments n and calls fun1() static void fun1() { if (n <= N) { System.out.printf(\"%d \", n); n++; fun2(); } else { return; } } // Prints n, increments n and calls fun2() static void fun2() { if (n <= N) { System.out.printf(\"%d \", n); n++; fun1(); } else { return; } } // Driver Program public static void main(String[] args) { fun1(); }} // This code is contributed by Rajput-Ji", "e": 28553, "s": 27770, "text": null }, { "code": "# Python program to print from 1 to N using# indirect recursion # We can avoid use of these using referencesN = 20;n = 1; # Prints n, increments n and calls fun1()def fun1(): global N, n; if (n <= N): print(n, end = \" \"); n += 1; fun2(); else: return; # Prints n, increments n and calls fun2()def fun2(): global N, n; if (n <= N): print(n, end = \" \"); n += 1; fun1(); else: return; # Driver Programif __name__ == '__main__': fun1(); # This code is contributed by 29AjayKumar", "e": 29106, "s": 28553, "text": null }, { "code": "// C# program to print from 1 to N using// indirect recursionusing System; class GFG{ // We can avoid use of these using references static readonly int N = 20; static int n = 1; // Prints n, increments n and calls fun1() static void fun1() { if (n <= N) { Console.Write(\"{0} \", n); n++; fun2(); } else { return; } } // Prints n, increments n and calls fun2() static void fun2() { if (n <= N) { Console.Write(\"{0} \", n); n++; fun1(); } else { return; } } // Driver Code public static void Main(String[] args) { fun1(); }} // This code is contributed by Rajput-Ji", "e": 29895, "s": 29106, "text": null }, { "code": "<?php// PHP program to print// from 1 to N using// indirect recursion // We can avoid use of// these using references$N = 20;$n = 1; // Prints n, increments// n and calls fun1()function fun1(){ global $N; global $n; if ($n <= $N) { echo $n, \" \"; $n++; fun2(); } else return;} // Prints n, increments// n and calls fun2()function fun2(){ global $N; global $n; if ($n <= $N) { echo $n, \" \"; $n++; fun1(); } else return;} // Driver Codefun1(); // This code is contributed// by m_kit?>", "e": 30470, "s": 29895, "text": null }, { "code": "<script> // Javascript program to print from 1 to N using// indirect recursion // We can avoid use of these using referenceslet N = 20;let n = 1 // Prints n, increments n and calls fun1()function fun1(){ if (n <= N) { document.write( n+\" \"); n++; fun2(); } else { return; }} // Prints n, increments n and calls fun2()function fun2(){ if (n <= N) { document.write(n+\" \"); n++; fun1(); } else { return; }} // Driver codefun1(); // This code is contributed by rag2127 </script>", "e": 31037, "s": 30470, "text": null }, { "code": null, "e": 31047, "s": 31037, "text": "Output : " }, { "code": null, "e": 31099, "s": 31047, "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 " }, { "code": null, "e": 31244, "s": 31099, "text": "How This works?: In above program, we just used two functions. One calls others and other one calls previous one, therefore indirect recursion." }, { "code": null, "e": 31333, "s": 31244, "text": "Exercise : Modify the above program to use N as a parameter instead of making it global." }, { "code": null, "e": 31805, "s": 31333, "text": "This article is contributed by Umamaheswararao Tumma of Jntuh college of Engineering Hyderabad. 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 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": 31811, "s": 31805, "text": "jit_t" }, { "code": null, "e": 31821, "s": 31811, "text": "Rajput-Ji" }, { "code": null, "e": 31833, "s": 31821, "text": "29AjayKumar" }, { "code": null, "e": 31841, "s": 31833, "text": "rag2127" }, { "code": null, "e": 31857, "s": 31841, "text": "pankajsharmagfg" }, { "code": null, "e": 31870, "s": 31857, "text": "simmytarika5" }, { "code": null, "e": 31885, "s": 31870, "text": "sagartomar9927" }, { "code": null, "e": 31896, "s": 31885, "text": "Algorithms" }, { "code": null, "e": 31907, "s": 31896, "text": "Algorithms" }, { "code": null, "e": 32005, "s": 31907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32030, "s": 32005, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32057, "s": 32030, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32110, "s": 32057, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 32144, "s": 32110, "text": "K means Clustering - Introduction" }, { "code": null, "e": 32211, "s": 32144, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 32254, "s": 32211, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 32283, "s": 32254, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 32347, "s": 32283, "text": "What are Hash Functions and How to choose a good Hash Function?" } ]
TCS Placement Paper | MCQ 10 - GeeksforGeeks
21 May, 2019 This is a TCS model placement paper for aptitude preparation. This placement paper will cover aptitude questions that are asked in TCS recruitment drives and also strictly follows the pattern of questions asked in TCS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the TCS interview. All even numbers from 2 to 98 inclusive the both, are to be multiplied together. What is the unit digit of the product?a) 2b) 0c) 6d) 4Answer: b) 0Solution:Let us look at the sequence of the multiplications,2 * 4 * 6 * 8 *10* 12 * 14 * 16 * 18 *...* 98If we look closely we will find that the units place of every number forms a sequence of 2, 4, 6 ,8 and 0 multiplying to a number whose units place is always 0 and in all we get 0. So the unit digit of final number = 0.10 programmers are able to type 10 lines in 10 minutes. How many programmer are required to type 60 lines in 60 minutes?a) 10b) 16c) 60d) None of the aboveAnswer: a) 10Solution:This is a simple question of logical reasoning. If 10 programmers can type 10 lines of code in 10 minutes then to type 60 lines of code, in 60 minutes, the same 10 coders will be required, since the lines of code and time are in proportionAnil works for 8 straight days and rest on the 9th day. If he starts his work on Monday, then on which day he gets his 12th rest day?a) Thursdayb) Tuesdayc) Wednesdayd) FridayAnswer: c) WednesdaySolution:Anil works for 8 days and rests on 9th day. In total 9 days are to be processed 12 times = 12 * 9 = 108.If we calculate according to the week, we get 108 / 7 = remaining 3 days. So if Anil starts working on Monday, he will rest on third day of the week which is Wednesday.Overfishing is a serious environmental issue. The scientists were able to determine that if the net of a trawler has a mesh size of ‘x’ cm (a square mesh), then the percentage of fish entering the net is caught in the net is expressed in form of the quadratic equation, 100 – 0.04x^2- 0.24x. For example, if the mesh size is zero, 100% of the fish that enter the net will be caught. A trawler with a net with a square mesh, that was suspect of using an illegal size net, dropped its net to the ocean floor near the Lakshadweep and the coast guard, arrested the crew. It was later looked at the size of the fish caught and estimated that for the net used by the trawler, at least 97.8% of the fish entering the net would be caught. What is the maximum value of x for the net used by the trawler?a) 7b) 4.5c) 6d) 5Answer: d) 5Solution:According to the question,for few values of x, the total fish caught is 97.8%. So=> 100 – 0.04x^2- 0.24x = 97.8=> 0.04x^2 + 0.24x = 2.2=> 4x^2+ 24x = 220=> x^2+ 6x – 55 = 0Solving, we get x = 5 and -11So, the value of x = 5 has to be positive and hence the answer.The rejection rate for Audi production was 4 per cent, for Mercedes it was 8 per cent and for the 2 cars combined it was 7 per cent. What was the ratio of Audi production?a) 4/1b) 2/1c) 3/1d) 7/1Answer: c) 3/1Solution:Using the simple weighted average formula we get,(4x + 8y)/(x+y) = 7or, 4x + 8y = 7x + 7yor, a/b = 3/1A team of 11 is needed to be formed who are to be selected from 5 men and 11 women, with the restriction of selecting not more than 3 men. In how many ways can the selection be done?a) 1121b) 1565c) 1243d) 2256Answer: d) 2256Solution:Selecting 0 men and 11 women = 5C0 * 11C11 = 1Selecting 1 men and 10 women = 5C1 * 11C10 = 55Selecting 2 men and 9 women = 5C2 * 11C9 = 10 * 55 = 550Selecting 3 men and 8 women = 5C3 * 11C8 = 10 * 165 = 1650So total number of ways = 1650 + 550 + 55 + 1 = 2256 wayThere are two bags containing white and black marbles. In the first bag there are 8 white marbles and 6 black marbles and in the second bag, there are 4 white marbles and 7 black marbles. One marble is drawn at random from any of these two bags. Find the probability of this marble being black.a) 7/54b) 7/154c) 41/77d) 22/77Answer: c) 41/77Solution:Probability of drawing a black ball from the first bag is = 6C1 / 14C1Probability of drawing a black ball from the second bag is = 7C1 / 11C1Total probability = 1/2 * (6C1/14C1) * (7C1/11C1) = 41/77There is a city where all 100% votes are registered. Among this 60% votes for Congress and 40% votes for BJP. Ram, gets 75% of congress votes and 8% of BJP votes. How many votes did Ram get?a) 48.2 %b) 56.6 %c) 42.8 %d) 64.4 %Answer: a) 48.2 %Solution:Let the total number if votes = 100. So Ram gets,75% of 60 = 60 * 0.75 = 45 votes8% of 40 = 40 * 0.08 = 3.2 votesThus total number of votes that Ram gets = 48.2 %John is faster than Peter. John and Peter each walk 24 km. Sum of the speeds of John and Peter is 7 km/h. Sum of time taken by them is 14 hours. Find John’s speed.a) 4 km/hb) 5 km/hc) 3 km/hd) 7 km/hAnswer: a) 4 km/hSolution:We know that John’s speed is greater than Peter’s speed and the sum of there speed is 7.So the combinations are = (6, 1), (5, 2), (4, 3)Now checking from the options if John’s speed is equal to 4, then Peter’s speed is 3,or, the time taken by them = 24/4 + 24/3 = 14 hours.If f(x) = 2x + 2 what is the value of f(f(3))?a) 8b) 64c) 16d) 18Answer: d) 18Solution;f(f(3)) = 2(f(3)) + 2=> 2(2(3) + 2) + 2=> 16 + 2 = 18 All even numbers from 2 to 98 inclusive the both, are to be multiplied together. What is the unit digit of the product?a) 2b) 0c) 6d) 4Answer: b) 0Solution:Let us look at the sequence of the multiplications,2 * 4 * 6 * 8 *10* 12 * 14 * 16 * 18 *...* 98If we look closely we will find that the units place of every number forms a sequence of 2, 4, 6 ,8 and 0 multiplying to a number whose units place is always 0 and in all we get 0. So the unit digit of final number = 0. Answer: b) 0 Solution:Let us look at the sequence of the multiplications,2 * 4 * 6 * 8 *10* 12 * 14 * 16 * 18 *...* 98If we look closely we will find that the units place of every number forms a sequence of 2, 4, 6 ,8 and 0 multiplying to a number whose units place is always 0 and in all we get 0. So the unit digit of final number = 0. 10 programmers are able to type 10 lines in 10 minutes. How many programmer are required to type 60 lines in 60 minutes?a) 10b) 16c) 60d) None of the aboveAnswer: a) 10Solution:This is a simple question of logical reasoning. If 10 programmers can type 10 lines of code in 10 minutes then to type 60 lines of code, in 60 minutes, the same 10 coders will be required, since the lines of code and time are in proportion Answer: a) 10 Solution:This is a simple question of logical reasoning. If 10 programmers can type 10 lines of code in 10 minutes then to type 60 lines of code, in 60 minutes, the same 10 coders will be required, since the lines of code and time are in proportion Anil works for 8 straight days and rest on the 9th day. If he starts his work on Monday, then on which day he gets his 12th rest day?a) Thursdayb) Tuesdayc) Wednesdayd) FridayAnswer: c) WednesdaySolution:Anil works for 8 days and rests on 9th day. In total 9 days are to be processed 12 times = 12 * 9 = 108.If we calculate according to the week, we get 108 / 7 = remaining 3 days. So if Anil starts working on Monday, he will rest on third day of the week which is Wednesday. Answer: c) Wednesday Solution:Anil works for 8 days and rests on 9th day. In total 9 days are to be processed 12 times = 12 * 9 = 108.If we calculate according to the week, we get 108 / 7 = remaining 3 days. So if Anil starts working on Monday, he will rest on third day of the week which is Wednesday. Overfishing is a serious environmental issue. The scientists were able to determine that if the net of a trawler has a mesh size of ‘x’ cm (a square mesh), then the percentage of fish entering the net is caught in the net is expressed in form of the quadratic equation, 100 – 0.04x^2- 0.24x. For example, if the mesh size is zero, 100% of the fish that enter the net will be caught. A trawler with a net with a square mesh, that was suspect of using an illegal size net, dropped its net to the ocean floor near the Lakshadweep and the coast guard, arrested the crew. It was later looked at the size of the fish caught and estimated that for the net used by the trawler, at least 97.8% of the fish entering the net would be caught. What is the maximum value of x for the net used by the trawler?a) 7b) 4.5c) 6d) 5Answer: d) 5Solution:According to the question,for few values of x, the total fish caught is 97.8%. So=> 100 – 0.04x^2- 0.24x = 97.8=> 0.04x^2 + 0.24x = 2.2=> 4x^2+ 24x = 220=> x^2+ 6x – 55 = 0Solving, we get x = 5 and -11So, the value of x = 5 has to be positive and hence the answer. Answer: d) 5 Solution:According to the question,for few values of x, the total fish caught is 97.8%. So=> 100 – 0.04x^2- 0.24x = 97.8=> 0.04x^2 + 0.24x = 2.2=> 4x^2+ 24x = 220=> x^2+ 6x – 55 = 0Solving, we get x = 5 and -11So, the value of x = 5 has to be positive and hence the answer. The rejection rate for Audi production was 4 per cent, for Mercedes it was 8 per cent and for the 2 cars combined it was 7 per cent. What was the ratio of Audi production?a) 4/1b) 2/1c) 3/1d) 7/1Answer: c) 3/1Solution:Using the simple weighted average formula we get,(4x + 8y)/(x+y) = 7or, 4x + 8y = 7x + 7yor, a/b = 3/1 Answer: c) 3/1 Solution:Using the simple weighted average formula we get,(4x + 8y)/(x+y) = 7or, 4x + 8y = 7x + 7yor, a/b = 3/1 A team of 11 is needed to be formed who are to be selected from 5 men and 11 women, with the restriction of selecting not more than 3 men. In how many ways can the selection be done?a) 1121b) 1565c) 1243d) 2256Answer: d) 2256Solution:Selecting 0 men and 11 women = 5C0 * 11C11 = 1Selecting 1 men and 10 women = 5C1 * 11C10 = 55Selecting 2 men and 9 women = 5C2 * 11C9 = 10 * 55 = 550Selecting 3 men and 8 women = 5C3 * 11C8 = 10 * 165 = 1650So total number of ways = 1650 + 550 + 55 + 1 = 2256 way Answer: d) 2256 Solution:Selecting 0 men and 11 women = 5C0 * 11C11 = 1Selecting 1 men and 10 women = 5C1 * 11C10 = 55Selecting 2 men and 9 women = 5C2 * 11C9 = 10 * 55 = 550Selecting 3 men and 8 women = 5C3 * 11C8 = 10 * 165 = 1650So total number of ways = 1650 + 550 + 55 + 1 = 2256 way There are two bags containing white and black marbles. In the first bag there are 8 white marbles and 6 black marbles and in the second bag, there are 4 white marbles and 7 black marbles. One marble is drawn at random from any of these two bags. Find the probability of this marble being black.a) 7/54b) 7/154c) 41/77d) 22/77Answer: c) 41/77Solution:Probability of drawing a black ball from the first bag is = 6C1 / 14C1Probability of drawing a black ball from the second bag is = 7C1 / 11C1Total probability = 1/2 * (6C1/14C1) * (7C1/11C1) = 41/77 Answer: c) 41/77 Solution:Probability of drawing a black ball from the first bag is = 6C1 / 14C1Probability of drawing a black ball from the second bag is = 7C1 / 11C1Total probability = 1/2 * (6C1/14C1) * (7C1/11C1) = 41/77 There is a city where all 100% votes are registered. Among this 60% votes for Congress and 40% votes for BJP. Ram, gets 75% of congress votes and 8% of BJP votes. How many votes did Ram get?a) 48.2 %b) 56.6 %c) 42.8 %d) 64.4 %Answer: a) 48.2 %Solution:Let the total number if votes = 100. So Ram gets,75% of 60 = 60 * 0.75 = 45 votes8% of 40 = 40 * 0.08 = 3.2 votesThus total number of votes that Ram gets = 48.2 % Answer: a) 48.2 % Solution:Let the total number if votes = 100. So Ram gets,75% of 60 = 60 * 0.75 = 45 votes8% of 40 = 40 * 0.08 = 3.2 votesThus total number of votes that Ram gets = 48.2 % John is faster than Peter. John and Peter each walk 24 km. Sum of the speeds of John and Peter is 7 km/h. Sum of time taken by them is 14 hours. Find John’s speed.a) 4 km/hb) 5 km/hc) 3 km/hd) 7 km/hAnswer: a) 4 km/hSolution:We know that John’s speed is greater than Peter’s speed and the sum of there speed is 7.So the combinations are = (6, 1), (5, 2), (4, 3)Now checking from the options if John’s speed is equal to 4, then Peter’s speed is 3,or, the time taken by them = 24/4 + 24/3 = 14 hours. Answer: a) 4 km/h Solution:We know that John’s speed is greater than Peter’s speed and the sum of there speed is 7.So the combinations are = (6, 1), (5, 2), (4, 3)Now checking from the options if John’s speed is equal to 4, then Peter’s speed is 3,or, the time taken by them = 24/4 + 24/3 = 14 hours. If f(x) = 2x + 2 what is the value of f(f(3))?a) 8b) 64c) 16d) 18Answer: d) 18Solution;f(f(3)) = 2(f(3)) + 2=> 2(2(3) + 2) + 2=> 16 + 2 = 18 Answer: d) 18 Solution;f(f(3)) = 2(f(3)) + 2=> 2(2(3) + 2) + 2=> 16 + 2 = 18 RupalRaturi interview-preparation placement preparation TCS Placements TCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 20 Puzzles Commonly Asked During SDE Interviews Codenation Recruitment Process Minimum changes required to make all Array elements Prime Permutation and Combination Progressions (AP, GP, HP) Interview Preparation Puzzle | 50 red marbles and 50 blue marbles C program to reverse the content of the file and print it Time Speed Distance Print the longest path from root to leaf in a Binary tree
[ { "code": null, "e": 25539, "s": 25511, "text": "\n21 May, 2019" }, { "code": null, "e": 25888, "s": 25539, "text": "This is a TCS model placement paper for aptitude preparation. This placement paper will cover aptitude questions that are asked in TCS recruitment drives and also strictly follows the pattern of questions asked in TCS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the TCS interview." }, { "code": null, "e": 30766, "s": 25888, "text": "All even numbers from 2 to 98 inclusive the both, are to be multiplied together. What is the unit digit of the product?a) 2b) 0c) 6d) 4Answer: b) 0Solution:Let us look at the sequence of the multiplications,2 * 4 * 6 * 8 *10* 12 * 14 * 16 * 18 *...* 98If we look closely we will find that the units place of every number forms a sequence of 2, 4, 6 ,8 and 0 multiplying to a number whose units place is always 0 and in all we get 0. So the unit digit of final number = 0.10 programmers are able to type 10 lines in 10 minutes. How many programmer are required to type 60 lines in 60 minutes?a) 10b) 16c) 60d) None of the aboveAnswer: a) 10Solution:This is a simple question of logical reasoning. If 10 programmers can type 10 lines of code in 10 minutes then to type 60 lines of code, in 60 minutes, the same 10 coders will be required, since the lines of code and time are in proportionAnil works for 8 straight days and rest on the 9th day. If he starts his work on Monday, then on which day he gets his 12th rest day?a) Thursdayb) Tuesdayc) Wednesdayd) FridayAnswer: c) WednesdaySolution:Anil works for 8 days and rests on 9th day. In total 9 days are to be processed 12 times = 12 * 9 = 108.If we calculate according to the week, we get 108 / 7 = remaining 3 days. So if Anil starts working on Monday, he will rest on third day of the week which is Wednesday.Overfishing is a serious environmental issue. The scientists were able to determine that if the net of a trawler has a mesh size of ‘x’ cm (a square mesh), then the percentage of fish entering the net is caught in the net is expressed in form of the quadratic equation, 100 – 0.04x^2- 0.24x. For example, if the mesh size is zero, 100% of the fish that enter the net will be caught. A trawler with a net with a square mesh, that was suspect of using an illegal size net, dropped its net to the ocean floor near the Lakshadweep and the coast guard, arrested the crew. It was later looked at the size of the fish caught and estimated that for the net used by the trawler, at least 97.8% of the fish entering the net would be caught. What is the maximum value of x for the net used by the trawler?a) 7b) 4.5c) 6d) 5Answer: d) 5Solution:According to the question,for few values of x, the total fish caught is 97.8%. So=> 100 – 0.04x^2- 0.24x = 97.8=> 0.04x^2 + 0.24x = 2.2=> 4x^2+ 24x = 220=> x^2+ 6x – 55 = 0Solving, we get x = 5 and -11So, the value of x = 5 has to be positive and hence the answer.The rejection rate for Audi production was 4 per cent, for Mercedes it was 8 per cent and for the 2 cars combined it was 7 per cent. What was the ratio of Audi production?a) 4/1b) 2/1c) 3/1d) 7/1Answer: c) 3/1Solution:Using the simple weighted average formula we get,(4x + 8y)/(x+y) = 7or, 4x + 8y = 7x + 7yor, a/b = 3/1A team of 11 is needed to be formed who are to be selected from 5 men and 11 women, with the restriction of selecting not more than 3 men. In how many ways can the selection be done?a) 1121b) 1565c) 1243d) 2256Answer: d) 2256Solution:Selecting 0 men and 11 women = 5C0 * 11C11 = 1Selecting 1 men and 10 women = 5C1 * 11C10 = 55Selecting 2 men and 9 women = 5C2 * 11C9 = 10 * 55 = 550Selecting 3 men and 8 women = 5C3 * 11C8 = 10 * 165 = 1650So total number of ways = 1650 + 550 + 55 + 1 = 2256 wayThere are two bags containing white and black marbles. In the first bag there are 8 white marbles and 6 black marbles and in the second bag, there are 4 white marbles and 7 black marbles. One marble is drawn at random from any of these two bags. Find the probability of this marble being black.a) 7/54b) 7/154c) 41/77d) 22/77Answer: c) 41/77Solution:Probability of drawing a black ball from the first bag is = 6C1 / 14C1Probability of drawing a black ball from the second bag is = 7C1 / 11C1Total probability = 1/2 * (6C1/14C1) * (7C1/11C1) = 41/77There is a city where all 100% votes are registered. Among this 60% votes for Congress and 40% votes for BJP. Ram, gets 75% of congress votes and 8% of BJP votes. How many votes did Ram get?a) 48.2 %b) 56.6 %c) 42.8 %d) 64.4 %Answer: a) 48.2 %Solution:Let the total number if votes = 100. So Ram gets,75% of 60 = 60 * 0.75 = 45 votes8% of 40 = 40 * 0.08 = 3.2 votesThus total number of votes that Ram gets = 48.2 %John is faster than Peter. John and Peter each walk 24 km. Sum of the speeds of John and Peter is 7 km/h. Sum of time taken by them is 14 hours. Find John’s speed.a) 4 km/hb) 5 km/hc) 3 km/hd) 7 km/hAnswer: a) 4 km/hSolution:We know that John’s speed is greater than Peter’s speed and the sum of there speed is 7.So the combinations are = (6, 1), (5, 2), (4, 3)Now checking from the options if John’s speed is equal to 4, then Peter’s speed is 3,or, the time taken by them = 24/4 + 24/3 = 14 hours.If f(x) = 2x + 2 what is the value of f(f(3))?a) 8b) 64c) 16d) 18Answer: d) 18Solution;f(f(3)) = 2(f(3)) + 2=> 2(2(3) + 2) + 2=> 16 + 2 = 18" }, { "code": null, "e": 31238, "s": 30766, "text": "All even numbers from 2 to 98 inclusive the both, are to be multiplied together. What is the unit digit of the product?a) 2b) 0c) 6d) 4Answer: b) 0Solution:Let us look at the sequence of the multiplications,2 * 4 * 6 * 8 *10* 12 * 14 * 16 * 18 *...* 98If we look closely we will find that the units place of every number forms a sequence of 2, 4, 6 ,8 and 0 multiplying to a number whose units place is always 0 and in all we get 0. So the unit digit of final number = 0." }, { "code": null, "e": 31251, "s": 31238, "text": "Answer: b) 0" }, { "code": null, "e": 31576, "s": 31251, "text": "Solution:Let us look at the sequence of the multiplications,2 * 4 * 6 * 8 *10* 12 * 14 * 16 * 18 *...* 98If we look closely we will find that the units place of every number forms a sequence of 2, 4, 6 ,8 and 0 multiplying to a number whose units place is always 0 and in all we get 0. So the unit digit of final number = 0." }, { "code": null, "e": 31993, "s": 31576, "text": "10 programmers are able to type 10 lines in 10 minutes. How many programmer are required to type 60 lines in 60 minutes?a) 10b) 16c) 60d) None of the aboveAnswer: a) 10Solution:This is a simple question of logical reasoning. If 10 programmers can type 10 lines of code in 10 minutes then to type 60 lines of code, in 60 minutes, the same 10 coders will be required, since the lines of code and time are in proportion" }, { "code": null, "e": 32007, "s": 31993, "text": "Answer: a) 10" }, { "code": null, "e": 32256, "s": 32007, "text": "Solution:This is a simple question of logical reasoning. If 10 programmers can type 10 lines of code in 10 minutes then to type 60 lines of code, in 60 minutes, the same 10 coders will be required, since the lines of code and time are in proportion" }, { "code": null, "e": 32733, "s": 32256, "text": "Anil works for 8 straight days and rest on the 9th day. If he starts his work on Monday, then on which day he gets his 12th rest day?a) Thursdayb) Tuesdayc) Wednesdayd) FridayAnswer: c) WednesdaySolution:Anil works for 8 days and rests on 9th day. In total 9 days are to be processed 12 times = 12 * 9 = 108.If we calculate according to the week, we get 108 / 7 = remaining 3 days. So if Anil starts working on Monday, he will rest on third day of the week which is Wednesday." }, { "code": null, "e": 32754, "s": 32733, "text": "Answer: c) Wednesday" }, { "code": null, "e": 33036, "s": 32754, "text": "Solution:Anil works for 8 days and rests on 9th day. In total 9 days are to be processed 12 times = 12 * 9 = 108.If we calculate according to the week, we get 108 / 7 = remaining 3 days. So if Anil starts working on Monday, he will rest on third day of the week which is Wednesday." }, { "code": null, "e": 34134, "s": 33036, "text": "Overfishing is a serious environmental issue. The scientists were able to determine that if the net of a trawler has a mesh size of ‘x’ cm (a square mesh), then the percentage of fish entering the net is caught in the net is expressed in form of the quadratic equation, 100 – 0.04x^2- 0.24x. For example, if the mesh size is zero, 100% of the fish that enter the net will be caught. A trawler with a net with a square mesh, that was suspect of using an illegal size net, dropped its net to the ocean floor near the Lakshadweep and the coast guard, arrested the crew. It was later looked at the size of the fish caught and estimated that for the net used by the trawler, at least 97.8% of the fish entering the net would be caught. What is the maximum value of x for the net used by the trawler?a) 7b) 4.5c) 6d) 5Answer: d) 5Solution:According to the question,for few values of x, the total fish caught is 97.8%. So=> 100 – 0.04x^2- 0.24x = 97.8=> 0.04x^2 + 0.24x = 2.2=> 4x^2+ 24x = 220=> x^2+ 6x – 55 = 0Solving, we get x = 5 and -11So, the value of x = 5 has to be positive and hence the answer." }, { "code": null, "e": 34147, "s": 34134, "text": "Answer: d) 5" }, { "code": null, "e": 34421, "s": 34147, "text": "Solution:According to the question,for few values of x, the total fish caught is 97.8%. So=> 100 – 0.04x^2- 0.24x = 97.8=> 0.04x^2 + 0.24x = 2.2=> 4x^2+ 24x = 220=> x^2+ 6x – 55 = 0Solving, we get x = 5 and -11So, the value of x = 5 has to be positive and hence the answer." }, { "code": null, "e": 34742, "s": 34421, "text": "The rejection rate for Audi production was 4 per cent, for Mercedes it was 8 per cent and for the 2 cars combined it was 7 per cent. What was the ratio of Audi production?a) 4/1b) 2/1c) 3/1d) 7/1Answer: c) 3/1Solution:Using the simple weighted average formula we get,(4x + 8y)/(x+y) = 7or, 4x + 8y = 7x + 7yor, a/b = 3/1" }, { "code": null, "e": 34757, "s": 34742, "text": "Answer: c) 3/1" }, { "code": null, "e": 34869, "s": 34757, "text": "Solution:Using the simple weighted average formula we get,(4x + 8y)/(x+y) = 7or, 4x + 8y = 7x + 7yor, a/b = 3/1" }, { "code": null, "e": 35367, "s": 34869, "text": "A team of 11 is needed to be formed who are to be selected from 5 men and 11 women, with the restriction of selecting not more than 3 men. In how many ways can the selection be done?a) 1121b) 1565c) 1243d) 2256Answer: d) 2256Solution:Selecting 0 men and 11 women = 5C0 * 11C11 = 1Selecting 1 men and 10 women = 5C1 * 11C10 = 55Selecting 2 men and 9 women = 5C2 * 11C9 = 10 * 55 = 550Selecting 3 men and 8 women = 5C3 * 11C8 = 10 * 165 = 1650So total number of ways = 1650 + 550 + 55 + 1 = 2256 way" }, { "code": null, "e": 35383, "s": 35367, "text": "Answer: d) 2256" }, { "code": null, "e": 35656, "s": 35383, "text": "Solution:Selecting 0 men and 11 women = 5C0 * 11C11 = 1Selecting 1 men and 10 women = 5C1 * 11C10 = 55Selecting 2 men and 9 women = 5C2 * 11C9 = 10 * 55 = 550Selecting 3 men and 8 women = 5C3 * 11C8 = 10 * 165 = 1650So total number of ways = 1650 + 550 + 55 + 1 = 2256 way" }, { "code": null, "e": 36205, "s": 35656, "text": "There are two bags containing white and black marbles. In the first bag there are 8 white marbles and 6 black marbles and in the second bag, there are 4 white marbles and 7 black marbles. One marble is drawn at random from any of these two bags. Find the probability of this marble being black.a) 7/54b) 7/154c) 41/77d) 22/77Answer: c) 41/77Solution:Probability of drawing a black ball from the first bag is = 6C1 / 14C1Probability of drawing a black ball from the second bag is = 7C1 / 11C1Total probability = 1/2 * (6C1/14C1) * (7C1/11C1) = 41/77" }, { "code": null, "e": 36222, "s": 36205, "text": "Answer: c) 41/77" }, { "code": null, "e": 36430, "s": 36222, "text": "Solution:Probability of drawing a black ball from the first bag is = 6C1 / 14C1Probability of drawing a black ball from the second bag is = 7C1 / 11C1Total probability = 1/2 * (6C1/14C1) * (7C1/11C1) = 41/77" }, { "code": null, "e": 36845, "s": 36430, "text": "There is a city where all 100% votes are registered. Among this 60% votes for Congress and 40% votes for BJP. Ram, gets 75% of congress votes and 8% of BJP votes. How many votes did Ram get?a) 48.2 %b) 56.6 %c) 42.8 %d) 64.4 %Answer: a) 48.2 %Solution:Let the total number if votes = 100. So Ram gets,75% of 60 = 60 * 0.75 = 45 votes8% of 40 = 40 * 0.08 = 3.2 votesThus total number of votes that Ram gets = 48.2 %" }, { "code": null, "e": 36863, "s": 36845, "text": "Answer: a) 48.2 %" }, { "code": null, "e": 37035, "s": 36863, "text": "Solution:Let the total number if votes = 100. So Ram gets,75% of 60 = 60 * 0.75 = 45 votes8% of 40 = 40 * 0.08 = 3.2 votesThus total number of votes that Ram gets = 48.2 %" }, { "code": null, "e": 37534, "s": 37035, "text": "John is faster than Peter. John and Peter each walk 24 km. Sum of the speeds of John and Peter is 7 km/h. Sum of time taken by them is 14 hours. Find John’s speed.a) 4 km/hb) 5 km/hc) 3 km/hd) 7 km/hAnswer: a) 4 km/hSolution:We know that John’s speed is greater than Peter’s speed and the sum of there speed is 7.So the combinations are = (6, 1), (5, 2), (4, 3)Now checking from the options if John’s speed is equal to 4, then Peter’s speed is 3,or, the time taken by them = 24/4 + 24/3 = 14 hours." }, { "code": null, "e": 37552, "s": 37534, "text": "Answer: a) 4 km/h" }, { "code": null, "e": 37835, "s": 37552, "text": "Solution:We know that John’s speed is greater than Peter’s speed and the sum of there speed is 7.So the combinations are = (6, 1), (5, 2), (4, 3)Now checking from the options if John’s speed is equal to 4, then Peter’s speed is 3,or, the time taken by them = 24/4 + 24/3 = 14 hours." }, { "code": null, "e": 37976, "s": 37835, "text": "If f(x) = 2x + 2 what is the value of f(f(3))?a) 8b) 64c) 16d) 18Answer: d) 18Solution;f(f(3)) = 2(f(3)) + 2=> 2(2(3) + 2) + 2=> 16 + 2 = 18" }, { "code": null, "e": 37990, "s": 37976, "text": "Answer: d) 18" }, { "code": null, "e": 38053, "s": 37990, "text": "Solution;f(f(3)) = 2(f(3)) + 2=> 2(2(3) + 2) + 2=> 16 + 2 = 18" }, { "code": null, "e": 38065, "s": 38053, "text": "RupalRaturi" }, { "code": null, "e": 38087, "s": 38065, "text": "interview-preparation" }, { "code": null, "e": 38109, "s": 38087, "text": "placement preparation" }, { "code": null, "e": 38113, "s": 38109, "text": "TCS" }, { "code": null, "e": 38124, "s": 38113, "text": "Placements" }, { "code": null, "e": 38128, "s": 38124, "text": "TCS" }, { "code": null, "e": 38226, "s": 38128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38278, "s": 38226, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 38309, "s": 38278, "text": "Codenation Recruitment Process" }, { "code": null, "e": 38367, "s": 38309, "text": "Minimum changes required to make all Array elements Prime" }, { "code": null, "e": 38395, "s": 38367, "text": "Permutation and Combination" }, { "code": null, "e": 38421, "s": 38395, "text": "Progressions (AP, GP, HP)" }, { "code": null, "e": 38443, "s": 38421, "text": "Interview Preparation" }, { "code": null, "e": 38487, "s": 38443, "text": "Puzzle | 50 red marbles and 50 blue marbles" }, { "code": null, "e": 38545, "s": 38487, "text": "C program to reverse the content of the file and print it" }, { "code": null, "e": 38565, "s": 38545, "text": "Time Speed Distance" } ]
Python | Output Formatting - GeeksforGeeks
19 Feb, 2022 There are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values. There are several ways to format output. To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. The str. format() method of strings helps a user create a fancier output Users can do all the string handling by using string slicing and concatenation operations to create any layout that the users want. The string type has some methods that perform useful operations for padding strings to a given column width. Formatting output using String modulo operator(%) : The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format as in C language strings to be applied to the right argument. In Python, there is no printf() function but the functionality of the ancient printf is contained in Python. To this purpose, the modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is often called a string modulo (or sometimes even called modulus) operator. The string modulo operator ( % ) is still available in Python(3.x) and is widely used. But nowadays the old style of formatting is removed from the language. Python3 # Python program showing how to use# string modulo operator(%) to print# fancier output # print integer and float valueprint("Geeks : %2d, Portal : %5.2f" % (1, 05.333)) # print integer valueprint("Total students : %3d, Boys : %2d" % (240, 120)) # print octal valueprint("%7.3o" % (25)) # print exponential valueprint("%10.3E" % (356.08977)) Output : Geeks : 1, Portal : 5.33 Total students : 240, Boys : 120 031 3.561E+02 There are two of those in our example: “%2d” and “%5.2f”. The general syntax for a format placeholder is: %[flags][width][.precision]type Let’s take a look at the placeholders in our example. The first placeholder “%2d” is used for the first component of our tuple, i.e. the integer 1. The number will be printed with 2 characters. As 1 consists only of one digit, the output is padded with 1 leading blanks. The second one “%5.2f” is a format description for a float number. Like other placeholders, it is introduced with the % character. This is followed by the total number of digits the string should contain. This number includes the decimal point and all the digits, i.e. before and after the decimal point. Our float number 05.333 has to be formatted with 5 characters. The decimal part of the number or the precision is set to 2, i.e. the number following the “.” in our placeholder. Finally, the last character “f” of our placeholder stands for “float”. Formatting output using the format method : The format() method was added in Python(2.6). The format method of strings requires more manual effort. Users use {} to mark where a variable will be substituted and can provide detailed formatting directives, but the user also needs to provide the information to be formatted. This method lets us concatenate elements within an output through positional formatting. For Example – Code 1: Python3 # Python program showing# use of format() method # using format() methodprint('I love {} for "{}!"'.format('Geeks', 'Geeks')) # using format() method and referring# a position of the objectprint('{0} and {1}'.format('Geeks', 'Portal')) print('{1} and {0}'.format('Geeks', 'Portal')) # the above formatting can also be done by using f-Strings# Although, this features work only with python 3.6 or above. print(f"I love {'Geeks'} for \"{'Geeks'}!\"") # using format() method and referring# a position of the objectprint(f"{'Geeks'} and {'Portal'}") Output : I love Geeks for "Geeks!" Geeks and Portal Portal and Geeks The brackets and characters within them (called format fields) are replaced with the objects passed into the format() method. A number in the brackets can be used to refer to the position of the object passed into the format() method. Code 2: Python3 # Python program showing# a use of format() method # combining positional and keyword argumentsprint('Number one portal is {0}, {1}, and {other}.' .format('Geeks', 'For', other ='Geeks')) # using format() method with numberprint("Geeks :{0:2d}, Portal :{1:8.2f}". format(12, 00.546)) # Changing positional argumentprint("Second argument: {1:3d}, first one: {0:7.2f}". format(47.42, 11)) print("Geeks: {a:5d}, Portal: {p:8.2f}". format(a = 453, p = 59.058)) Output: Number one portal is Geeks, For, and Geeks. Geeks :12, Portal : 0.55 Second argument: 11, first one: 47.42 Geeks: 453, Portal: 59.06 The following diagram with an example usage depicts how the format method works for positional parameters: Code 3: Python3 # Python program to# show format () is# used in dictionary tab = {'geeks': 4127, 'for': 4098, 'geek': 8637678} # using format() in dictionaryprint('Geeks: {0[geeks]:d}; For: {0[for]:d}; ' 'Geeks: {0[geek]:d}'.format(tab)) data = dict(fun ="GeeksForGeeks", adj ="Portal") # using format() in dictionaryprint("I love {fun} computer {adj}".format(**data)) Output: Geeks: 4127; For: 4098; Geeks: 8637678 I love GeeksForGeeks computer Portal Formatting output using the String method : This output is formatted by using string slicing and concatenation operations. The string type has some methods that help in formatting output in a fancier way. Some methods which help in formatting an output are str.rjust(), str.rjust(), and str.centre() Python3 # Python program to# format a output using# string() method cstr = "I love geeksforgeeks" # Printing the center aligned # string with fillchrprint ("Center aligned string with fillchr: ")print (cstr.center(40, '#')) # Printing the left aligned # string with "-" padding print ("The left aligned string is : ")print (cstr.ljust(40, '-')) # Printing the right aligned string# with "-" padding print ("The right aligned string is : ")print (cstr.rjust(40, '-')) Output: Center aligned string with fillchr: ##########I love geeksforgeeks########## The left aligned string is : I love geeksforgeeks-------------------- The right aligned string is : --------------------I love geeksforgeeks AshisKumarSahu shreyasbs kumarv456 adnanirshad158 punamsingh628700 billsker souvikmondal01 python-input-output Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42675, "s": 42647, "text": "\n19 Feb, 2022" }, { "code": null, "e": 43002, "s": 42675, "text": "There are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values. There are several ways to format output. " }, { "code": null, "e": 43123, "s": 43002, "text": "To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark." }, { "code": null, "e": 43196, "s": 43123, "text": "The str. format() method of strings helps a user create a fancier output" }, { "code": null, "e": 43437, "s": 43196, "text": "Users can do all the string handling by using string slicing and concatenation operations to create any layout that the users want. The string type has some methods that perform useful operations for padding strings to a given column width." }, { "code": null, "e": 43976, "s": 43437, "text": "Formatting output using String modulo operator(%) : The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format as in C language strings to be applied to the right argument. In Python, there is no printf() function but the functionality of the ancient printf is contained in Python. To this purpose, the modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is often called a string modulo (or sometimes even called modulus) operator. " }, { "code": null, "e": 44135, "s": 43976, "text": "The string modulo operator ( % ) is still available in Python(3.x) and is widely used. But nowadays the old style of formatting is removed from the language. " }, { "code": null, "e": 44143, "s": 44135, "text": "Python3" }, { "code": "# Python program showing how to use# string modulo operator(%) to print# fancier output # print integer and float valueprint(\"Geeks : %2d, Portal : %5.2f\" % (1, 05.333)) # print integer valueprint(\"Total students : %3d, Boys : %2d\" % (240, 120)) # print octal valueprint(\"%7.3o\" % (25)) # print exponential valueprint(\"%10.3E\" % (356.08977))", "e": 44485, "s": 44143, "text": null }, { "code": null, "e": 44495, "s": 44485, "text": "Output : " }, { "code": null, "e": 44572, "s": 44495, "text": "Geeks : 1, Portal : 5.33\nTotal students : 240, Boys : 120\n 031\n3.561E+02" }, { "code": null, "e": 44679, "s": 44572, "text": "There are two of those in our example: “%2d” and “%5.2f”. The general syntax for a format placeholder is: " }, { "code": null, "e": 44713, "s": 44679, "text": " %[flags][width][.precision]type " }, { "code": null, "e": 44769, "s": 44713, "text": "Let’s take a look at the placeholders in our example. " }, { "code": null, "e": 44986, "s": 44769, "text": "The first placeholder “%2d” is used for the first component of our tuple, i.e. the integer 1. The number will be printed with 2 characters. As 1 consists only of one digit, the output is padded with 1 leading blanks." }, { "code": null, "e": 45291, "s": 44986, "text": "The second one “%5.2f” is a format description for a float number. Like other placeholders, it is introduced with the % character. This is followed by the total number of digits the string should contain. This number includes the decimal point and all the digits, i.e. before and after the decimal point." }, { "code": null, "e": 45540, "s": 45291, "text": "Our float number 05.333 has to be formatted with 5 characters. The decimal part of the number or the precision is set to 2, i.e. the number following the “.” in our placeholder. Finally, the last character “f” of our placeholder stands for “float”." }, { "code": null, "e": 45966, "s": 45540, "text": "Formatting output using the format method : The format() method was added in Python(2.6). The format method of strings requires more manual effort. Users use {} to mark where a variable will be substituted and can provide detailed formatting directives, but the user also needs to provide the information to be formatted. This method lets us concatenate elements within an output through positional formatting. For Example – " }, { "code": null, "e": 45976, "s": 45966, "text": "Code 1: " }, { "code": null, "e": 45984, "s": 45976, "text": "Python3" }, { "code": "# Python program showing# use of format() method # using format() methodprint('I love {} for \"{}!\"'.format('Geeks', 'Geeks')) # using format() method and referring# a position of the objectprint('{0} and {1}'.format('Geeks', 'Portal')) print('{1} and {0}'.format('Geeks', 'Portal')) # the above formatting can also be done by using f-Strings# Although, this features work only with python 3.6 or above. print(f\"I love {'Geeks'} for \\\"{'Geeks'}!\\\"\") # using format() method and referring# a position of the objectprint(f\"{'Geeks'} and {'Portal'}\")", "e": 46532, "s": 45984, "text": null }, { "code": null, "e": 46542, "s": 46532, "text": "Output : " }, { "code": null, "e": 46602, "s": 46542, "text": "I love Geeks for \"Geeks!\"\nGeeks and Portal\nPortal and Geeks" }, { "code": null, "e": 46848, "s": 46602, "text": "The brackets and characters within them (called format fields) are replaced with the objects passed into the format() method. A number in the brackets can be used to refer to the position of the object passed into the format() method. Code 2: " }, { "code": null, "e": 46856, "s": 46848, "text": "Python3" }, { "code": "# Python program showing# a use of format() method # combining positional and keyword argumentsprint('Number one portal is {0}, {1}, and {other}.' .format('Geeks', 'For', other ='Geeks')) # using format() method with numberprint(\"Geeks :{0:2d}, Portal :{1:8.2f}\". format(12, 00.546)) # Changing positional argumentprint(\"Second argument: {1:3d}, first one: {0:7.2f}\". format(47.42, 11)) print(\"Geeks: {a:5d}, Portal: {p:8.2f}\". format(a = 453, p = 59.058))", "e": 47332, "s": 46856, "text": null }, { "code": null, "e": 47341, "s": 47332, "text": "Output: " }, { "code": null, "e": 47485, "s": 47341, "text": "Number one portal is Geeks, For, and Geeks.\nGeeks :12, Portal : 0.55\nSecond argument: 11, first one: 47.42\nGeeks: 453, Portal: 59.06" }, { "code": null, "e": 47593, "s": 47485, "text": "The following diagram with an example usage depicts how the format method works for positional parameters: " }, { "code": null, "e": 47604, "s": 47593, "text": " Code 3: " }, { "code": null, "e": 47612, "s": 47604, "text": "Python3" }, { "code": "# Python program to# show format () is# used in dictionary tab = {'geeks': 4127, 'for': 4098, 'geek': 8637678} # using format() in dictionaryprint('Geeks: {0[geeks]:d}; For: {0[for]:d}; ' 'Geeks: {0[geek]:d}'.format(tab)) data = dict(fun =\"GeeksForGeeks\", adj =\"Portal\") # using format() in dictionaryprint(\"I love {fun} computer {adj}\".format(**data))", "e": 47968, "s": 47612, "text": null }, { "code": null, "e": 47977, "s": 47968, "text": "Output: " }, { "code": null, "e": 48053, "s": 47977, "text": "Geeks: 4127; For: 4098; Geeks: 8637678\nI love GeeksForGeeks computer Portal" }, { "code": null, "e": 48353, "s": 48053, "text": "Formatting output using the String method : This output is formatted by using string slicing and concatenation operations. The string type has some methods that help in formatting output in a fancier way. Some methods which help in formatting an output are str.rjust(), str.rjust(), and str.centre()" }, { "code": null, "e": 48361, "s": 48353, "text": "Python3" }, { "code": "# Python program to# format a output using# string() method cstr = \"I love geeksforgeeks\" # Printing the center aligned # string with fillchrprint (\"Center aligned string with fillchr: \")print (cstr.center(40, '#')) # Printing the left aligned # string with \"-\" padding print (\"The left aligned string is : \")print (cstr.ljust(40, '-')) # Printing the right aligned string# with \"-\" padding print (\"The right aligned string is : \")print (cstr.rjust(40, '-'))", "e": 48822, "s": 48361, "text": null }, { "code": null, "e": 48831, "s": 48822, "text": "Output: " }, { "code": null, "e": 49054, "s": 48831, "text": "Center aligned string with fillchr: \n##########I love geeksforgeeks##########\n\nThe left aligned string is : \nI love geeksforgeeks--------------------\n\nThe right aligned string is : \n--------------------I love geeksforgeeks" }, { "code": null, "e": 49071, "s": 49056, "text": "AshisKumarSahu" }, { "code": null, "e": 49081, "s": 49071, "text": "shreyasbs" }, { "code": null, "e": 49091, "s": 49081, "text": "kumarv456" }, { "code": null, "e": 49106, "s": 49091, "text": "adnanirshad158" }, { "code": null, "e": 49123, "s": 49106, "text": "punamsingh628700" }, { "code": null, "e": 49132, "s": 49123, "text": "billsker" }, { "code": null, "e": 49147, "s": 49132, "text": "souvikmondal01" }, { "code": null, "e": 49167, "s": 49147, "text": "python-input-output" }, { "code": null, "e": 49174, "s": 49167, "text": "Python" }, { "code": null, "e": 49272, "s": 49174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49300, "s": 49272, "text": "Read JSON file using Python" }, { "code": null, "e": 49350, "s": 49300, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 49372, "s": 49350, "text": "Python map() function" }, { "code": null, "e": 49416, "s": 49372, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 49451, "s": 49416, "text": "Read a file line by line in Python" }, { "code": null, "e": 49483, "s": 49451, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 49505, "s": 49483, "text": "Enumerate() in Python" }, { "code": null, "e": 49547, "s": 49505, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 49577, "s": 49547, "text": "Iterate over a list in Python" } ]
How to display specific properties from Get-Service output in PowerShell?
To display the other properties of the services than the default ones (which are supported by Get-Member), you need to pipeline the Select-Object (alias Select) command. For example, in the below command we will display theService name, start type and status of the service. Get-Service | Select-Object Name, StartType, Status Name StartType Status ---- --------- ------ AarSvc_158379 Manual Stopped AdobeARMservice Automatic Running AdobeFlashPlayerUpdateSvc Manual Stopped AJRouter Manual Stopped ALG Manual Stopped AppIDSvc Manual Stopped Appinfo Manual Running AppMgmt Manual Stopped AppReadiness Manual Stopped AppVClient Disabled Stopped AppXSvc Manual Stopped AssignedAccessManagerSvc Manual Stopped AudioEndpointBuilder Automatic Running Audiosrv Automatic Running autotimesvc Manual Stopped AVP20.0 Automatic Running AxInstSV Manual Stopped BcastDVRUserService_158379 Manual Stopped BDESVC Manual Stopped BFE Automatic Running BITS Automatic Running Bluetooth Device Monitor Automatic Running Bluetooth OBEX Service Automatic Running BluetoothUserService_158379 Manual Stopped BrokerInfrastructure Automatic Running You can also sort the properties of the object by Sort-Object. In the below example, services are sorted by their start type. Get-Service | Select Name,Status,StartType | Sort-Object StartType Audiosrv Running Automatic CDPUserSvc_158379 Running Automatic BrokerInfrastructure Running Automatic DellClientManagementService Running Automatic Bluetooth Device Monitor Running Automatic BFE Running Automatic BITS Running Automatic AdobeARMservice Running Automatic ZeroConfigService Running Automatic DeviceAssociationService Running Automatic Bluetooth OBEX Service Running Automatic Dell Hardware Support Running Automatic DDVRulesProcessor Running Automatic svsvc Stopped Manual WPDBusEnum Stopped Manual stisvc Stopped Manual StorSvc Running Manual vmickvpexchange Stopped Manual swprv Stopped Manual SstpSvc Running Manual workfolderssvc Stopped Manual SSDPSRV Running Manual WpcMonSvc Stopped Manual SNMPTRAP Stopped Manual spectrum Stopped Manual StateRepository Running Manual SDRSVC Stopped Manual XblAuthManager Stopped Manual
[ { "code": null, "e": 1337, "s": 1062, "text": "To display the other properties of the services than the default ones (which are supported by Get-Member), you need to pipeline the Select-Object (alias Select) command. For example, in the below command we will display theService name, start type and status of the service." }, { "code": null, "e": 1389, "s": 1337, "text": "Get-Service | Select-Object Name, StartType, Status" }, { "code": null, "e": 3360, "s": 1389, "text": "Name StartType Status\n---- --------- ------\nAarSvc_158379 Manual Stopped\nAdobeARMservice Automatic Running\nAdobeFlashPlayerUpdateSvc Manual Stopped\nAJRouter Manual Stopped\nALG Manual Stopped\nAppIDSvc Manual Stopped\nAppinfo Manual Running\nAppMgmt Manual Stopped\nAppReadiness Manual Stopped\nAppVClient Disabled Stopped\nAppXSvc Manual Stopped\nAssignedAccessManagerSvc Manual Stopped\nAudioEndpointBuilder Automatic Running\nAudiosrv Automatic Running\nautotimesvc Manual Stopped\nAVP20.0 Automatic Running\nAxInstSV Manual Stopped\nBcastDVRUserService_158379 Manual Stopped\nBDESVC Manual Stopped\nBFE Automatic Running\nBITS Automatic Running\nBluetooth Device Monitor Automatic Running\nBluetooth OBEX Service Automatic Running\nBluetoothUserService_158379 Manual Stopped\nBrokerInfrastructure Automatic Running" }, { "code": null, "e": 3486, "s": 3360, "text": "You can also sort the properties of the object by Sort-Object. In the below example, services are sorted by their start type." }, { "code": null, "e": 3554, "s": 3486, "text": "Get-Service | Select Name,Status,StartType | Sort-Object StartType\n" }, { "code": null, "e": 5598, "s": 3554, "text": "Audiosrv Running Automatic\nCDPUserSvc_158379 Running Automatic\nBrokerInfrastructure Running Automatic\nDellClientManagementService Running Automatic\nBluetooth Device Monitor Running Automatic\nBFE Running Automatic\nBITS Running Automatic\nAdobeARMservice Running Automatic\nZeroConfigService Running Automatic\nDeviceAssociationService Running Automatic\nBluetooth OBEX Service Running Automatic\nDell Hardware Support Running Automatic\nDDVRulesProcessor Running Automatic\nsvsvc Stopped Manual\nWPDBusEnum Stopped Manual\nstisvc Stopped Manual\nStorSvc Running Manual\nvmickvpexchange Stopped Manual\nswprv Stopped Manual\nSstpSvc Running Manual\nworkfolderssvc Stopped Manual\nSSDPSRV Running Manual\nWpcMonSvc Stopped Manual\nSNMPTRAP Stopped Manual\nspectrum Stopped Manual\nStateRepository Running Manual\nSDRSVC Stopped Manual\nXblAuthManager Stopped Manual" } ]
How to prevent modification of object in JavaScript ?.
ECMAScript 5 has introduced several methods to prevent modification of object. Those preventive measures ensures that no one, accidentally or otherwise change functionality of object. In this level, one cannot add any new properties or methods but can access existing properties or methods. Here there is an ability to delete the respective object. Object.preventExtensions() is the method used to accomplish this task. It prevents any new properties from ever being added to the object. Live Demo <html> <body> <script> var object1 = { prop1: 1 }; Object.preventExtensions(object1); delete object1.prop1 // value got deleted try { Object.defineProperty(object1, 'prop2', { value: 2 }); } catch (err) { document.write(err); } document.write("</br>"); document.write(object1.prop1); </script> </body> </html> TypeError: Cannot define property prop2, object is not extensible undefined // deleted so undefined It is same as preventing extensions, in addition it doesn't allow to delete existing properties or methods. To accomplish this task Object.seal() method is used. Live Demo <html> <body> <script> var object1 = { prop1: 1 }; Object.seal(object1); object1.prop1 = 2; // value got changed delete object1.prop1; try { Object.defineProperty(object1, 'prop2', { value: 2 }); } catch (err) { document.write(err); } document.write("</br>"); document.write(object1.prop1); // it gives value as 2 because of seal. </script> </body> </html> TypeError: Cannot define property prop2, object is not extensible 2 // because of seal the value can't be deleated but got updated In addition to seal's functionality, freeze doesn't allow even to access the existing properties. To freeze an object we use Object.freeze() method. It can also make an object immutable. Live Demo <html> <body> <script> var object1 = { prop1: 1 }; Object.freeze(object1); object1.prop1 = 2; // value got updated delete object1.prop1; // value got deleted try { Object.defineProperty(object1, 'prop2', { value: 2 }); } catch (err) { document.write(err); } document.write("</br>"); document.write(object1.prop1); // it gives 1 as output despite value updated to 2 </script> </body> </html> TypeError: Cannot define property prop2, object is not extensible 1 // because of freeze the value won't get delete and won't get update.
[ { "code": null, "e": 1246, "s": 1062, "text": "ECMAScript 5 has introduced several methods to prevent modification of object. Those preventive measures ensures that no one, accidentally or otherwise change functionality of object." }, { "code": null, "e": 1550, "s": 1246, "text": "In this level, one cannot add any new properties or methods but can access existing properties or methods. Here there is an ability to delete the respective object. Object.preventExtensions() is the method used to accomplish this task. It prevents any new properties from ever being added to the object." }, { "code": null, "e": 1560, "s": 1550, "text": "Live Demo" }, { "code": null, "e": 1921, "s": 1560, "text": "<html>\n<body>\n<script>\n var object1 = {\n prop1: 1\n };\n Object.preventExtensions(object1);\n delete object1.prop1 // value got deleted\n try {\n Object.defineProperty(object1, 'prop2', {\n value: 2\n });\n } catch (err) {\n document.write(err);\n }\n document.write(\"</br>\");\n document.write(object1.prop1);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2021, "s": 1921, "text": "TypeError: Cannot define property prop2, object is not extensible\nundefined // deleted so undefined" }, { "code": null, "e": 2183, "s": 2021, "text": "It is same as preventing extensions, in addition it doesn't allow to delete existing properties or methods. To accomplish this task Object.seal() method is used." }, { "code": null, "e": 2193, "s": 2183, "text": "Live Demo" }, { "code": null, "e": 2623, "s": 2193, "text": "<html>\n<body>\n<script>\n var object1 = {\n prop1: 1\n };\n Object.seal(object1);\n object1.prop1 = 2; // value got changed\n delete object1.prop1;\n try {\n Object.defineProperty(object1, 'prop2', {\n value: 2\n });\n } catch (err) {\n document.write(err);\n }\n document.write(\"</br>\");\n document.write(object1.prop1); // it gives value as 2 because of seal.\n</script>\n</body>\n</html>" }, { "code": null, "e": 2755, "s": 2623, "text": "TypeError: Cannot define property prop2, object is not extensible\n2 // because of seal the value can't be deleated but got updated" }, { "code": null, "e": 2942, "s": 2755, "text": "In addition to seal's functionality, freeze doesn't allow even to access the existing properties. To freeze an object we use Object.freeze() method. It can also make an object immutable." }, { "code": null, "e": 2952, "s": 2942, "text": "Live Demo" }, { "code": null, "e": 3418, "s": 2952, "text": "<html>\n<body>\n<script>\n var object1 = {\n prop1: 1\n };\n Object.freeze(object1);\n object1.prop1 = 2; // value got updated\n delete object1.prop1; // value got deleted\n try {\n Object.defineProperty(object1, 'prop2', {\n value: 2\n });\n } catch (err) {\n document.write(err);\n }\n document.write(\"</br>\");\n document.write(object1.prop1); // it gives 1 as output despite value updated to 2\n</script>\n</body>\n</html>" }, { "code": null, "e": 3557, "s": 3418, "text": "TypeError: Cannot define property prop2, object is not extensible\n1 // because of freeze the value won't get delete and won't get update. " } ]
How to Use FFmpeg in Android with Example? - GeeksforGeeks
08 Oct, 2021 FFmpeg, short for Fast-forward MPEG, is a free and open-source multimedia framework, which is able to decode, encode, transcode, mux, demux, stream, filter and play fairly all kinds of multimedia files that have been created to date. It also supports some of the eldest formats. FFmpeg compiles and runs, across various operating systems like Linux, Mac OS X, Microsoft Windows, the BSDs, Solaris, etc. among a large range of build environments, machine architectures, and configurations. Programming languages used in FFmpeg are C and Assembly language. We can do many fun kinds of stuff using Ffmpeg like, Video Compress, Audio Compress, Trim Video, Rotate Video, Crop Video, Adding filters to videos, Reverse a Video, Creating fast and slow-motion video, Fade in fade out, Merge audio and video, Creating a video from images, Convert video from one format into another, Extract Picture from Video or Sound from Video, Gifs overlay, and many more. FFmpeg is part of the workflow of hundreds of other media-related software projects, and it’s often used behind the scenes. Also, It is an internal part of software such as VLC media player, YouTube, Plex, iTunes, Shortcut, Blender, Kodi, HandBrake, it handles video and audio playback in Google Chrome, and Linux version of Firefox. FFmpeg comprises an enormous set-up of libraries and projects for dealing with video, sound, and other multimedia files and streams. libavutil is a utility library to help versatile media programming. It contains portable string functions, arbitrary number generators, extra arithmetic capacities, data structures, cryptography, and core multimedia utilities. libavcodec is a library that provides encoders and decoders for video/audio codecs, subtitle streams, and several bitstream channels. libavformat is a library that provides multiplexing and demultiplexing framework for video/audio codecs, subtitle streams libavdevice is a library containing I/O devices for getting from and delivering to numerous multimedia I/O programming systems, including Video4Linux, ALSA, and VfW. libavfilter library provides a media filtering framework that contains several filters and sinks. libswscale library performs exceptionally enhanced picture scaling and pixel format transformation tasks. libswresample is a library that performs highly optimized but a lossy change in audio rate, change in channel layout, for example from stereo to mono, and sample format conversion operations. Android doesn’t have efficient and robust APIs for multimedia which could provide functionalities like FFmpeg. The only API which android has is MediaCodec API, but it is faster than FFmpeg because it uses the device hardware for video processing. Prerequisites: Before we start, we need to set up an environment to run our FFmpeg commands. There are two options to do so: By building our own library By using any compiled source provided by the community. There are many libraries that can be used to perform FFmpeg operations in Android. For example,WritingMindsBravobittanersener/mobile-ffmpegyangjie10930/EpMedia: There are many inbuilt functions present in this library from which you can clip, crop, rotate, add a logo, add a custom filter, merge different videos. WritingMinds Bravobit tanersener/mobile-ffmpeg yangjie10930/EpMedia: There are many inbuilt functions present in this library from which you can clip, crop, rotate, add a logo, add a custom filter, merge different videos. Although it is highly recommended to build your library, because that will reduce your apk size, you can add a third-party library and can update the library with time as you want. But, this process is very time consuming and requires extra skills. So, as a beginner, you can use some above-mentioned libraries and if you face some issue you can raise that issue on their respective GitHub repository. In the below example I will be using tanersener/mobile-ffmpeg, as it has support for Android 10 scoped storage, and also it is the best library available on the internet for FFmpeg mobile. 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: Adding a dependency to the build.gradle file We will be using tanersener/mobile-ffmpeg library to implement FFmpeg functionalities in our app. And we will also require a rangeseekbar to select the particular length of the video. So add these dependencies in build.gradle file. implementation ‘com.arthenica:mobile-ffmpeg-full:4.4’ implementation ‘org.florescu.android.rangeseekbar:rangeseekbar-library:0.3.0’ Step 3: Working with the colors.xml file Below is the code for the colors.xml file. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPost">#0091EA</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#E25E14</color> <color name="colorAccentTrans">#BEE25E14</color> <color name="maincolor">#E25E14</color> <color name="yellow">#feeb3c</color> <color name="white">#fff</color> <color name="semitranswhitecolor">#00FFFFFF</color> <color name="colorwhite_50">#CCffffff</color> <color name="colorwhite_10">#1Affffff</color> <color name="colorwhite_30">#4Dffffff</color> <color name="black">#2F2F2F</color> <color name="graycolor">#D3D3D3</color> <color name="graycolor2">#C5C4C4</color> <color name="gainsboro">#DCDCDC</color> <color name="lightgraycolor">#f2f2f2</color> <color name="darkgray">#93959A</color> <color name="darkgraytrans">#9493959A</color> <color name="darkgraytransPost">#9BC5C6C9</color> <color name="dimgray">#696969</color> <color name="lightblack">#5d5d5d</color> <color name="delete_message_bg">#f2f2f2</color> <color name="delete_message_text">#b8b8b8</color> <color name="transparent">#00ffffff</color> <color name="fifty_transparent_black">#802F2F2F</color> <color name="redcolor">#ff0008</color> <color name="semitransredcolor">#93FF0008</color> <color name="semitransredcolornew">#918E8E</color> <color name="color_gray_alpha">#65b7b7b7</color> <color name="app_blue">#0e1f2f</color> <color name="text_color">#000000</color> <color name="seekbar_color">#3be3e3</color> <color name="line_color">#FF15FF00</color> <color name="shadow_color">#00000000</color> <color name="app_color">#c52127</color> </resources> Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.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" android:background="#43AF47" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/relative1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_margin="10dp"> <Button android:id="@+id/cancel_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@color/transparent" android:text="Select Video" android:textColor="@color/white" /> </RelativeLayout> <VideoView android:id="@+id/layout_movie_wrapper" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/relative" android:layout_below="@+id/relative1" /> <TextView android:id="@+id/progressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:paddingBottom="5dp" /> <RelativeLayout android:id="@+id/imagelinear" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/relative" android:layout_below="@+id/relative1" android:layout_centerInParent="true"> <TextView android:id="@+id/overlaytextview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Raghav" android:textAppearance="@style/TextAppearance.AppCompat.Medium" android:textColor="@color/white" android:textStyle="bold" android:visibility="gone" /> <ImageView android:id="@+id/overlayimage" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:scaleType="fitXY" /> </RelativeLayout> <LinearLayout android:id="@+id/relative" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/textleft" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_marginBottom="10dp" android:text="00:00" android:textColor="@color/white" /> <TextView android:id="@+id/textright" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_marginBottom="10dp" android:layout_weight="1" android:text="00:00" android:textAlignment="textEnd" android:textColor="@color/white" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white"> <org.florescu.android.rangeseekbar.RangeSeekBar android:id="@+id/rangeSeekBar" android:layout_width="match_parent" android:layout_height="wrap_content" app:activeColor="@color/white" app:alwaysActive="true" app:barHeight="2dp" app:showLabels="false" app:textAboveThumbsColor="#000000" /> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="10dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/lineartime" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:text="" android:textColor="@color/semitransredcolornew" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:orientation="vertical"> <ImageButton android:id="@+id/slow" android:layout_width="50dp" android:layout_height="50dp" android:layout_gravity="center" android:background="@color/transparent" android:scaleType="fitXY" android:src="@drawable/icon_effect_slow" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Slow Motion" android:textAlignment="center" android:textColor="@color/white" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:orientation="vertical"> <ImageButton android:id="@+id/reverse" android:layout_width="50dp" android:layout_height="50dp" android:layout_gravity="center" android:background="@color/transparent" android:scaleType="fitXY" android:src="@drawable/icon_effect_time" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Reverse" android:textAlignment="center" android:textColor="@color/white" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:orientation="vertical"> <ImageButton android:id="@+id/fast" android:layout_width="50dp" android:layout_height="50dp" android:layout_gravity="center" android:background="@color/transparent" android:scaleType="fitXY" android:src="@drawable/icon_effect_repeatedly" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Flash" android:textAlignment="center" android:textColor="@color/white" /> </LinearLayout> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/lineareffects" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:text="Tap to add effects" android:textColor="@color/white" /> </LinearLayout> </RelativeLayout> </LinearLayout> </RelativeLayout> Step 5: 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.app.ProgressDialog;import android.content.ContentValues;import android.content.Intent;import android.media.MediaPlayer;import android.net.Uri;import android.os.Build;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.provider.MediaStore;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;import android.widget.VideoView;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import com.arthenica.mobileffmpeg.Config;import com.arthenica.mobileffmpeg.ExecuteCallback;import com.arthenica.mobileffmpeg.FFmpeg;import org.florescu.android.rangeseekbar.RangeSeekBar;import java.io.File;import static com.arthenica.mobileffmpeg.Config.RETURN_CODE_CANCEL;import static com.arthenica.mobileffmpeg.Config.RETURN_CODE_SUCCESS; public class MainActivity extends AppCompatActivity { private ImageButton reverse, slow, fast; private Button cancel; private TextView tvLeft, tvRight; private ProgressDialog progressDialog; private String video_url; private VideoView videoView; private Runnable r; private RangeSeekBar rangeSeekBar; private static final String root = Environment.getExternalStorageDirectory().toString(); private static final String app_folder = root + "/GFG/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rangeSeekBar = (RangeSeekBar) findViewById(R.id.rangeSeekBar); tvLeft = (TextView) findViewById(R.id.textleft); tvRight = (TextView) findViewById(R.id.textright); slow = (ImageButton) findViewById(R.id.slow); reverse = (ImageButton) findViewById(R.id.reverse); fast = (ImageButton) findViewById(R.id.fast); cancel = (Button) findViewById(R.id.cancel_button); fast = (ImageButton) findViewById(R.id.fast); videoView = (VideoView) findViewById(R.id.layout_movie_wrapper); // creating the progress dialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Please wait.."); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); // set up the onClickListeners cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // create an intent to retrieve the video // file from the device storage Intent intent = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI); intent.setType("video/*"); startActivityForResult(intent, 123); } }); slow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check if the user has selected any video or not // In case a user hasn't selected any video and press the button, // we will show an warning, stating "Please upload the video" if (video_url != null) { // a try-catch block to handle all necessary exceptions // like File not found, IOException try { slowmotion(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000); } catch (Exception e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } else Toast.makeText(MainActivity.this, "Please upload video", Toast.LENGTH_SHORT).show(); } }); fast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (video_url != null) { try { fastforward(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); } } else Toast.makeText(MainActivity.this, "Please upload video", Toast.LENGTH_SHORT).show(); } }); reverse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (video_url != null) { try { reverse(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); } } else Toast.makeText(MainActivity.this, "Please upload video", Toast.LENGTH_SHORT).show(); } }); // set up the VideoView. // We will be using VideoView to view our video videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // get the duration of the video int duration = mp.getDuration() / 1000; // initially set the left TextView to "00:00:00" tvLeft.setText("00:00:00"); // initially set the right Text-View to the video length // the getTime() method returns a formatted string in hh:mm:ss tvRight.setText(getTime(mp.getDuration() / 1000)); // this will run he video in loop // i.e. the video won't stop // when it reaches its duration mp.setLooping(true); // set up the initial values of rangeSeekbar rangeSeekBar.setRangeValues(0, duration); rangeSeekBar.setSelectedMinValue(0); rangeSeekBar.setSelectedMaxValue(duration); rangeSeekBar.setEnabled(true); rangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() { @Override public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) { // we seek through the video when the user // drags and adjusts the seekbar videoView.seekTo((int) minValue * 1000); // changing the left and right TextView according to // the minValue and maxValue tvLeft.setText(getTime((int) bar.getSelectedMinValue())); tvRight.setText(getTime((int) bar.getSelectedMaxValue())); } }); // this method changes the right TextView every 1 second // as the video is being played // It works same as a time counter we see in any Video Player final Handler handler = new Handler(); handler.postDelayed(r = new Runnable() { @Override public void run() { if (videoView.getCurrentPosition() >= rangeSeekBar.getSelectedMaxValue().intValue() * 1000) videoView.seekTo(rangeSeekBar.getSelectedMinValue().intValue() * 1000); handler.postDelayed(r, 1000); } }, 1000); } }); } // Method for creating fast motion video private void fastforward(int startMs, int endMs) throws Exception { // startMs is the starting time, from where we have to apply the effect. // endMs is the ending time, till where we have to apply effect. // For example, we have a video of 5min and we only want to fast forward a part of video // say, from 1:00 min to 2:00min, then our startMs will be 1000ms and endMs will be 2000ms. // create a progress dialog and show it until this method executes. progressDialog.show(); // creating a new file in storage final String filePath; String filePrefix = "fastforward"; String fileExtn = ".mp4"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // With introduction of scoped storage in Android Q the primitive method gives error // So, it is recommended to use the below method to create a video file in storage. ContentValues valuesvideos = new ContentValues(); valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "Folder"); valuesvideos.put(MediaStore.Video.Media.TITLE, filePrefix + System.currentTimeMillis()); valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, filePrefix + System.currentTimeMillis() + fileExtn); valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4"); valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000); valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()); Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos); // get the path of the video file created in the storage. File file = FileUtils.getFileFromUri(this, uri); filePath = file.getAbsolutePath(); } else { // This else statement will work for devices with Android version lower than 10 // Here, "app_folder" is the path to your app's root directory in device storage File dest = new File(new File(app_folder), filePrefix + fileExtn); int fileNo = 0; // check if the file name previously exist. Since we don't want // to overwrite the video files while (dest.exists()) { fileNo++; dest = new File(new File(app_folder), filePrefix + fileNo + fileExtn); } // Get the filePath once the file is successfully created. filePath = dest.getAbsolutePath(); } String exe; // the "exe" string contains the command to process video.The details of command are discussed later in this post. // "video_url" is the url of video which you want to edit. You can get this url from intent by selecting any video from gallery. exe = "-y -i " + video_url + " -filter_complex [0:v]trim=0:" + startMs / 1000 + ",setpts=PTS-STARTPTS[v1];[0:v]trim=" + startMs / 1000 + ":" + endMs / 1000 + ",setpts=0.5*(PTS-STARTPTS)[v2];[0:v]trim=" + (endMs / 1000) + ",setpts=PTS-STARTPTS[v3];[0:a]atrim=0:" + (startMs / 1000) + ",asetpts=PTS-STARTPTS[a1];[0:a]atrim=" + (startMs / 1000) + ":" + (endMs / 1000) + ",asetpts=PTS-STARTPTS,atempo=2[a2];[0:a]atrim=" + (endMs / 1000) + ",asetpts=PTS-STARTPTS[a3];[v1][a1][v2][a2][v3][a3]concat=n=3:v=1:a=1 " + "-b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast " + filePath; // Here, we have used he Async task to execute our query because // if we use the regular method the progress dialog // won't be visible. This happens because the regular method and // progress dialog uses the same thread to execute // and as a result only one is a allowed to work at a time. // By using we Async task we create a different thread which resolves the issue. long executionId = FFmpeg.executeAsync(exe, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { if (returnCode == RETURN_CODE_SUCCESS) { // after successful execution of ffmpeg command, // again set up the video Uri in VideoView videoView.setVideoURI(Uri.parse(filePath)); // change the video_url to filePath, so that we could // do more manipulations in the // resultant video. By this we can apply as many effects // as we want in a single video. // Actually there are multiple videos being formed in // storage but while using app it // feels like we are doing manipulations in only one video video_url = filePath; // play the result video in VideoView videoView.start(); // remove the progress dialog progressDialog.dismiss(); } else if (returnCode == RETURN_CODE_CANCEL) { Log.i(Config.TAG, "Async command execution cancelled by user."); } else { Log.i(Config.TAG, String.format("Async command execution failed with returnCode=%d.", returnCode)); } } }); } // Method for creating slow motion video for specific part of the video // The below code is same as above only the command in string "exe" is changed private void slowmotion(int startMs, int endMs) throws Exception { progressDialog.show(); final String filePath; String filePrefix = "slowmotion"; String fileExtn = ".mp4"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ContentValues valuesvideos = new ContentValues(); valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "Folder"); valuesvideos.put(MediaStore.Video.Media.TITLE, filePrefix + System.currentTimeMillis()); valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, filePrefix + System.currentTimeMillis() + fileExtn); valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4"); valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000); valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()); Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos); File file = FileUtils.getFileFromUri(this, uri); filePath = file.getAbsolutePath(); } else { File dest = new File(new File(app_folder), filePrefix + fileExtn); int fileNo = 0; while (dest.exists()) { fileNo++; dest = new File(new File(app_folder), filePrefix + fileNo + fileExtn); } filePath = dest.getAbsolutePath(); } String exe; exe = "-y -i " + video_url + " -filter_complex [0:v]trim=0:" + startMs / 1000 + ",setpts=PTS-STARTPTS[v1];[0:v]trim=" + startMs / 1000 + ":" + endMs / 1000 + ",setpts=2*(PTS-STARTPTS)[v2];[0:v]trim=" + (endMs / 1000) + ",setpts=PTS-STARTPTS[v3];[0:a]atrim=0:" + (startMs / 1000) + ",asetpts=PTS-STARTPTS[a1];[0:a]atrim=" + (startMs / 1000) + ":" + (endMs / 1000) + ",asetpts=PTS-STARTPTS,atempo=0.5[a2];[0:a]atrim=" + (endMs / 1000) + ",asetpts=PTS-STARTPTS[a3];[v1][a1][v2][a2][v3][a3]concat=n=3:v=1:a=1 " + "-b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast " + filePath; long executionId = FFmpeg.executeAsync(exe, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { if (returnCode == RETURN_CODE_SUCCESS) { videoView.setVideoURI(Uri.parse(filePath)); video_url = filePath; videoView.start(); progressDialog.dismiss(); } else if (returnCode == RETURN_CODE_CANCEL) { Log.i(Config.TAG, "Async command execution cancelled by user."); } else { Log.i(Config.TAG, String.format("Async command execution failed with returnCode=%d.", returnCode)); } } }); } // Method for reversing the video // The below code is same as above only the command is changed. private void reverse(int startMs, int endMs) throws Exception { progressDialog.show(); String filePrefix = "reverse"; String fileExtn = ".mp4"; final String filePath; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ContentValues valuesvideos = new ContentValues(); valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "Folder"); valuesvideos.put(MediaStore.Video.Media.TITLE, filePrefix + System.currentTimeMillis()); valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, filePrefix + System.currentTimeMillis() + fileExtn); valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4"); valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000); valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()); Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos); File file = FileUtils.getFileFromUri(this, uri); filePath = file.getAbsolutePath(); } else { filePrefix = "reverse"; fileExtn = ".mp4"; File dest = new File(new File(app_folder), filePrefix + fileExtn); int fileNo = 0; while (dest.exists()) { fileNo++; dest = new File(new File(app_folder), filePrefix + fileNo + fileExtn); } filePath = dest.getAbsolutePath(); } long executionId = FFmpeg.executeAsync("-y -i " + video_url + " -filter_complex [0:v]trim=0:" + endMs / 1000 + ",setpts=PTS-STARTPTS[v1];[0:v]trim=" + startMs / 1000 + ":" + endMs / 1000 + ",reverse,setpts=PTS-STARTPTS[v2];[0:v]trim=" + (startMs / 1000) + ",setpts=PTS-STARTPTS[v3];[v1][v2][v3]concat=n=3:v=1 " + "-b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast " + filePath, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { if (returnCode == RETURN_CODE_SUCCESS) { videoView.setVideoURI(Uri.parse(filePath)); video_url = filePath; videoView.start(); progressDialog.dismiss(); } else if (returnCode == RETURN_CODE_CANCEL) { Log.i(Config.TAG, "Async command execution cancelled by user."); } else { Log.i(Config.TAG, String.format("Async command execution failed with returnCode=%d.", returnCode)); } } }); } // Overriding the method onActivityResult() // to get the video Uri form intent. @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 123) { if (data != null) { // get the video Uri Uri uri = data.getData(); try { // get the file from the Uri using getFileFromUri() method present // in FileUils.java File video_file = FileUtils.getFileFromUri(this, uri); // now set the video uri in the VideoView videoView.setVideoURI(uri); // after successful retrieval of the video and properly // setting up the retried video uri in // VideoView, Start the VideoView to play that video videoView.start(); // get the absolute path of the video file. We will require // this as an input argument in // the ffmpeg command. video_url = video_file.getAbsolutePath(); } catch (Exception e) { Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } } } } // This method returns the seconds in hh:mm:ss time format private String getTime(int seconds) { int hr = seconds / 3600; int rem = seconds % 3600; int mn = rem / 60; int sec = rem % 60; return String.format("%02d", hr) + ":" + String.format("%02d", mn) + ":" + String.format("%02d", sec); }} Step 6: Creating a new Java Class FileUtils.java Refer to How to Create Classes in Android Studio to create a new java class in Android Studio. This is a Utility file that will help in retrieving the File from a Uri. Below is the code for the FileUtils.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.ContentUris;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.os.Environment;import android.provider.DocumentsContract;import android.provider.MediaStore;import java.io.File; public class FileUtils { // Get a file from a Uri. // Framework Documents, as well as the _data field for the MediaStore and // other file-based ContentProviders. // @param context The context. // @param uri The Uri to query public static File getFileFromUri(final Context context, final Uri uri) throws Exception { String path = null; // DocumentProvider if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (DocumentsContract.isDocumentUri(context, uri)) { // TODO: 2015. 11. 17. KITKAT // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { path = Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } else if (isDownloadsDocument(uri)) { // DownloadsProvider final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); path = getDataColumn(context, contentUri, null, null); } else if (isMediaDocument(uri)) { // MediaProvider final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[]{ split[1] }; path = getDataColumn(context, contentUri, selection, selectionArgs); } // MediaStore (and general) } else if ("content".equalsIgnoreCase(uri.getScheme())) { path = getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { path = uri.getPath(); } return new File(path); } else { Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); return new File(cursor.getString(cursor.getColumnIndex("_data"))); } } // Get the value of the data column for this Uri. This is useful for // MediaStore Uris, and other file-based ContentProviders. // @param context The context. // @param uri The Uri to query. // @param selection (Optional) Filter used in the query. // @param selectionArgs (Optional) Selection arguments used in the query. // @return The value of the _data column, which is typically a file path. public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.Images.Media.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } // @param uri The Uri to check. // @return Whether the Uri authority is ExternalStorageProvide public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } // @param uri The Uri to check. // @return Whether the Uri authority is DownloadsProvider. public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } // @param uri The Uri to check. // @return Whether the Uri authority is MediaProvider. public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); }} Output: Github Project Link: https://github.com/raghavtilak/VideoEditor concate video of different framerates in .mkv format:-i input1.mp4 -i input2.mp4 -filter_complex [0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa] -map [outv] -map [outa] output.mkv -i input1.mp4 -i input2.mp4 -filter_complex [0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa] -map [outv] -map [outa] output.mkv concate video with no sound/audio:-y -i input.mp4 -filter_complex [0:v]trim=0:0,setpts=PTS-STARTPTS[v1];[0:v]trim=0:5,setpts=0.5*(PTS-STARTPTS)[v2];[0:v]trim=5,setpts=PTS-STARTPTS[v3];[v1][v2][v3]concat=n=3:v=1:a=0 -b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast output.mp4 -y -i input.mp4 -filter_complex [0:v]trim=0:0,setpts=PTS-STARTPTS[v1];[0:v]trim=0:5,setpts=0.5*(PTS-STARTPTS)[v2];[0:v]trim=5,setpts=PTS-STARTPTS[v3];[v1][v2][v3]concat=n=3:v=1:a=0 -b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast output.mp4 Textoverlay:-y -i input.mp4 -vf drawtext=”fontsize=30:fontfile=cute.ttf:text=’GFG'”:x=w-tw-10:y=h-th-10 -c:v libx264 -preset ultrafast outputmp4 -y -i input.mp4 -vf drawtext=”fontsize=30:fontfile=cute.ttf:text=’GFG'”:x=w-tw-10:y=h-th-10 -c:v libx264 -preset ultrafast outputmp4 gif/png/jpeg overlay-i input.mp4 -i inputimage.png -filter_complex [1:v]scale=320:394[ovr1],[0:v][ovr1]overlay=0:0:enable=’between(t,0,16)’ -c:a copy output.mp4, (or)-i input.mp4 -i inputimage.png -filter_complex overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2:enable=’between(t,0,7)’ -c:a copy output.mp4 -i input.mp4 -i inputimage.png -filter_complex [1:v]scale=320:394[ovr1],[0:v][ovr1]overlay=0:0:enable=’between(t,0,16)’ -c:a copy output.mp4, (or) -i input.mp4 -i inputimage.png -filter_complex overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2:enable=’between(t,0,7)’ -c:a copy output.mp4 Add subtitles to a video file-i input.mp4 -i subtitle.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset superfast output.mp4 -i input.mp4 -i subtitle.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset superfast output.mp4 Converting video files to audio files-i input.mp4 -vn output.mp3 -i input.mp4 -vn output.mp3 Cropping videos-i input.mp4 -filter:v “crop=w:h:x:y” output.mp4w – width of the rectangle which we are intended to crop from the source video.h – the height of that rectangle.x – the x coordinate of that rectangle.y – the y coordinate of the rectangle. -i input.mp4 -filter:v “crop=w:h:x:y” output.mp4w – width of the rectangle which we are intended to crop from the source video.h – the height of that rectangle.x – the x coordinate of that rectangle.y – the y coordinate of the rectangle. w – width of the rectangle which we are intended to crop from the source video. h – the height of that rectangle. x – the x coordinate of that rectangle. y – the y coordinate of the rectangle. Adding a poster image to audio files-loop 1 -i inputimage.jpg -i inputaudio.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest output.mp4 -loop 1 -i inputimage.jpg -i inputaudio.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest output.mp4 It is also highly portable.It is profoundly valuable for the transcoding of all kinds of multimedia files into a single common format.You don’t need heavy Third-party VideoEditors like Adobe Premiere Pro, Filmora for small editing tasks. It is also highly portable. It is profoundly valuable for the transcoding of all kinds of multimedia files into a single common format. You don’t need heavy Third-party VideoEditors like Adobe Premiere Pro, Filmora for small editing tasks. It’s difficult for beginners to use and implement.It takes some time to process. We don’t get results in a second or two.The official documentation is quite confusing and it’s not beginner-friendly.APK size becomes very large. The FFmpeg libraries alone will use 30-70MB depending upon the libraries you are including. It’s difficult for beginners to use and implement. It takes some time to process. We don’t get results in a second or two. The official documentation is quite confusing and it’s not beginner-friendly. APK size becomes very large. The FFmpeg libraries alone will use 30-70MB depending upon the libraries you are including. MediaCodec Android LiTr Gstreamer MP4Parser Intel INDE Media for Mobile Notes: 1. If you set -preset to a higher value say, ultrafast then the video processing will be fast but the quality of the video will be compromised. The lower the -preset higher the quality of the video. 2. You can change the -crf value to change the quality of the output video. Lower the crf value higher the quality of the video. 3. If you use -y in starting of command then this means that if a file is present with the same name as that of the output file name that FFmpeg will overwrite the existing file. 4. In the case of video, to slow down the video set -PTS value larger than 1. The larger the value slower the video, Lower the value Faster the video. But in the case of Audio this is just the opposite, i.e. Larger the value faster the Audio, the Lower the value slower the audio. 5. The atempo(audio) filter is limited to using values between 0.5 and 2.0 (so it can slow it down to no less than half the original speed, and speed up to no more than double the input) 6. FFmpeg takes too much time working with audio. If the video file doesn’t contain the audio we need not to command FFmpeg to work with audio, and hence this will reduce the workload and we will get the processed video fast/in less time. varshagumber28 prachisoda1234 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. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Content Providers in Android with Example Android RecyclerView in Kotlin Navigation Drawer in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java HashMap in Java with Examples
[ { "code": null, "e": 25470, "s": 25442, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26887, "s": 25470, "text": "FFmpeg, short for Fast-forward MPEG, is a free and open-source multimedia framework, which is able to decode, encode, transcode, mux, demux, stream, filter and play fairly all kinds of multimedia files that have been created to date. It also supports some of the eldest formats. FFmpeg compiles and runs, across various operating systems like Linux, Mac OS X, Microsoft Windows, the BSDs, Solaris, etc. among a large range of build environments, machine architectures, and configurations. Programming languages used in FFmpeg are C and Assembly language. We can do many fun kinds of stuff using Ffmpeg like, Video Compress, Audio Compress, Trim Video, Rotate Video, Crop Video, Adding filters to videos, Reverse a Video, Creating fast and slow-motion video, Fade in fade out, Merge audio and video, Creating a video from images, Convert video from one format into another, Extract Picture from Video or Sound from Video, Gifs overlay, and many more. FFmpeg is part of the workflow of hundreds of other media-related software projects, and it’s often used behind the scenes. Also, It is an internal part of software such as VLC media player, YouTube, Plex, iTunes, Shortcut, Blender, Kodi, HandBrake, it handles video and audio playback in Google Chrome, and Linux version of Firefox. FFmpeg comprises an enormous set-up of libraries and projects for dealing with video, sound, and other multimedia files and streams." }, { "code": null, "e": 27114, "s": 26887, "text": "libavutil is a utility library to help versatile media programming. It contains portable string functions, arbitrary number generators, extra arithmetic capacities, data structures, cryptography, and core multimedia utilities." }, { "code": null, "e": 27248, "s": 27114, "text": "libavcodec is a library that provides encoders and decoders for video/audio codecs, subtitle streams, and several bitstream channels." }, { "code": null, "e": 27370, "s": 27248, "text": "libavformat is a library that provides multiplexing and demultiplexing framework for video/audio codecs, subtitle streams" }, { "code": null, "e": 27536, "s": 27370, "text": "libavdevice is a library containing I/O devices for getting from and delivering to numerous multimedia I/O programming systems, including Video4Linux, ALSA, and VfW." }, { "code": null, "e": 27634, "s": 27536, "text": "libavfilter library provides a media filtering framework that contains several filters and sinks." }, { "code": null, "e": 27740, "s": 27634, "text": "libswscale library performs exceptionally enhanced picture scaling and pixel format transformation tasks." }, { "code": null, "e": 27932, "s": 27740, "text": "libswresample is a library that performs highly optimized but a lossy change in audio rate, change in channel layout, for example from stereo to mono, and sample format conversion operations." }, { "code": null, "e": 28181, "s": 27932, "text": "Android doesn’t have efficient and robust APIs for multimedia which could provide functionalities like FFmpeg. The only API which android has is MediaCodec API, but it is faster than FFmpeg because it uses the device hardware for video processing." }, { "code": null, "e": 28197, "s": 28181, "text": "Prerequisites: " }, { "code": null, "e": 28307, "s": 28197, "text": "Before we start, we need to set up an environment to run our FFmpeg commands. There are two options to do so:" }, { "code": null, "e": 28335, "s": 28307, "text": "By building our own library" }, { "code": null, "e": 28705, "s": 28335, "text": "By using any compiled source provided by the community. There are many libraries that can be used to perform FFmpeg operations in Android. For example,WritingMindsBravobittanersener/mobile-ffmpegyangjie10930/EpMedia: There are many inbuilt functions present in this library from which you can clip, crop, rotate, add a logo, add a custom filter, merge different videos." }, { "code": null, "e": 28718, "s": 28705, "text": "WritingMinds" }, { "code": null, "e": 28727, "s": 28718, "text": "Bravobit" }, { "code": null, "e": 28752, "s": 28727, "text": "tanersener/mobile-ffmpeg" }, { "code": null, "e": 28927, "s": 28752, "text": "yangjie10930/EpMedia: There are many inbuilt functions present in this library from which you can clip, crop, rotate, add a logo, add a custom filter, merge different videos." }, { "code": null, "e": 29683, "s": 28927, "text": "Although it is highly recommended to build your library, because that will reduce your apk size, you can add a third-party library and can update the library with time as you want. But, this process is very time consuming and requires extra skills. So, as a beginner, you can use some above-mentioned libraries and if you face some issue you can raise that issue on their respective GitHub repository. In the below example I will be using tanersener/mobile-ffmpeg, as it has support for Android 10 scoped storage, and also it is the best library available on the internet for FFmpeg mobile. 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": 29712, "s": 29683, "text": "Step 1: Create a New Project" }, { "code": null, "e": 29874, "s": 29712, "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": 29927, "s": 29874, "text": "Step 2: Adding a dependency to the build.gradle file" }, { "code": null, "e": 30159, "s": 29927, "text": "We will be using tanersener/mobile-ffmpeg library to implement FFmpeg functionalities in our app. And we will also require a rangeseekbar to select the particular length of the video. So add these dependencies in build.gradle file." }, { "code": null, "e": 30213, "s": 30159, "text": "implementation ‘com.arthenica:mobile-ffmpeg-full:4.4’" }, { "code": null, "e": 30291, "s": 30213, "text": "implementation ‘org.florescu.android.rangeseekbar:rangeseekbar-library:0.3.0’" }, { "code": null, "e": 30332, "s": 30291, "text": "Step 3: Working with the colors.xml file" }, { "code": null, "e": 30375, "s": 30332, "text": "Below is the code for the colors.xml file." }, { "code": null, "e": 30379, "s": 30375, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#3F51B5</color> <color name=\"colorPost\">#0091EA</color> <color name=\"colorPrimaryDark\">#303F9F</color> <color name=\"colorAccent\">#E25E14</color> <color name=\"colorAccentTrans\">#BEE25E14</color> <color name=\"maincolor\">#E25E14</color> <color name=\"yellow\">#feeb3c</color> <color name=\"white\">#fff</color> <color name=\"semitranswhitecolor\">#00FFFFFF</color> <color name=\"colorwhite_50\">#CCffffff</color> <color name=\"colorwhite_10\">#1Affffff</color> <color name=\"colorwhite_30\">#4Dffffff</color> <color name=\"black\">#2F2F2F</color> <color name=\"graycolor\">#D3D3D3</color> <color name=\"graycolor2\">#C5C4C4</color> <color name=\"gainsboro\">#DCDCDC</color> <color name=\"lightgraycolor\">#f2f2f2</color> <color name=\"darkgray\">#93959A</color> <color name=\"darkgraytrans\">#9493959A</color> <color name=\"darkgraytransPost\">#9BC5C6C9</color> <color name=\"dimgray\">#696969</color> <color name=\"lightblack\">#5d5d5d</color> <color name=\"delete_message_bg\">#f2f2f2</color> <color name=\"delete_message_text\">#b8b8b8</color> <color name=\"transparent\">#00ffffff</color> <color name=\"fifty_transparent_black\">#802F2F2F</color> <color name=\"redcolor\">#ff0008</color> <color name=\"semitransredcolor\">#93FF0008</color> <color name=\"semitransredcolornew\">#918E8E</color> <color name=\"color_gray_alpha\">#65b7b7b7</color> <color name=\"app_blue\">#0e1f2f</color> <color name=\"text_color\">#000000</color> <color name=\"seekbar_color\">#3be3e3</color> <color name=\"line_color\">#FF15FF00</color> <color name=\"shadow_color\">#00000000</color> <color name=\"app_color\">#c52127</color> </resources>", "e": 32133, "s": 30379, "text": null }, { "code": null, "e": 32184, "s": 32136, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 32302, "s": 32186, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 32308, "s": 32304, "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\" android:background=\"#43AF47\" tools:context=\".MainActivity\"> <RelativeLayout android:id=\"@+id/relative1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_margin=\"10dp\"> <Button android:id=\"@+id/cancel_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:background=\"@color/transparent\" android:text=\"Select Video\" android:textColor=\"@color/white\" /> </RelativeLayout> <VideoView android:id=\"@+id/layout_movie_wrapper\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_above=\"@+id/relative\" android:layout_below=\"@+id/relative1\" /> <TextView android:id=\"@+id/progressbar\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:paddingBottom=\"5dp\" /> <RelativeLayout android:id=\"@+id/imagelinear\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_above=\"@+id/relative\" android:layout_below=\"@+id/relative1\" android:layout_centerInParent=\"true\"> <TextView android:id=\"@+id/overlaytextview\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Raghav\" android:textAppearance=\"@style/TextAppearance.AppCompat.Medium\" android:textColor=\"@color/white\" android:textStyle=\"bold\" android:visibility=\"gone\" /> <ImageView android:id=\"@+id/overlayimage\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_centerInParent=\"true\" android:scaleType=\"fitXY\" /> </RelativeLayout> <LinearLayout android:id=\"@+id/relative\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:orientation=\"vertical\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:id=\"@+id/textleft\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_marginBottom=\"10dp\" android:text=\"00:00\" android:textColor=\"@color/white\" /> <TextView android:id=\"@+id/textright\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_marginBottom=\"10dp\" android:layout_weight=\"1\" android:text=\"00:00\" android:textAlignment=\"textEnd\" android:textColor=\"@color/white\" /> </RelativeLayout> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/white\"> <org.florescu.android.rangeseekbar.RangeSeekBar android:id=\"@+id/rangeSeekBar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:activeColor=\"@color/white\" app:alwaysActive=\"true\" app:barHeight=\"2dp\" app:showLabels=\"false\" app:textAboveThumbsColor=\"#000000\" /> </RelativeLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"10dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <LinearLayout android:id=\"@+id/lineartime\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"10dp\" android:text=\"\" android:textColor=\"@color/semitransredcolornew\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:orientation=\"vertical\"> <ImageButton android:id=\"@+id/slow\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_gravity=\"center\" android:background=\"@color/transparent\" android:scaleType=\"fitXY\" android:src=\"@drawable/icon_effect_slow\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Slow Motion\" android:textAlignment=\"center\" android:textColor=\"@color/white\" /> </LinearLayout> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:orientation=\"vertical\"> <ImageButton android:id=\"@+id/reverse\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_gravity=\"center\" android:background=\"@color/transparent\" android:scaleType=\"fitXY\" android:src=\"@drawable/icon_effect_time\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Reverse\" android:textAlignment=\"center\" android:textColor=\"@color/white\" /> </LinearLayout> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:orientation=\"vertical\"> <ImageButton android:id=\"@+id/fast\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_gravity=\"center\" android:background=\"@color/transparent\" android:scaleType=\"fitXY\" android:src=\"@drawable/icon_effect_repeatedly\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Flash\" android:textAlignment=\"center\" android:textColor=\"@color/white\" /> </LinearLayout> </LinearLayout> </LinearLayout> <LinearLayout android:id=\"@+id/lineareffects\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/text2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"10dp\" android:text=\"Tap to add effects\" android:textColor=\"@color/white\" /> </LinearLayout> </RelativeLayout> </LinearLayout> </RelativeLayout>", "e": 41564, "s": 32308, "text": null }, { "code": null, "e": 41615, "s": 41567, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 41807, "s": 41617, "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": 41814, "s": 41809, "text": "Java" }, { "code": "import android.app.ProgressDialog;import android.content.ContentValues;import android.content.Intent;import android.media.MediaPlayer;import android.net.Uri;import android.os.Build;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.provider.MediaStore;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;import android.widget.VideoView;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import com.arthenica.mobileffmpeg.Config;import com.arthenica.mobileffmpeg.ExecuteCallback;import com.arthenica.mobileffmpeg.FFmpeg;import org.florescu.android.rangeseekbar.RangeSeekBar;import java.io.File;import static com.arthenica.mobileffmpeg.Config.RETURN_CODE_CANCEL;import static com.arthenica.mobileffmpeg.Config.RETURN_CODE_SUCCESS; public class MainActivity extends AppCompatActivity { private ImageButton reverse, slow, fast; private Button cancel; private TextView tvLeft, tvRight; private ProgressDialog progressDialog; private String video_url; private VideoView videoView; private Runnable r; private RangeSeekBar rangeSeekBar; private static final String root = Environment.getExternalStorageDirectory().toString(); private static final String app_folder = root + \"/GFG/\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rangeSeekBar = (RangeSeekBar) findViewById(R.id.rangeSeekBar); tvLeft = (TextView) findViewById(R.id.textleft); tvRight = (TextView) findViewById(R.id.textright); slow = (ImageButton) findViewById(R.id.slow); reverse = (ImageButton) findViewById(R.id.reverse); fast = (ImageButton) findViewById(R.id.fast); cancel = (Button) findViewById(R.id.cancel_button); fast = (ImageButton) findViewById(R.id.fast); videoView = (VideoView) findViewById(R.id.layout_movie_wrapper); // creating the progress dialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage(\"Please wait..\"); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); // set up the onClickListeners cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // create an intent to retrieve the video // file from the device storage Intent intent = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI); intent.setType(\"video/*\"); startActivityForResult(intent, 123); } }); slow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check if the user has selected any video or not // In case a user hasn't selected any video and press the button, // we will show an warning, stating \"Please upload the video\" if (video_url != null) { // a try-catch block to handle all necessary exceptions // like File not found, IOException try { slowmotion(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000); } catch (Exception e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } else Toast.makeText(MainActivity.this, \"Please upload video\", Toast.LENGTH_SHORT).show(); } }); fast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (video_url != null) { try { fastforward(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); } } else Toast.makeText(MainActivity.this, \"Please upload video\", Toast.LENGTH_SHORT).show(); } }); reverse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (video_url != null) { try { reverse(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); } } else Toast.makeText(MainActivity.this, \"Please upload video\", Toast.LENGTH_SHORT).show(); } }); // set up the VideoView. // We will be using VideoView to view our video videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // get the duration of the video int duration = mp.getDuration() / 1000; // initially set the left TextView to \"00:00:00\" tvLeft.setText(\"00:00:00\"); // initially set the right Text-View to the video length // the getTime() method returns a formatted string in hh:mm:ss tvRight.setText(getTime(mp.getDuration() / 1000)); // this will run he video in loop // i.e. the video won't stop // when it reaches its duration mp.setLooping(true); // set up the initial values of rangeSeekbar rangeSeekBar.setRangeValues(0, duration); rangeSeekBar.setSelectedMinValue(0); rangeSeekBar.setSelectedMaxValue(duration); rangeSeekBar.setEnabled(true); rangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() { @Override public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) { // we seek through the video when the user // drags and adjusts the seekbar videoView.seekTo((int) minValue * 1000); // changing the left and right TextView according to // the minValue and maxValue tvLeft.setText(getTime((int) bar.getSelectedMinValue())); tvRight.setText(getTime((int) bar.getSelectedMaxValue())); } }); // this method changes the right TextView every 1 second // as the video is being played // It works same as a time counter we see in any Video Player final Handler handler = new Handler(); handler.postDelayed(r = new Runnable() { @Override public void run() { if (videoView.getCurrentPosition() >= rangeSeekBar.getSelectedMaxValue().intValue() * 1000) videoView.seekTo(rangeSeekBar.getSelectedMinValue().intValue() * 1000); handler.postDelayed(r, 1000); } }, 1000); } }); } // Method for creating fast motion video private void fastforward(int startMs, int endMs) throws Exception { // startMs is the starting time, from where we have to apply the effect. // endMs is the ending time, till where we have to apply effect. // For example, we have a video of 5min and we only want to fast forward a part of video // say, from 1:00 min to 2:00min, then our startMs will be 1000ms and endMs will be 2000ms. // create a progress dialog and show it until this method executes. progressDialog.show(); // creating a new file in storage final String filePath; String filePrefix = \"fastforward\"; String fileExtn = \".mp4\"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // With introduction of scoped storage in Android Q the primitive method gives error // So, it is recommended to use the below method to create a video file in storage. ContentValues valuesvideos = new ContentValues(); valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, \"Movies/\" + \"Folder\"); valuesvideos.put(MediaStore.Video.Media.TITLE, filePrefix + System.currentTimeMillis()); valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, filePrefix + System.currentTimeMillis() + fileExtn); valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, \"video/mp4\"); valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000); valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()); Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos); // get the path of the video file created in the storage. File file = FileUtils.getFileFromUri(this, uri); filePath = file.getAbsolutePath(); } else { // This else statement will work for devices with Android version lower than 10 // Here, \"app_folder\" is the path to your app's root directory in device storage File dest = new File(new File(app_folder), filePrefix + fileExtn); int fileNo = 0; // check if the file name previously exist. Since we don't want // to overwrite the video files while (dest.exists()) { fileNo++; dest = new File(new File(app_folder), filePrefix + fileNo + fileExtn); } // Get the filePath once the file is successfully created. filePath = dest.getAbsolutePath(); } String exe; // the \"exe\" string contains the command to process video.The details of command are discussed later in this post. // \"video_url\" is the url of video which you want to edit. You can get this url from intent by selecting any video from gallery. exe = \"-y -i \" + video_url + \" -filter_complex [0:v]trim=0:\" + startMs / 1000 + \",setpts=PTS-STARTPTS[v1];[0:v]trim=\" + startMs / 1000 + \":\" + endMs / 1000 + \",setpts=0.5*(PTS-STARTPTS)[v2];[0:v]trim=\" + (endMs / 1000) + \",setpts=PTS-STARTPTS[v3];[0:a]atrim=0:\" + (startMs / 1000) + \",asetpts=PTS-STARTPTS[a1];[0:a]atrim=\" + (startMs / 1000) + \":\" + (endMs / 1000) + \",asetpts=PTS-STARTPTS,atempo=2[a2];[0:a]atrim=\" + (endMs / 1000) + \",asetpts=PTS-STARTPTS[a3];[v1][a1][v2][a2][v3][a3]concat=n=3:v=1:a=1 \" + \"-b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast \" + filePath; // Here, we have used he Async task to execute our query because // if we use the regular method the progress dialog // won't be visible. This happens because the regular method and // progress dialog uses the same thread to execute // and as a result only one is a allowed to work at a time. // By using we Async task we create a different thread which resolves the issue. long executionId = FFmpeg.executeAsync(exe, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { if (returnCode == RETURN_CODE_SUCCESS) { // after successful execution of ffmpeg command, // again set up the video Uri in VideoView videoView.setVideoURI(Uri.parse(filePath)); // change the video_url to filePath, so that we could // do more manipulations in the // resultant video. By this we can apply as many effects // as we want in a single video. // Actually there are multiple videos being formed in // storage but while using app it // feels like we are doing manipulations in only one video video_url = filePath; // play the result video in VideoView videoView.start(); // remove the progress dialog progressDialog.dismiss(); } else if (returnCode == RETURN_CODE_CANCEL) { Log.i(Config.TAG, \"Async command execution cancelled by user.\"); } else { Log.i(Config.TAG, String.format(\"Async command execution failed with returnCode=%d.\", returnCode)); } } }); } // Method for creating slow motion video for specific part of the video // The below code is same as above only the command in string \"exe\" is changed private void slowmotion(int startMs, int endMs) throws Exception { progressDialog.show(); final String filePath; String filePrefix = \"slowmotion\"; String fileExtn = \".mp4\"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ContentValues valuesvideos = new ContentValues(); valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, \"Movies/\" + \"Folder\"); valuesvideos.put(MediaStore.Video.Media.TITLE, filePrefix + System.currentTimeMillis()); valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, filePrefix + System.currentTimeMillis() + fileExtn); valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, \"video/mp4\"); valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000); valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()); Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos); File file = FileUtils.getFileFromUri(this, uri); filePath = file.getAbsolutePath(); } else { File dest = new File(new File(app_folder), filePrefix + fileExtn); int fileNo = 0; while (dest.exists()) { fileNo++; dest = new File(new File(app_folder), filePrefix + fileNo + fileExtn); } filePath = dest.getAbsolutePath(); } String exe; exe = \"-y -i \" + video_url + \" -filter_complex [0:v]trim=0:\" + startMs / 1000 + \",setpts=PTS-STARTPTS[v1];[0:v]trim=\" + startMs / 1000 + \":\" + endMs / 1000 + \",setpts=2*(PTS-STARTPTS)[v2];[0:v]trim=\" + (endMs / 1000) + \",setpts=PTS-STARTPTS[v3];[0:a]atrim=0:\" + (startMs / 1000) + \",asetpts=PTS-STARTPTS[a1];[0:a]atrim=\" + (startMs / 1000) + \":\" + (endMs / 1000) + \",asetpts=PTS-STARTPTS,atempo=0.5[a2];[0:a]atrim=\" + (endMs / 1000) + \",asetpts=PTS-STARTPTS[a3];[v1][a1][v2][a2][v3][a3]concat=n=3:v=1:a=1 \" + \"-b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast \" + filePath; long executionId = FFmpeg.executeAsync(exe, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { if (returnCode == RETURN_CODE_SUCCESS) { videoView.setVideoURI(Uri.parse(filePath)); video_url = filePath; videoView.start(); progressDialog.dismiss(); } else if (returnCode == RETURN_CODE_CANCEL) { Log.i(Config.TAG, \"Async command execution cancelled by user.\"); } else { Log.i(Config.TAG, String.format(\"Async command execution failed with returnCode=%d.\", returnCode)); } } }); } // Method for reversing the video // The below code is same as above only the command is changed. private void reverse(int startMs, int endMs) throws Exception { progressDialog.show(); String filePrefix = \"reverse\"; String fileExtn = \".mp4\"; final String filePath; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ContentValues valuesvideos = new ContentValues(); valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, \"Movies/\" + \"Folder\"); valuesvideos.put(MediaStore.Video.Media.TITLE, filePrefix + System.currentTimeMillis()); valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, filePrefix + System.currentTimeMillis() + fileExtn); valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, \"video/mp4\"); valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000); valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()); Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos); File file = FileUtils.getFileFromUri(this, uri); filePath = file.getAbsolutePath(); } else { filePrefix = \"reverse\"; fileExtn = \".mp4\"; File dest = new File(new File(app_folder), filePrefix + fileExtn); int fileNo = 0; while (dest.exists()) { fileNo++; dest = new File(new File(app_folder), filePrefix + fileNo + fileExtn); } filePath = dest.getAbsolutePath(); } long executionId = FFmpeg.executeAsync(\"-y -i \" + video_url + \" -filter_complex [0:v]trim=0:\" + endMs / 1000 + \",setpts=PTS-STARTPTS[v1];[0:v]trim=\" + startMs / 1000 + \":\" + endMs / 1000 + \",reverse,setpts=PTS-STARTPTS[v2];[0:v]trim=\" + (startMs / 1000) + \",setpts=PTS-STARTPTS[v3];[v1][v2][v3]concat=n=3:v=1 \" + \"-b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast \" + filePath, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { if (returnCode == RETURN_CODE_SUCCESS) { videoView.setVideoURI(Uri.parse(filePath)); video_url = filePath; videoView.start(); progressDialog.dismiss(); } else if (returnCode == RETURN_CODE_CANCEL) { Log.i(Config.TAG, \"Async command execution cancelled by user.\"); } else { Log.i(Config.TAG, String.format(\"Async command execution failed with returnCode=%d.\", returnCode)); } } }); } // Overriding the method onActivityResult() // to get the video Uri form intent. @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 123) { if (data != null) { // get the video Uri Uri uri = data.getData(); try { // get the file from the Uri using getFileFromUri() method present // in FileUils.java File video_file = FileUtils.getFileFromUri(this, uri); // now set the video uri in the VideoView videoView.setVideoURI(uri); // after successful retrieval of the video and properly // setting up the retried video uri in // VideoView, Start the VideoView to play that video videoView.start(); // get the absolute path of the video file. We will require // this as an input argument in // the ffmpeg command. video_url = video_file.getAbsolutePath(); } catch (Exception e) { Toast.makeText(this, \"Error\", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } } } } // This method returns the seconds in hh:mm:ss time format private String getTime(int seconds) { int hr = seconds / 3600; int rem = seconds % 3600; int mn = rem / 60; int sec = rem % 60; return String.format(\"%02d\", hr) + \":\" + String.format(\"%02d\", mn) + \":\" + String.format(\"%02d\", sec); }}", "e": 62696, "s": 41814, "text": null }, { "code": null, "e": 62745, "s": 62696, "text": "Step 6: Creating a new Java Class FileUtils.java" }, { "code": null, "e": 63034, "s": 62745, "text": "Refer to How to Create Classes in Android Studio to create a new java class in Android Studio. This is a Utility file that will help in retrieving the File from a Uri. Below is the code for the FileUtils.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 63039, "s": 63034, "text": "Java" }, { "code": "import android.content.ContentUris;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.os.Environment;import android.provider.DocumentsContract;import android.provider.MediaStore;import java.io.File; public class FileUtils { // Get a file from a Uri. // Framework Documents, as well as the _data field for the MediaStore and // other file-based ContentProviders. // @param context The context. // @param uri The Uri to query public static File getFileFromUri(final Context context, final Uri uri) throws Exception { String path = null; // DocumentProvider if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (DocumentsContract.isDocumentUri(context, uri)) { // TODO: 2015. 11. 17. KITKAT // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(\":\"); final String type = split[0]; if (\"primary\".equalsIgnoreCase(type)) { path = Environment.getExternalStorageDirectory() + \"/\" + split[1]; } // TODO handle non-primary volumes } else if (isDownloadsDocument(uri)) { // DownloadsProvider final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id)); path = getDataColumn(context, contentUri, null, null); } else if (isMediaDocument(uri)) { // MediaProvider final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(\":\"); final String type = split[0]; Uri contentUri = null; if (\"image\".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if (\"video\".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if (\"audio\".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = \"_id=?\"; final String[] selectionArgs = new String[]{ split[1] }; path = getDataColumn(context, contentUri, selection, selectionArgs); } // MediaStore (and general) } else if (\"content\".equalsIgnoreCase(uri.getScheme())) { path = getDataColumn(context, uri, null, null); } // File else if (\"file\".equalsIgnoreCase(uri.getScheme())) { path = uri.getPath(); } return new File(path); } else { Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); return new File(cursor.getString(cursor.getColumnIndex(\"_data\"))); } } // Get the value of the data column for this Uri. This is useful for // MediaStore Uris, and other file-based ContentProviders. // @param context The context. // @param uri The Uri to query. // @param selection (Optional) Filter used in the query. // @param selectionArgs (Optional) Selection arguments used in the query. // @return The value of the _data column, which is typically a file path. public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.Images.Media.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } // @param uri The Uri to check. // @return Whether the Uri authority is ExternalStorageProvide public static boolean isExternalStorageDocument(Uri uri) { return \"com.android.externalstorage.documents\".equals(uri.getAuthority()); } // @param uri The Uri to check. // @return Whether the Uri authority is DownloadsProvider. public static boolean isDownloadsDocument(Uri uri) { return \"com.android.providers.downloads.documents\".equals(uri.getAuthority()); } // @param uri The Uri to check. // @return Whether the Uri authority is MediaProvider. public static boolean isMediaDocument(Uri uri) { return \"com.android.providers.media.documents\".equals(uri.getAuthority()); }}", "e": 68148, "s": 63039, "text": null }, { "code": null, "e": 68156, "s": 68148, "text": "Output:" }, { "code": null, "e": 68222, "s": 68158, "text": "Github Project Link: https://github.com/raghavtilak/VideoEditor" }, { "code": null, "e": 68413, "s": 68222, "text": "concate video of different framerates in .mkv format:-i input1.mp4 -i input2.mp4 -filter_complex [0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa] -map [outv] -map [outa] output.mkv" }, { "code": null, "e": 68551, "s": 68413, "text": "-i input1.mp4 -i input2.mp4 -filter_complex [0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa] -map [outv] -map [outa] output.mkv" }, { "code": null, "e": 68827, "s": 68551, "text": "concate video with no sound/audio:-y -i input.mp4 -filter_complex [0:v]trim=0:0,setpts=PTS-STARTPTS[v1];[0:v]trim=0:5,setpts=0.5*(PTS-STARTPTS)[v2];[0:v]trim=5,setpts=PTS-STARTPTS[v3];[v1][v2][v3]concat=n=3:v=1:a=0 -b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast output.mp4" }, { "code": null, "e": 69069, "s": 68827, "text": "-y -i input.mp4 -filter_complex [0:v]trim=0:0,setpts=PTS-STARTPTS[v1];[0:v]trim=0:5,setpts=0.5*(PTS-STARTPTS)[v2];[0:v]trim=5,setpts=PTS-STARTPTS[v3];[v1][v2][v3]concat=n=3:v=1:a=0 -b:v 2097k -vcodec mpeg4 -crf 0 -preset superfast output.mp4" }, { "code": null, "e": 69214, "s": 69069, "text": "Textoverlay:-y -i input.mp4 -vf drawtext=”fontsize=30:fontfile=cute.ttf:text=’GFG'”:x=w-tw-10:y=h-th-10 -c:v libx264 -preset ultrafast outputmp4" }, { "code": null, "e": 69347, "s": 69214, "text": "-y -i input.mp4 -vf drawtext=”fontsize=30:fontfile=cute.ttf:text=’GFG'”:x=w-tw-10:y=h-th-10 -c:v libx264 -preset ultrafast outputmp4" }, { "code": null, "e": 69655, "s": 69347, "text": "gif/png/jpeg overlay-i input.mp4 -i inputimage.png -filter_complex [1:v]scale=320:394[ovr1],[0:v][ovr1]overlay=0:0:enable=’between(t,0,16)’ -c:a copy output.mp4, (or)-i input.mp4 -i inputimage.png -filter_complex overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2:enable=’between(t,0,7)’ -c:a copy output.mp4" }, { "code": null, "e": 69802, "s": 69655, "text": "-i input.mp4 -i inputimage.png -filter_complex [1:v]scale=320:394[ovr1],[0:v][ovr1]overlay=0:0:enable=’between(t,0,16)’ -c:a copy output.mp4, (or)" }, { "code": null, "e": 69944, "s": 69802, "text": "-i input.mp4 -i inputimage.png -filter_complex overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2:enable=’between(t,0,7)’ -c:a copy output.mp4" }, { "code": null, "e": 70074, "s": 69944, "text": "Add subtitles to a video file-i input.mp4 -i subtitle.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset superfast output.mp4" }, { "code": null, "e": 70175, "s": 70074, "text": "-i input.mp4 -i subtitle.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset superfast output.mp4" }, { "code": null, "e": 70240, "s": 70175, "text": "Converting video files to audio files-i input.mp4 -vn output.mp3" }, { "code": null, "e": 70268, "s": 70240, "text": "-i input.mp4 -vn output.mp3" }, { "code": null, "e": 70521, "s": 70268, "text": "Cropping videos-i input.mp4 -filter:v “crop=w:h:x:y” output.mp4w – width of the rectangle which we are intended to crop from the source video.h – the height of that rectangle.x – the x coordinate of that rectangle.y – the y coordinate of the rectangle." }, { "code": null, "e": 70759, "s": 70521, "text": "-i input.mp4 -filter:v “crop=w:h:x:y” output.mp4w – width of the rectangle which we are intended to crop from the source video.h – the height of that rectangle.x – the x coordinate of that rectangle.y – the y coordinate of the rectangle." }, { "code": null, "e": 70839, "s": 70759, "text": "w – width of the rectangle which we are intended to crop from the source video." }, { "code": null, "e": 70873, "s": 70839, "text": "h – the height of that rectangle." }, { "code": null, "e": 70913, "s": 70873, "text": "x – the x coordinate of that rectangle." }, { "code": null, "e": 70952, "s": 70913, "text": "y – the y coordinate of the rectangle." }, { "code": null, "e": 71106, "s": 70952, "text": "Adding a poster image to audio files-loop 1 -i inputimage.jpg -i inputaudio.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest output.mp4" }, { "code": null, "e": 71224, "s": 71106, "text": "-loop 1 -i inputimage.jpg -i inputaudio.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest output.mp4" }, { "code": null, "e": 71462, "s": 71224, "text": "It is also highly portable.It is profoundly valuable for the transcoding of all kinds of multimedia files into a single common format.You don’t need heavy Third-party VideoEditors like Adobe Premiere Pro, Filmora for small editing tasks." }, { "code": null, "e": 71490, "s": 71462, "text": "It is also highly portable." }, { "code": null, "e": 71598, "s": 71490, "text": "It is profoundly valuable for the transcoding of all kinds of multimedia files into a single common format." }, { "code": null, "e": 71702, "s": 71598, "text": "You don’t need heavy Third-party VideoEditors like Adobe Premiere Pro, Filmora for small editing tasks." }, { "code": null, "e": 72021, "s": 71702, "text": "It’s difficult for beginners to use and implement.It takes some time to process. We don’t get results in a second or two.The official documentation is quite confusing and it’s not beginner-friendly.APK size becomes very large. The FFmpeg libraries alone will use 30-70MB depending upon the libraries you are including." }, { "code": null, "e": 72072, "s": 72021, "text": "It’s difficult for beginners to use and implement." }, { "code": null, "e": 72144, "s": 72072, "text": "It takes some time to process. We don’t get results in a second or two." }, { "code": null, "e": 72222, "s": 72144, "text": "The official documentation is quite confusing and it’s not beginner-friendly." }, { "code": null, "e": 72343, "s": 72222, "text": "APK size becomes very large. The FFmpeg libraries alone will use 30-70MB depending upon the libraries you are including." }, { "code": null, "e": 72362, "s": 72343, "text": "MediaCodec Android" }, { "code": null, "e": 72367, "s": 72362, "text": "LiTr" }, { "code": null, "e": 72377, "s": 72367, "text": "Gstreamer" }, { "code": null, "e": 72387, "s": 72377, "text": "MP4Parser" }, { "code": null, "e": 72415, "s": 72387, "text": "Intel INDE Media for Mobile" }, { "code": null, "e": 72422, "s": 72415, "text": "Notes:" }, { "code": null, "e": 72621, "s": 72422, "text": "1. If you set -preset to a higher value say, ultrafast then the video processing will be fast but the quality of the video will be compromised. The lower the -preset higher the quality of the video." }, { "code": null, "e": 72750, "s": 72621, "text": "2. You can change the -crf value to change the quality of the output video. Lower the crf value higher the quality of the video." }, { "code": null, "e": 72929, "s": 72750, "text": "3. If you use -y in starting of command then this means that if a file is present with the same name as that of the output file name that FFmpeg will overwrite the existing file." }, { "code": null, "e": 73210, "s": 72929, "text": "4. In the case of video, to slow down the video set -PTS value larger than 1. The larger the value slower the video, Lower the value Faster the video. But in the case of Audio this is just the opposite, i.e. Larger the value faster the Audio, the Lower the value slower the audio." }, { "code": null, "e": 73397, "s": 73210, "text": "5. The atempo(audio) filter is limited to using values between 0.5 and 2.0 (so it can slow it down to no less than half the original speed, and speed up to no more than double the input)" }, { "code": null, "e": 73636, "s": 73397, "text": "6. FFmpeg takes too much time working with audio. If the video file doesn’t contain the audio we need not to command FFmpeg to work with audio, and hence this will reduce the workload and we will get the processed video fast/in less time." }, { "code": null, "e": 73651, "s": 73636, "text": "varshagumber28" }, { "code": null, "e": 73666, "s": 73651, "text": "prachisoda1234" }, { "code": null, "e": 73674, "s": 73666, "text": "android" }, { "code": null, "e": 73698, "s": 73674, "text": "Technical Scripter 2020" }, { "code": null, "e": 73706, "s": 73698, "text": "Android" }, { "code": null, "e": 73711, "s": 73706, "text": "Java" }, { "code": null, "e": 73730, "s": 73711, "text": "Technical Scripter" }, { "code": null, "e": 73735, "s": 73730, "text": "Java" }, { "code": null, "e": 73743, "s": 73735, "text": "Android" }, { "code": null, "e": 73841, "s": 73743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 73850, "s": 73841, "text": "Comments" }, { "code": null, "e": 73863, "s": 73850, "text": "Old Comments" }, { "code": null, "e": 73906, "s": 73863, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 73964, "s": 73906, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 74006, "s": 73964, "text": "Content Providers in Android with Example" }, { "code": null, "e": 74037, "s": 74006, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 74066, "s": 74037, "text": "Navigation Drawer in Android" }, { "code": null, "e": 74081, "s": 74066, "text": "Arrays in Java" }, { "code": null, "e": 74125, "s": 74081, "text": "Split() String method in Java with examples" }, { "code": null, "e": 74147, "s": 74125, "text": "For-each loop in Java" }, { "code": null, "e": 74172, "s": 74147, "text": "Reverse a string in Java" } ]
How to pass data from Parent to Child component in Angular ? - GeeksforGeeks
12 Mar, 2021 We can use the @Input directive for passing the data from the Parent to Child component in Angular Using Input Binding: @Input – We can use this directive inside the child component to access the data sent by the parent component. Here app.component is the Parent component and cdetail.component is the child component. app.component.ts There are two arrays. One for list_prog – list of languages, prog_details – details of languages. app.component.ts import { Component } from '@angular/core';import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { list_prog = ['JAVA', 'C++', 'C', 'PYTHON', 'JAVASCRIPT']; prog_details = [`Java is a widely used platform independent language. Java was developed by James Gosling.`, `C++ is multi-paradigm and procedural oriented language. Developed by Bjarne Stroustrup.`, `C is a procedural language and developed by Dennis Ritchie`, `Python is a interpreted high level language developed by Guido van Rossum`, `Javascript is a language that conforms the ECMAScript and developed by ECMAScript`]; options: number; curr_info: string; prog_title: string; constructor() {} onClick(lang) { switch (lang) { case 'JAVA': this.options = 0; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'C++': this.options = 1; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'C': this.options = 2; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'PYTHON': this.options = 3; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'JAVASCRIPT': this.options = 4; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; default: break; } }} app.component.html Here we have added our child component inside the parent component and pass two data one is prog_title and another is curr_info. But make sure you have already declared variable details and title inside the child component. HTML <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h4 class="makeCenter"> List of Programming Languages </h4> <ul class="uList"> <li *ngFor="let lang of list_prog" [ngClass]= "{'active': list_prog[options]===lang}" (click)="onClick(lang)" class="lLang"> {{lang}} </li> </ul> </div> </div></div><br><br><br><app-cdetail [title]="prog_title" [details]="curr_info"></app-cdetail> cdetail.component.ts Here we have used the @Input() directive inside the child component. Now in the child component, the data passed by the parent component can be used. Javascript import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-cdetail', templateUrl: './cdetail.component.html', styleUrls: ['./cdetail.component.css']})export class CdetailComponent implements OnInit { @Input() details: string; @Input() title: string; constructor() { } ngOnInit(): void { } } cdetail.component.html HTML <div class="container"> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <h3 class="makeCenter">{{title}}</h3> <p style="text-align: justify; text-justify: inter-word;"> {{details}} </p> </div> </div></div> AngularJS-Questions Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n12 Mar, 2021" }, { "code": null, "e": 25208, "s": 25109, "text": "We can use the @Input directive for passing the data from the Parent to Child component in Angular" }, { "code": null, "e": 25429, "s": 25208, "text": "Using Input Binding: @Input – We can use this directive inside the child component to access the data sent by the parent component. Here app.component is the Parent component and cdetail.component is the child component." }, { "code": null, "e": 25544, "s": 25429, "text": "app.component.ts There are two arrays. One for list_prog – list of languages, prog_details – details of languages." }, { "code": null, "e": 25561, "s": 25544, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { list_prog = ['JAVA', 'C++', 'C', 'PYTHON', 'JAVASCRIPT']; prog_details = [`Java is a widely used platform independent language. Java was developed by James Gosling.`, `C++ is multi-paradigm and procedural oriented language. Developed by Bjarne Stroustrup.`, `C is a procedural language and developed by Dennis Ritchie`, `Python is a interpreted high level language developed by Guido van Rossum`, `Javascript is a language that conforms the ECMAScript and developed by ECMAScript`]; options: number; curr_info: string; prog_title: string; constructor() {} onClick(lang) { switch (lang) { case 'JAVA': this.options = 0; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'C++': this.options = 1; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'C': this.options = 2; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'PYTHON': this.options = 3; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; case 'JAVASCRIPT': this.options = 4; this.curr_info = this.prog_details[this.options]; this.prog_title = this.list_prog[this.options]; break; default: break; } }}", "e": 27815, "s": 25561, "text": null }, { "code": null, "e": 28058, "s": 27815, "text": "app.component.html Here we have added our child component inside the parent component and pass two data one is prog_title and another is curr_info. But make sure you have already declared variable details and title inside the child component." }, { "code": null, "e": 28063, "s": 28058, "text": "HTML" }, { "code": "<div class=\"container\"> <div class=\"row\"> <div class=\"col-md-3\"></div> <div class=\"col-md-6\"> <h4 class=\"makeCenter\"> List of Programming Languages </h4> <ul class=\"uList\"> <li *ngFor=\"let lang of list_prog\" [ngClass]= \"{'active': list_prog[options]===lang}\" (click)=\"onClick(lang)\" class=\"lLang\"> {{lang}} </li> </ul> </div> </div></div><br><br><br><app-cdetail [title]=\"prog_title\" [details]=\"curr_info\"></app-cdetail>", "e": 28661, "s": 28063, "text": null }, { "code": null, "e": 28832, "s": 28661, "text": "cdetail.component.ts Here we have used the @Input() directive inside the child component. Now in the child component, the data passed by the parent component can be used." }, { "code": null, "e": 28843, "s": 28832, "text": "Javascript" }, { "code": "import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-cdetail', templateUrl: './cdetail.component.html', styleUrls: ['./cdetail.component.css']})export class CdetailComponent implements OnInit { @Input() details: string; @Input() title: string; constructor() { } ngOnInit(): void { } }", "e": 29177, "s": 28843, "text": null }, { "code": null, "e": 29200, "s": 29177, "text": "cdetail.component.html" }, { "code": null, "e": 29205, "s": 29200, "text": "HTML" }, { "code": "<div class=\"container\"> <div class=\"row\"> <div class=\"col-md-4\"></div> <div class=\"col-md-4\"> <h3 class=\"makeCenter\">{{title}}</h3> <p style=\"text-align: justify; text-justify: inter-word;\"> {{details}} </p> </div> </div></div>", "e": 29524, "s": 29205, "text": null }, { "code": null, "e": 29544, "s": 29524, "text": "AngularJS-Questions" }, { "code": null, "e": 29551, "s": 29544, "text": "Picked" }, { "code": null, "e": 29561, "s": 29551, "text": "AngularJS" }, { "code": null, "e": 29578, "s": 29561, "text": "Web Technologies" }, { "code": null, "e": 29676, "s": 29578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29685, "s": 29676, "text": "Comments" }, { "code": null, "e": 29698, "s": 29685, "text": "Old Comments" }, { "code": null, "e": 29742, "s": 29698, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29806, "s": 29742, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 29859, "s": 29806, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29883, "s": 29859, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29918, "s": 29883, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29960, "s": 29918, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29993, "s": 29960, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30036, "s": 29993, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30098, "s": 30036, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How can I get the list of files in a directory using C/C++?
Standard C++ doesn't provide a way to do this. You could use the system command to initialize the ls command as follows − #include<iostream> int main () { char command[50] = "ls -l"; system(command); return 0; } This will give the output − -rwxrwxrwx 1 root root 9728 Feb 25 20:51 a.out -rwxrwxrwx 1 root root 131 Feb 25 20:44 hello.cpp -rwxrwxrwx 1 root root 243 Sep 7 13:09 hello.py -rwxrwxrwx 1 root root 33198 Jan 7 11:42 hello.o drwxrwxrwx 0 root root 512 Oct 1 21:40 hydeout -rwxrwxrwx 1 root root 42 Oct 21 11:29 my_file.txt -rwxrwxrwx 1 root root 527 Oct 21 11:29 watch.py If you're on windows, you can use dir instead of ls to display the list. You can use the direct package(https://github.com/tronkko/dirent) to use a much more flexible API. You can use it as follows to get a list of files − #include <iostream> #include <dirent.h> #include <sys/types.h> using namespace std; void list_dir(const char *path) { struct dirent *entry; DIR *dir = opendir(path); if (dir == NULL) { return; } while ((entry = readdir(dir)) != NULL) { cout << entry->d_name << endl; } closedir(dir); } int main() { list_dir("/home/username/Documents"); } This will give the output − a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
[ { "code": null, "e": 1184, "s": 1062, "text": "Standard C++ doesn't provide a way to do this. You could use the system command to initialize the ls command as follows −" }, { "code": null, "e": 1283, "s": 1184, "text": "#include<iostream>\nint main () {\n char command[50] = \"ls -l\";\n system(command);\n return 0;\n}" }, { "code": null, "e": 1311, "s": 1283, "text": "This will give the output −" }, { "code": null, "e": 1667, "s": 1311, "text": "-rwxrwxrwx 1 root root 9728 Feb 25 20:51 a.out\n-rwxrwxrwx 1 root root 131 Feb 25 20:44 hello.cpp\n-rwxrwxrwx 1 root root 243 Sep 7 13:09 hello.py\n-rwxrwxrwx 1 root root 33198 Jan 7 11:42 hello.o\ndrwxrwxrwx 0 root root 512 Oct 1 21:40 hydeout\n-rwxrwxrwx 1 root root 42 Oct 21 11:29 my_file.txt\n-rwxrwxrwx 1 root root 527 Oct 21 11:29 watch.py" }, { "code": null, "e": 1740, "s": 1667, "text": "If you're on windows, you can use dir instead of ls to display the list." }, { "code": null, "e": 1890, "s": 1740, "text": "You can use the direct package(https://github.com/tronkko/dirent) to use a much more flexible API. You can use it as follows to get a list of files −" }, { "code": null, "e": 2267, "s": 1890, "text": "#include <iostream>\n#include <dirent.h>\n#include <sys/types.h>\n\nusing namespace std;\nvoid list_dir(const char *path) {\n struct dirent *entry;\n DIR *dir = opendir(path);\n \n if (dir == NULL) {\n return;\n }\n while ((entry = readdir(dir)) != NULL) {\n cout << entry->d_name << endl;\n }\n closedir(dir);\n}\nint main() {\n list_dir(\"/home/username/Documents\");\n}" }, { "code": null, "e": 2295, "s": 2267, "text": "This will give the output −" }, { "code": null, "e": 2357, "s": 2295, "text": "a.out\nhello.cpp\nhello.py\nhello.o\nhydeout\nmy_file.txt\nwatch.py" } ]
Tryit Editor v3.7
CSS Text Effects Tryit: The word-break property
[ { "code": null, "e": 26, "s": 9, "text": "CSS Text Effects" } ]
Sorting a VARCHAR column as FLOAT using the CAST operator isn’t working in MySQL ?
If your cast does not work, then you can use yourColumnName*1 with ORDER BY clause. Using yourColumnName*1. The syntax is as follows: SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY yourColumnName*1 DESC; You can also use CAST() operator. The syntax is as follows: SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY CAST(yourColumnName as DECIMAL(8,2)) DESC; To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table VarcharColumnAsFloatDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Amount varchar(20), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.01 sec) Insert some records in the table using insert command. The query is as follows: mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3446.23'); Query OK, 1 row affected (0.10 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('2464.46'); Query OK, 1 row affected (0.16 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.78'); Query OK, 1 row affected (0.13 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6464.98'); Query OK, 1 row affected (0.44 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('645.90'); Query OK, 1 row affected (0.19 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.99'); Query OK, 1 row affected (0.23 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3745.76'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from VarcharColumnAsFloatDemo; The following is the output: +----+---------+ | Id | Amount | +----+---------+ | 1 | 3446.23 | | 2 | 2464.46 | | 3 | 6465.78 | | 4 | 6464.98 | | 5 | 645.90 | | 6 | 6465.99 | | 7 | 3745.76 | +----+---------+ 7 rows in set (0.00 sec) Here is the query to sort varchar as float using cast operator: mysql> select Id,Amount from VarcharColumnAsFloatDemo order by cast(Amount as DECIMAL(8,2)) DESC; The following is the output: +----+---------+ | Id | Amount | +----+---------+ | 6 | 6465.99 | | 3 | 6465.78 | | 4 | 6464.98 | | 7 | 3745.76 | | 1 | 3446.23 | | 2 | 2464.46 | | 5 | 645.90 | +----+---------+ 7 rows in set (0.00 sec) The second approach is as follows using yourColumnName*1: mysql> select Id,Amount from VarcharColumnAsFloatDemo order by Amount*1 desc; The following is the output: +----+---------+ | Id | Amount | +----+---------+ | 6 | 6465.99 | | 3 | 6465.78 | | 4 | 6464.98 | | 7 | 3745.76 | | 1 | 3446.23 | | 2 | 2464.46 | | 5 | 645.90 | +----+---------+ 7 rows in set (0.00 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "If your cast does not work, then you can use yourColumnName*1 with ORDER BY clause." }, { "code": null, "e": 1196, "s": 1146, "text": "Using yourColumnName*1. The syntax is as follows:" }, { "code": null, "e": 1291, "s": 1196, "text": "SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY yourColumnName*1 DESC;" }, { "code": null, "e": 1351, "s": 1291, "text": "You can also use CAST() operator. The syntax is as follows:" }, { "code": null, "e": 1466, "s": 1351, "text": "SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY CAST(yourColumnName as DECIMAL(8,2)) DESC;" }, { "code": null, "e": 1564, "s": 1466, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1749, "s": 1564, "text": "mysql> create table VarcharColumnAsFloatDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Amount varchar(20),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.01 sec)" }, { "code": null, "e": 1829, "s": 1749, "text": "Insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2577, "s": 1829, "text": "mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3446.23');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into VarcharColumnAsFloatDemo(Amount) values('2464.46');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.78');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into VarcharColumnAsFloatDemo(Amount) values('6464.98');\nQuery OK, 1 row affected (0.44 sec)\nmysql> insert into VarcharColumnAsFloatDemo(Amount) values('645.90');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.99');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into VarcharColumnAsFloatDemo(Amount) values('3745.76');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2661, "s": 2577, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2707, "s": 2661, "text": "mysql> select *from VarcharColumnAsFloatDemo;" }, { "code": null, "e": 2736, "s": 2707, "text": "The following is the output:" }, { "code": null, "e": 2948, "s": 2736, "text": "+----+---------+\n| Id | Amount |\n+----+---------+\n| 1 | 3446.23 |\n| 2 | 2464.46 |\n| 3 | 6465.78 |\n| 4 | 6464.98 |\n| 5 | 645.90 |\n| 6 | 6465.99 |\n| 7 | 3745.76 |\n+----+---------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3012, "s": 2948, "text": "Here is the query to sort varchar as float using cast operator:" }, { "code": null, "e": 3110, "s": 3012, "text": "mysql> select Id,Amount from VarcharColumnAsFloatDemo order by cast(Amount as DECIMAL(8,2)) DESC;" }, { "code": null, "e": 3139, "s": 3110, "text": "The following is the output:" }, { "code": null, "e": 3351, "s": 3139, "text": "+----+---------+\n| Id | Amount |\n+----+---------+\n| 6 | 6465.99 |\n| 3 | 6465.78 |\n| 4 | 6464.98 |\n| 7 | 3745.76 |\n| 1 | 3446.23 |\n| 2 | 2464.46 |\n| 5 | 645.90 |\n+----+---------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3409, "s": 3351, "text": "The second approach is as follows using yourColumnName*1:" }, { "code": null, "e": 3487, "s": 3409, "text": "mysql> select Id,Amount from VarcharColumnAsFloatDemo order by Amount*1 desc;" }, { "code": null, "e": 3516, "s": 3487, "text": "The following is the output:" }, { "code": null, "e": 3728, "s": 3516, "text": "+----+---------+\n| Id | Amount |\n+----+---------+\n| 6 | 6465.99 |\n| 3 | 6465.78 |\n| 4 | 6464.98 |\n| 7 | 3745.76 |\n| 1 | 3446.23 |\n| 2 | 2464.46 |\n| 5 | 645.90 |\n+----+---------+\n7 rows in set (0.00 sec)" } ]
HTML DOM Marquee Object - GeeksforGeeks
10 Mar, 2022 The HTML DOM Marquee Object is used to to represent the HTML <marquee> tag. We know that the <marquee> tag is used to move the content from horizontal to vertical or left to right or right to left. Syntax It is used to access the marquee tag.document.getElementById("id"); It is used to access the marquee tag. document.getElementById("id"); It is used to create a marquee tag.document.createElement("MARQUEE"); It is used to create a marquee tag. document.createElement("MARQUEE"); Property values: bgcolor: It is used to set or return the value of the background color of the <marquee> tag. behavior: It is used to set or return the value of the behavior attribute of the <marquee> tag. scrollamount: It is used to set or return the speed of the <marquee> tag. direction: It is used to set or return the value of the direction attribute of the <marquee> tag. loop: It is used to set or return the value of the loop attribute of the <marquee> tag. height: It is used to set or return the height of the <marquee> tag. width: It is used to set or return the height of the <marquee> tag. hspace: It is used to set or return the space of the <marquee> tag. vspace: It is used to set or return the vspace of the <marquee> tag. scrollDelay : It is used to set or return the value of the scrolldelay attribute of a <marquee> Tag. truespeed : It is used to set or return the value of the truespeed attribute of the <marquee> Tag. Methods start (): This method is used to start the scrolling of the Marquee Tag. stop (): This method is used to stop the scrolling of the Marquee Tag. Example 1: Below HTML code illustrates how to create a marquee object. HTML <!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Marquee Object</h2> <b> Click on the below button to create a marquee object </b> <p></p> <button onclick="createMarqueObject()"> Create Marquee Object </button> <script> function createMarqueObject() { var elementVar = document.createElement("MARQUEE"); var txt = document.createTextNode( "GeeksforGeeks:A computer Science Portal for Geek"); elementVar.appendChild(txt); document.body.appendChild(elementVar); } </script></body> </html> Output: Example 2: Below HTML code illustrates how to change the background color and font size of the marquee element. HTML <!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Marquee Object</h2> <marquee id="marqueeID"> GeeksforGeeks:A computer Science Portal for Geeks </marquee> <br><br> <button onclick="btnClick()"> Change BackGround Color </button> <script> function btnClick() { var txt = document.getElementById("marqueeID"); txt.style.backgroundColor = "green"; txt.style.fontSize = "25px"; } </script></body> </html> Output: Supported browsers: Google Chrome 1.0 Edge 12.0 Firefox 65.0 Internet Explorer 2.0 Opera 7.2 Safari 1.2 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 chhabradhanvi HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery How to auto-resize an image to fit a div container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24919, "s": 24891, "text": "\n10 Mar, 2022" }, { "code": null, "e": 25118, "s": 24919, "text": "The HTML DOM Marquee Object is used to to represent the HTML <marquee> tag. We know that the <marquee> tag is used to move the content from horizontal to vertical or left to right or right to left. " }, { "code": null, "e": 25125, "s": 25118, "text": "Syntax" }, { "code": null, "e": 25195, "s": 25125, "text": "It is used to access the marquee tag.document.getElementById(\"id\"); " }, { "code": null, "e": 25233, "s": 25195, "text": "It is used to access the marquee tag." }, { "code": null, "e": 25266, "s": 25233, "text": "document.getElementById(\"id\"); " }, { "code": null, "e": 25336, "s": 25266, "text": "It is used to create a marquee tag.document.createElement(\"MARQUEE\");" }, { "code": null, "e": 25372, "s": 25336, "text": "It is used to create a marquee tag." }, { "code": null, "e": 25407, "s": 25372, "text": "document.createElement(\"MARQUEE\");" }, { "code": null, "e": 25426, "s": 25409, "text": "Property values:" }, { "code": null, "e": 25519, "s": 25426, "text": "bgcolor: It is used to set or return the value of the background color of the <marquee> tag." }, { "code": null, "e": 25615, "s": 25519, "text": "behavior: It is used to set or return the value of the behavior attribute of the <marquee> tag." }, { "code": null, "e": 25689, "s": 25615, "text": "scrollamount: It is used to set or return the speed of the <marquee> tag." }, { "code": null, "e": 25787, "s": 25689, "text": "direction: It is used to set or return the value of the direction attribute of the <marquee> tag." }, { "code": null, "e": 25875, "s": 25787, "text": "loop: It is used to set or return the value of the loop attribute of the <marquee> tag." }, { "code": null, "e": 25944, "s": 25875, "text": "height: It is used to set or return the height of the <marquee> tag." }, { "code": null, "e": 26012, "s": 25944, "text": "width: It is used to set or return the height of the <marquee> tag." }, { "code": null, "e": 26080, "s": 26012, "text": "hspace: It is used to set or return the space of the <marquee> tag." }, { "code": null, "e": 26149, "s": 26080, "text": "vspace: It is used to set or return the vspace of the <marquee> tag." }, { "code": null, "e": 26250, "s": 26149, "text": "scrollDelay : It is used to set or return the value of the scrolldelay attribute of a <marquee> Tag." }, { "code": null, "e": 26349, "s": 26250, "text": "truespeed : It is used to set or return the value of the truespeed attribute of the <marquee> Tag." }, { "code": null, "e": 26357, "s": 26349, "text": "Methods" }, { "code": null, "e": 26430, "s": 26357, "text": "start (): This method is used to start the scrolling of the Marquee Tag." }, { "code": null, "e": 26501, "s": 26430, "text": "stop (): This method is used to stop the scrolling of the Marquee Tag." }, { "code": null, "e": 26573, "s": 26501, "text": "Example 1: Below HTML code illustrates how to create a marquee object. " }, { "code": null, "e": 26578, "s": 26573, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Marquee Object</h2> <b> Click on the below button to create a marquee object </b> <p></p> <button onclick=\"createMarqueObject()\"> Create Marquee Object </button> <script> function createMarqueObject() { var elementVar = document.createElement(\"MARQUEE\"); var txt = document.createTextNode( \"GeeksforGeeks:A computer Science Portal for Geek\"); elementVar.appendChild(txt); document.body.appendChild(elementVar); } </script></body> </html>", "e": 27286, "s": 26578, "text": null }, { "code": null, "e": 27294, "s": 27286, "text": "Output:" }, { "code": null, "e": 27406, "s": 27294, "text": "Example 2: Below HTML code illustrates how to change the background color and font size of the marquee element." }, { "code": null, "e": 27411, "s": 27406, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Marquee Object</h2> <marquee id=\"marqueeID\"> GeeksforGeeks:A computer Science Portal for Geeks </marquee> <br><br> <button onclick=\"btnClick()\"> Change BackGround Color </button> <script> function btnClick() { var txt = document.getElementById(\"marqueeID\"); txt.style.backgroundColor = \"green\"; txt.style.fontSize = \"25px\"; } </script></body> </html>", "e": 27987, "s": 27411, "text": null }, { "code": null, "e": 27995, "s": 27987, "text": "Output:" }, { "code": null, "e": 28015, "s": 27995, "text": "Supported browsers:" }, { "code": null, "e": 28033, "s": 28015, "text": "Google Chrome 1.0" }, { "code": null, "e": 28043, "s": 28033, "text": "Edge 12.0" }, { "code": null, "e": 28056, "s": 28043, "text": "Firefox 65.0" }, { "code": null, "e": 28078, "s": 28056, "text": "Internet Explorer 2.0" }, { "code": null, "e": 28088, "s": 28078, "text": "Opera 7.2" }, { "code": null, "e": 28099, "s": 28088, "text": "Safari 1.2" }, { "code": null, "e": 28236, "s": 28099, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28256, "s": 28236, "text": "hritikbhatnagar2182" }, { "code": null, "e": 28270, "s": 28256, "text": "chhabradhanvi" }, { "code": null, "e": 28279, "s": 28270, "text": "HTML-DOM" }, { "code": null, "e": 28284, "s": 28279, "text": "HTML" }, { "code": null, "e": 28301, "s": 28284, "text": "Web Technologies" }, { "code": null, "e": 28306, "s": 28301, "text": "HTML" }, { "code": null, "e": 28404, "s": 28306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28428, "s": 28404, "text": "REST API (Introduction)" }, { "code": null, "e": 28465, "s": 28428, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28485, "s": 28465, "text": "Angular File Upload" }, { "code": null, "e": 28514, "s": 28485, "text": "Form validation using jQuery" }, { "code": null, "e": 28576, "s": 28514, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 28618, "s": 28576, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28651, "s": 28618, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28694, "s": 28651, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28739, "s": 28694, "text": "Convert a string to an integer in JavaScript" } ]
Can we cast a double value to a byte in java?
Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects). Converting one primitive data type into another is known as type casting. There are two types of casting − Widening− Converting a lower datatype to a higher datatype is known as widening. It is done implicitly. Narrowing− Converting a higher datatype to a lower datatype is known as narrowing. You need to do it explicitly using the cast operator (“( )”). Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator. Live Demo import java.util.Scanner; public class CastingExample { public static void main(String args[]){ //Reading a double value form user Scanner sc = new Scanner(System.in); System.out.println("Enter a double value: "); double d = sc.nextDouble(); //Converting the double value to byte byte by = (byte) d; //Printing the result System.out.println("byte value: "+by); } } Enter a double value: 102.365 byte value: 102
[ { "code": null, "e": 1289, "s": 1062, "text": "Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects)." }, { "code": null, "e": 1396, "s": 1289, "text": "Converting one primitive data type into another is known as type casting. There are two types of casting −" }, { "code": null, "e": 1500, "s": 1396, "text": "Widening− Converting a lower datatype to a higher datatype is known as widening. It is done implicitly." }, { "code": null, "e": 1645, "s": 1500, "text": "Narrowing− Converting a higher datatype to a lower datatype is known as narrowing. You need to do it explicitly using the cast operator (“( )”)." }, { "code": null, "e": 1807, "s": 1645, "text": "Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator." }, { "code": null, "e": 1818, "s": 1807, "text": " Live Demo" }, { "code": null, "e": 2237, "s": 1818, "text": "import java.util.Scanner;\npublic class CastingExample {\n public static void main(String args[]){\n //Reading a double value form user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a double value: \");\n double d = sc.nextDouble();\n //Converting the double value to byte\n byte by = (byte) d;\n //Printing the result\n System.out.println(\"byte value: \"+by);\n }\n}" }, { "code": null, "e": 2283, "s": 2237, "text": "Enter a double value:\n102.365\nbyte value: 102" } ]
R Statistics Data Set
A data set is a collection of data, often presented in a table. There is a popular built-in data set in R called "mtcars" (Motor Trend Car Road Tests), which is retrieved from the 1974 Motor Trend US Magazine. In the examples below (and for the next chapters), we will use the mtcars data set, for statistical purposes: Result: mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 You can use the question mark (?) to get information about the mtcars data set: Result: The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973-74 models). mtcars A data frame with 32 observations on 11 (numeric) variables. Henderson and Velleman (1981) comment in a footnote to Table 1: 'Hocking [original transcriber]'s noncrucial coding of the Mazda's rotary engine as a straight six-cylinder engine and the Porsche's flat engine as a V engine, as well as the inclusion of the diesel Mercedes 240D, have been retained to enable direct comparisons to be made with previous analyses.' Henderson and Velleman (1981), Building multiple regression models interactively. Biometrics, 37, 391-411. require(graphics) pairs(mtcars, main = "mtcars data", gap = 1/4) coplot(mpg ~ disp | as.factor(cyl), data = mtcars, panel = panel.smooth, rows = 1) ## possibly more meaningful, e.g., for summary() or bivariate plots: mtcars2 <- within(mtcars, { vs <- factor(vs, labels = c("V", "S")) am <- factor(am, labels = c("automatic", "manual")) cyl <- ordered(cyl) gear <- ordered(gear) carb <- ordered(carb) }) summary(mtcars2) Use the dim() function to find the dimensions of the data set, and the names() function to view the names of the variables: Result: [1] 32 11 [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" [11] "carb" Use the rownames() function to get the name of each row in the first column, which is the name of each car: Result: [1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" [4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant" [7] "Duster 360" "Merc 240D" "Merc 230" [10] "Merc 280" "Merc 280C" "Merc 450SE" [13] "Merc 450SL" "Merc 450SLC" "Cadillac Fleetwood" [16] "Lincoln Continental" "Chrysler Imperial" "Fiat 128" [19] "Honda Civic" "Toyota Corolla" "Toyota Corona" [22] "Dodge Challenger" "AMC Javelin" "Camaro Z28" [25] "Pontiac Firebird" "Fiat X1-9" "Porsche 914-2" [28] "Lotus Europa" "Ford Pantera L" "Ferrari Dino" [31] "Maserati Bora" "Volvo 142E" From the examples above, we have found out that the data set has 32 observations (Mazda RX4, Mazda RX4 Wag, Datsun 710, etc) and 11 variables (mpg, cyl, disp, etc). A variable is defined as something that can be measured or counted. Here is a brief explanation of the variables from the mtcars data set: If you want to print all values that belong to a variable, access the data frame by using the $ sign, and the name of the variable (for example cyl (cylinders)): Result: [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4 To sort the values, use the sort() function: Result: [1] 4 4 4 4 4 4 4 4 4 4 4 6 6 6 6 6 6 6 8 8 8 8 8 8 8 8 8 8 8 8 8 8 From the examples above, we see that most cars have 4 and 8 cylinders. Now that we have some information about the data set, we can start to analyze it with some statistical numbers. For example, we can use the summary() function to get a statistical summary of the data: Do not worry if you do not understand the output numbers. You will master them shortly. The summary() function returns six statistical numbers for each variable: Min First quantile (percentile) Median Mean Third quantile (percentile) Max We will cover all of them, along with other statistical numbers in the next chapters. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 64, "s": 0, "text": "A data set is a collection of data, often presented in a table." }, { "code": null, "e": 211, "s": 64, "text": "There is a popular built-in data set in R called \"mtcars\" (Motor Trend Car Road Tests), which is \nretrieved from the 1974 Motor Trend US Magazine." }, { "code": null, "e": 322, "s": 211, "text": "In the examples below (and for the next chapters), we will use the mtcars \ndata set, for statistical purposes:" }, { "code": null, "e": 330, "s": 322, "text": "Result:" }, { "code": null, "e": 2707, "s": 330, "text": " mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1\nDuster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4\nMerc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2\nMerc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2\nMerc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4\nMerc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4\nMerc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3\nMerc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3\nMerc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3\nCadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4\nLincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4\nChrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4\nFiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1\nHonda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2\nToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1\nToyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1\nDodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2\nAMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2\nCamaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4\nPontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2\nFiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1\nPorsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2\nLotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2\nFord Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4\nFerrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6\nMaserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8\nVolvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2\n" }, { "code": null, "e": 2787, "s": 2707, "text": "You can use the question mark (?) to get information about the mtcars data set:" }, { "code": null, "e": 2795, "s": 2787, "text": "Result:" }, { "code": null, "e": 2978, "s": 2795, "text": "The data was extracted from the 1974 Motor Trend US magazine,\nand comprises fuel consumption and 10 aspects of\nautomobile design and performance for 32 automobiles (1973-74\nmodels).\n" }, { "code": null, "e": 2985, "s": 2978, "text": "mtcars" }, { "code": null, "e": 3047, "s": 2985, "text": "A data frame with 32 observations on 11 (numeric) variables.\n" }, { "code": null, "e": 3410, "s": 3047, "text": "Henderson and Velleman (1981) comment in a footnote to Table 1:\n'Hocking [original transcriber]'s noncrucial coding of the\nMazda's rotary engine as a straight six-cylinder engine and the\nPorsche's flat engine as a V engine, as well as the inclusion of the\ndiesel Mercedes 240D, have been retained to enable direct comparisons\nto be made with previous analyses.'\n" }, { "code": null, "e": 3518, "s": 3410, "text": "Henderson and Velleman (1981),\nBuilding multiple regression models interactively.\nBiometrics, 37, 391-411.\n" }, { "code": null, "e": 3962, "s": 3518, "text": "require(graphics)\npairs(mtcars, main = \"mtcars data\", gap = 1/4)\ncoplot(mpg ~ disp | as.factor(cyl), data = mtcars,\n panel = panel.smooth, rows = 1)\n## possibly more meaningful, e.g., for summary() or bivariate plots:\nmtcars2 <- within(mtcars, {\n vs <- factor(vs, labels = c(\"V\", \"S\"))\n am <- factor(am, labels = c(\"automatic\", \"manual\"))\n cyl <- ordered(cyl)\n gear <- ordered(gear)\n carb <- ordered(carb)\n})\nsummary(mtcars2)\n" }, { "code": null, "e": 4086, "s": 3962, "text": "Use the dim() function to find the dimensions of the data set, and the names() function to view the names of the\nvariables:" }, { "code": null, "e": 4094, "s": 4086, "text": "Result:" }, { "code": null, "e": 4192, "s": 4094, "text": "[1] 32 11\n [1] \"mpg\" \"cyl\" \"disp\" \"hp\" \"drat\" \"wt\" \"qsec\" \"vs\" \"am\" \"gear\"\n[11] \"carb\"\n" }, { "code": null, "e": 4300, "s": 4192, "text": "Use the rownames() function to get the name of each row in the first column, which is the name of each car:" }, { "code": null, "e": 4308, "s": 4300, "text": "Result:" }, { "code": null, "e": 5067, "s": 4308, "text": " [1] \"Mazda RX4\" \"Mazda RX4 Wag\" \"Datsun 710\" \n [4] \"Hornet 4 Drive\" \"Hornet Sportabout\" \"Valiant\" \n [7] \"Duster 360\" \"Merc 240D\" \"Merc 230\" \n[10] \"Merc 280\" \"Merc 280C\" \"Merc 450SE\" \n[13] \"Merc 450SL\" \"Merc 450SLC\" \"Cadillac Fleetwood\" \n[16] \"Lincoln Continental\" \"Chrysler Imperial\" \"Fiat 128\" \n[19] \"Honda Civic\" \"Toyota Corolla\" \"Toyota Corona\" \n[22] \"Dodge Challenger\" \"AMC Javelin\" \"Camaro Z28\" \n[25] \"Pontiac Firebird\" \"Fiat X1-9\" \"Porsche 914-2\" \n[28] \"Lotus Europa\" \"Ford Pantera L\" \"Ferrari Dino\" \n[31] \"Maserati Bora\" \"Volvo 142E\" " }, { "code": null, "e": 5234, "s": 5067, "text": "From the examples above, we have found out that the data set has 32 observations \n(Mazda RX4, Mazda RX4 Wag, Datsun 710, etc) and 11 variables \n(mpg, cyl, disp, etc)." }, { "code": null, "e": 5302, "s": 5234, "text": "A variable is defined as something that can be measured or counted." }, { "code": null, "e": 5373, "s": 5302, "text": "Here is a brief explanation of the variables from the mtcars data set:" }, { "code": null, "e": 5537, "s": 5373, "text": "If you want to print all values that belong to a variable, access the data \nframe by using the $ sign, and the name of the variable \n(for example cyl (cylinders)):" }, { "code": null, "e": 5545, "s": 5537, "text": "Result:" }, { "code": null, "e": 5614, "s": 5545, "text": " [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4" }, { "code": null, "e": 5659, "s": 5614, "text": "To sort the values, use the sort() function:" }, { "code": null, "e": 5667, "s": 5659, "text": "Result:" }, { "code": null, "e": 5736, "s": 5667, "text": " [1] 4 4 4 4 4 4 4 4 4 4 4 6 6 6 6 6 6 6 8 8 8 8 8 8 8 8 8 8 8 8 8 8" }, { "code": null, "e": 5807, "s": 5736, "text": "From the examples above, we see that most cars have 4 and 8 cylinders." }, { "code": null, "e": 5919, "s": 5807, "text": "Now that we have some information about the data set, we can start to analyze it with some statistical numbers." }, { "code": null, "e": 6008, "s": 5919, "text": "For example, we can use the summary() function to get a statistical summary of the data:" }, { "code": null, "e": 6096, "s": 6008, "text": "Do not worry if you do not understand the output numbers. You will master them shortly." }, { "code": null, "e": 6170, "s": 6096, "text": "The summary() function returns six statistical numbers for each variable:" }, { "code": null, "e": 6174, "s": 6170, "text": "Min" }, { "code": null, "e": 6202, "s": 6174, "text": "First quantile (percentile)" }, { "code": null, "e": 6209, "s": 6202, "text": "Median" }, { "code": null, "e": 6214, "s": 6209, "text": "Mean" }, { "code": null, "e": 6242, "s": 6214, "text": "Third quantile (percentile)" }, { "code": null, "e": 6246, "s": 6242, "text": "Max" }, { "code": null, "e": 6332, "s": 6246, "text": "We will cover all of them, along with other statistical numbers in the next chapters." }, { "code": null, "e": 6365, "s": 6332, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 6407, "s": 6365, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 6514, "s": 6407, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 6533, "s": 6514, "text": "[email protected]" } ]
How to handle the error “Text strings must be rendered within a <Text> component” in ReactNative?
While developing your app you can come across the error as stated above. Here is the code that gives the error − import React from "react"; import { Image , Text, View, StyleSheet } from "react-native"; export default class App extends React.Component { render() { return ( <View style={styles.container}> <Image style={styles.stretch} source={{ uri: 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png ', }} /> </View> ); } } const styles = StyleSheet.create({ container: { paddingTop: 50, paddingLeft: 50, }, stretch: { width: 200, height: 200, resizeMode: 'stretch', }, }); The error displayed on the screen is as follows − The error comes for the following reasons. Make sure you avoid those mistakes while coding in your app. The first cause for the error is because of bad indentation. It is very necessary that each component is indented properly. The child elements are indented properly inside the parent component. The second case is because of spaces left at the end of each component. Remove the spaces from the end of the screen and compile again. It will work fine. Please be careful when copy pasting the code from another source. You will encounter this error mostly in those cases. Let us now correct the code and check the output again. import React from "react"; import { Image , Text, View, StyleSheet } from "react-native"; export default class App extends React.Component { render() { return ( <View style={styles.container}> <Image style={styles.stretch} source={{uri: 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png '}} /> </View> ); } } const styles = StyleSheet.create({ container: { paddingTop: 50, paddingLeft: 50, }, stretch: { width: 200, height: 200, resizeMode: 'stretch', } });
[ { "code": null, "e": 1175, "s": 1062, "text": "While developing your app you can come across the error as stated above. Here is the\ncode that gives the error −" }, { "code": null, "e": 1845, "s": 1175, "text": "import React from \"react\";\nimport { Image , Text, View, StyleSheet } from \"react-native\";\nexport default class App extends React.Component {\n render() {\n return (\n <View style={styles.container}>\n <Image\n style={styles.stretch}\n source={{\n uri:\n 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png ',\n }}\n />\n </View>\n );\n }\n}\nconst styles = StyleSheet.create({\n container: {\n paddingTop: 50,\n paddingLeft: 50,\n },\n stretch: {\n width: 200,\n height: 200,\n resizeMode: 'stretch',\n },\n});" }, { "code": null, "e": 1895, "s": 1845, "text": "The error displayed on the screen is as follows −" }, { "code": null, "e": 1999, "s": 1895, "text": "The error comes for the following reasons. Make sure you avoid those mistakes while\ncoding in your app." }, { "code": null, "e": 2193, "s": 1999, "text": "The first cause for the error is because of bad indentation. It is very necessary that each\ncomponent is indented properly. The child elements are indented properly inside the\nparent component." }, { "code": null, "e": 2467, "s": 2193, "text": "The second case is because of spaces left at the end of each component. Remove the\nspaces from the end of the screen and compile again. It will work fine. Please be careful\nwhen copy pasting the code from another source. You will encounter this error mostly in\nthose cases." }, { "code": null, "e": 2523, "s": 2467, "text": "Let us now correct the code and check the output again." }, { "code": null, "e": 3123, "s": 2523, "text": "import React from \"react\";\nimport { Image , Text, View, StyleSheet } from \"react-native\";\nexport default class App extends React.Component {\n render() {\n return (\n <View style={styles.container}>\n <Image style={styles.stretch} source={{uri:\n 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png\n '}} />\n </View>\n );\n }\n}\nconst styles = StyleSheet.create({\n container: {\n paddingTop: 50,\n paddingLeft: 50,\n },\n stretch: {\n width: 200,\n height: 200,\n resizeMode: 'stretch',\n }\n});" } ]
Discounts - Solved Examples
Q 1 - Find the P.W. of Rs. 9920 due 3 years at 8% p.a. A - Rs 7000 B - Rs 8000 C - Rs 6000 D - Rs 7000 Answer - B Explanation P.W.= ((100 x Amount))/(100+(R x T)) = Rs {(100 x 9920)/(100 (3 x 8))} = Rs (100 x 9920)/124 = Rs 8000 Q 2 - The genuine rebate on a bill due 9 months consequently at 6% for each annum is Rs. 180. Discover its present worth. A - Rs 4000 B - Rs 5000 C - Rs 3000 D - Rs 6000 Answer - A Explanation P.W. = ((100 x T.D.))/((R x T)) = Rs {(100 x 180)/(6 x 3/4)} = Rs 4000 Q 3 - The genuine markdown on a sure total of cash due 3 years consequently is Rs 200 and the straightforward enthusiasm on the some aggregate for the same time and at the same guideline is Rs. 240. Discover the aggregate and the rate percent. A - Rs 1200 B - Rs 1000 C - Rs 1200 D - Rs 1000 Answer - A Explanation T.D = Rs 200 and S.I. = Rs 240 Sum due = (S .I. x T.D.)/(S.I.-T.D.) = Rs ((240 x 200))/((240-200)) = Rs 1200 Q 4 - The genuine rebate on Rs 1860 due after a sure time at 5% p.a. is Rs. 60. Discover the time after which it is expected. A - 10 months B - 8 months C - 7 months D - 6 months Answer - B Explanation P.W. = (Amount)-(T.D.) = Rs (1860-60) = Rs 1800 T.D. is S.I. on P.W. Rs. 60 is S.I. on Rs 1800 at 5% p.a. Time = ((100 x 60))/((5 x 1800)) years = 2/3 years = 2/3 x 12 months = 8 months Q 5 - Find the rebate on Rs. 9920 due 3 years at 8% p.a. A - Rs 1720 B - Rs 1820 C - Rs 1920 D - Rs 1220 Answer - C Explanation P.W.= ((100 x Amount))/(100+(R x T)) = Rs {(100 x 9920)/(100 (3 x 8))} = Rs (100 x 9920)/124 = Rs 8000 T.D. = (Amount)-(P.W.) = Rs (9920-8000) = Rs 1920 Q 6 - The genuine rebate on a bill due 9 months consequently at 6% for each annum is Rs. 180. Discover the charge's measure. A - Rs 4180 B - Rs 3180 C - Rs 2180 D - Rs 1180 Answer - A Explanation P.W. = ((100 x T.D.))/((R x T)) = Rs {(100 x 180)/(6 x 3/4)} = Rs 4000 Sum = (P.W.+T.D.) = Rs (4000+180) = Rs 4180 Q 7 - The genuine markdown on a sure total of cash due 3 years consequently is Rs 200 and the straightforward enthusiasm on the some aggregate for the same time and at the same guideline is Rs. 240. Discover the rate percent. A - 50/3% p.a B - 40/3% p.a C - 10/3% p.a D - 20/3% p.a Answer - D Explanation T.D = Rs 200 and S.I. = Rs 240 Sum due = (S .I. x T.D.)/(S.I.-T.D.) = Rs ((240 x 200))/((240-200)) = Rs 1200 T.D is S.I. on the sum. Rs. 240 is S.I. on Rs 1200 for a long time. R= ((100 x 240))/((1200 x 3))% p.a. = 20/3% p.a Q 8 - The genuine markdown on Rs 2575 due 4 months thus is Rs. 75. Discover the rate of hobby. A - 6% p.a. B - 7% p.a. C - 8% p.a. D - 9% p.a. Answer - D Explanation Amount = Rs 2575, T=4/12 years = 1/3 years, T.D = Rs. 75 P.W. = (Amount) - (T.D.) = Rs (2575-75) = 2500. T.D. Is S.I. on P.W. R.s 75 is S.I. on Rs. 2500 or 1/3 years Rate = ((100x75)/(2500x1/3))% p.a. = 9% p.a. Q 9 - The genuine rebate on a bill due 10 months consequently at 6% p.a. is Rs 26.25. Discover the charge's measure. A - Rs 451.25 B - Rs 551.25 C - Rs 351.25 D - Rs 251.25 Answer - B Explanation T.D. = Rs 26.25, T = 10/12 year= 5/6 year,R=6% p.a. Let P.W. be Rs x. Then, S.I. on Rs x at 6% p.a. for 5/6 year is Rs. 26.25 ∴ (x * 6 * 5/6)/100 = 25.25 => x= (26.25 * 20) = 525 ∴ (P.W.) + (T.D.) = Rs. (525+26.25) = Rs 551.25 Q 10 - The contrast between the S.I. what's more, T.D. on a sure whole of cash for 6 months at 6% p.a. is Rs. 27. Discover the total. A - 32900 B - 30900 C - 31900 D - 33900 Answer - B Explanation S.I. = Rs. (x * 6 * 1/2)/100 = Rs. 3x/100 and T.D. = Rs {(x * 78/12)/(100+(6 * 6/12) )} = Rs. 3x/103 ∴ 3x/100-3x/103 = 27 => (309x-300x) = (27 * 100 * 103) => x = ((27*100*103))/9 = 30900 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3947, "s": 3892, "text": "Q 1 - Find the P.W. of Rs. 9920 due 3 years at 8% p.a." }, { "code": null, "e": 3959, "s": 3947, "text": "A - Rs 7000" }, { "code": null, "e": 3971, "s": 3959, "text": "B - Rs 8000" }, { "code": null, "e": 3983, "s": 3971, "text": "C - Rs 6000" }, { "code": null, "e": 3995, "s": 3983, "text": "D - Rs 7000" }, { "code": null, "e": 4006, "s": 3995, "text": "Answer - B" }, { "code": null, "e": 4018, "s": 4006, "text": "Explanation" }, { "code": null, "e": 4124, "s": 4018, "text": "P.W.= ((100 x Amount))/(100+(R x T))\n= Rs {(100 x 9920)/(100 (3 x 8))}\n= Rs (100 x 9920)/124 \n= Rs 8000\n" }, { "code": null, "e": 4246, "s": 4124, "text": "Q 2 - The genuine rebate on a bill due 9 months consequently at 6% for each annum is Rs. 180. Discover its present worth." }, { "code": null, "e": 4258, "s": 4246, "text": "A - Rs 4000" }, { "code": null, "e": 4270, "s": 4258, "text": "B - Rs 5000" }, { "code": null, "e": 4282, "s": 4270, "text": "C - Rs 3000" }, { "code": null, "e": 4294, "s": 4282, "text": "D - Rs 6000" }, { "code": null, "e": 4305, "s": 4294, "text": "Answer - A" }, { "code": null, "e": 4317, "s": 4305, "text": "Explanation" }, { "code": null, "e": 4389, "s": 4317, "text": "P.W. = ((100 x T.D.))/((R x T))\n= Rs {(100 x 180)/(6 x 3/4)}\n= Rs 4000\n" }, { "code": null, "e": 4634, "s": 4389, "text": "Q 3 - The genuine markdown on a sure total of cash due 3 years consequently is Rs 200 and the straightforward enthusiasm on the some aggregate for the same time and at the same guideline is Rs. 240. Discover the aggregate and the rate percent. " }, { "code": null, "e": 4646, "s": 4634, "text": "A - Rs 1200" }, { "code": null, "e": 4658, "s": 4646, "text": "B - Rs 1000" }, { "code": null, "e": 4670, "s": 4658, "text": "C - Rs 1200" }, { "code": null, "e": 4682, "s": 4670, "text": "D - Rs 1000" }, { "code": null, "e": 4693, "s": 4682, "text": "Answer - A" }, { "code": null, "e": 4705, "s": 4693, "text": "Explanation" }, { "code": null, "e": 4817, "s": 4705, "text": "T.D = Rs 200 and S.I. = Rs 240 \nSum due = (S .I. x T.D.)/(S.I.-T.D.) \n= Rs ((240 x 200))/((240-200))\n= Rs 1200\n" }, { "code": null, "e": 4944, "s": 4817, "text": "Q 4 - The genuine rebate on Rs 1860 due after a sure time at 5% p.a. is Rs. 60. Discover the time after which it is expected. " }, { "code": null, "e": 4958, "s": 4944, "text": "A - 10 months" }, { "code": null, "e": 4971, "s": 4958, "text": "B - 8 months" }, { "code": null, "e": 4985, "s": 4971, "text": "C - 7 months " }, { "code": null, "e": 4998, "s": 4985, "text": "D - 6 months" }, { "code": null, "e": 5009, "s": 4998, "text": "Answer - B" }, { "code": null, "e": 5021, "s": 5009, "text": "Explanation" }, { "code": null, "e": 5216, "s": 5021, "text": "P.W. = (Amount)-(T.D.) \n= Rs (1860-60) \n= Rs 1800 \nT.D. is S.I. on P.W. \nRs. 60 is S.I. on Rs 1800 at 5% p.a. \nTime = ((100 x 60))/((5 x 1800)) years \n= 2/3 years \n= 2/3 x 12 months \n= 8 months\n" }, { "code": null, "e": 5274, "s": 5216, "text": "Q 5 - Find the rebate on Rs. 9920 due 3 years at 8% p.a." }, { "code": null, "e": 5286, "s": 5274, "text": "A - Rs 1720" }, { "code": null, "e": 5298, "s": 5286, "text": "B - Rs 1820" }, { "code": null, "e": 5310, "s": 5298, "text": "C - Rs 1920" }, { "code": null, "e": 5322, "s": 5310, "text": "D - Rs 1220" }, { "code": null, "e": 5333, "s": 5322, "text": "Answer - C" }, { "code": null, "e": 5345, "s": 5333, "text": "Explanation" }, { "code": null, "e": 5501, "s": 5345, "text": "P.W.= ((100 x Amount))/(100+(R x T))\n= Rs {(100 x 9920)/(100 (3 x 8))}\n= Rs (100 x 9920)/124 \n= Rs 8000\nT.D. = (Amount)-(P.W.)\n= Rs (9920-8000)\n= Rs 1920\n" }, { "code": null, "e": 5626, "s": 5501, "text": "Q 6 - The genuine rebate on a bill due 9 months consequently at 6% for each annum is Rs. 180. Discover the charge's measure." }, { "code": null, "e": 5638, "s": 5626, "text": "A - Rs 4180" }, { "code": null, "e": 5650, "s": 5638, "text": "B - Rs 3180" }, { "code": null, "e": 5662, "s": 5650, "text": "C - Rs 2180" }, { "code": null, "e": 5674, "s": 5662, "text": "D - Rs 1180" }, { "code": null, "e": 5685, "s": 5674, "text": "Answer - A" }, { "code": null, "e": 5697, "s": 5685, "text": "Explanation" }, { "code": null, "e": 5816, "s": 5697, "text": "P.W. = ((100 x T.D.))/((R x T))\n= Rs {(100 x 180)/(6 x 3/4)}\n= Rs 4000\nSum = (P.W.+T.D.) \n= Rs (4000+180) \n= Rs 4180 \n" }, { "code": null, "e": 6043, "s": 5816, "text": "Q 7 - The genuine markdown on a sure total of cash due 3 years consequently is Rs 200 and the straightforward enthusiasm on the some aggregate for the same time and at the same guideline is Rs. 240. Discover the rate percent. " }, { "code": null, "e": 6057, "s": 6043, "text": "A - 50/3% p.a" }, { "code": null, "e": 6071, "s": 6057, "text": "B - 40/3% p.a" }, { "code": null, "e": 6085, "s": 6071, "text": "C - 10/3% p.a" }, { "code": null, "e": 6099, "s": 6085, "text": "D - 20/3% p.a" }, { "code": null, "e": 6110, "s": 6099, "text": "Answer - D" }, { "code": null, "e": 6122, "s": 6110, "text": "Explanation" }, { "code": null, "e": 6352, "s": 6122, "text": "T.D = Rs 200 and S.I. = Rs 240 \nSum due = (S .I. x T.D.)/(S.I.-T.D.) \n= Rs ((240 x 200))/((240-200))\n= Rs 1200\nT.D is S.I. on the sum. \nRs. 240 is S.I. on Rs 1200 for a long time. \nR= ((100 x 240))/((1200 x 3))% p.a.\n= 20/3% p.a\n" }, { "code": null, "e": 6448, "s": 6352, "text": "Q 8 - The genuine markdown on Rs 2575 due 4 months thus is Rs. 75. Discover the rate of hobby. " }, { "code": null, "e": 6460, "s": 6448, "text": "A - 6% p.a." }, { "code": null, "e": 6472, "s": 6460, "text": "B - 7% p.a." }, { "code": null, "e": 6484, "s": 6472, "text": "C - 8% p.a." }, { "code": null, "e": 6496, "s": 6484, "text": "D - 9% p.a." }, { "code": null, "e": 6507, "s": 6496, "text": "Answer - D" }, { "code": null, "e": 6519, "s": 6507, "text": "Explanation" }, { "code": null, "e": 6734, "s": 6519, "text": "Amount = Rs 2575, T=4/12 years = 1/3 years, T.D = Rs. 75 \nP.W. = (Amount) - (T.D.) = Rs (2575-75) = 2500. \nT.D. Is S.I. on P.W. \nR.s 75 is S.I. on Rs. 2500 or 1/3 years\nRate = ((100x75)/(2500x1/3))% p.a. = 9% p.a.\n" }, { "code": null, "e": 6851, "s": 6734, "text": "Q 9 - The genuine rebate on a bill due 10 months consequently at 6% p.a. is Rs 26.25. Discover the charge's measure." }, { "code": null, "e": 6866, "s": 6851, "text": "A - Rs 451.25 " }, { "code": null, "e": 6881, "s": 6866, "text": "B - Rs 551.25 " }, { "code": null, "e": 6896, "s": 6881, "text": "C - Rs 351.25 " }, { "code": null, "e": 6911, "s": 6896, "text": "D - Rs 251.25 " }, { "code": null, "e": 6922, "s": 6911, "text": "Answer - B" }, { "code": null, "e": 6934, "s": 6922, "text": "Explanation" }, { "code": null, "e": 7168, "s": 6934, "text": "T.D. = Rs 26.25, T = 10/12 year= 5/6 year,R=6% p.a.\nLet P.W. be Rs x. Then,\nS.I. on Rs x at 6% p.a. for 5/6 year is Rs. 26.25\n∴ (x * 6 * 5/6)/100 = 25.25 \n=> x= (26.25 * 20) = 525\n∴ (P.W.) + (T.D.) = Rs. (525+26.25) = Rs 551.25\n" }, { "code": null, "e": 7302, "s": 7168, "text": "Q 10 - The contrast between the S.I. what's more, T.D. on a sure whole of cash for 6 months at 6% p.a. is Rs. 27. Discover the total." }, { "code": null, "e": 7313, "s": 7302, "text": "A - 32900 " }, { "code": null, "e": 7324, "s": 7313, "text": "B - 30900 " }, { "code": null, "e": 7335, "s": 7324, "text": "C - 31900 " }, { "code": null, "e": 7346, "s": 7335, "text": "D - 33900 " }, { "code": null, "e": 7357, "s": 7346, "text": "Answer - B" }, { "code": null, "e": 7369, "s": 7357, "text": "Explanation" }, { "code": null, "e": 7562, "s": 7369, "text": "S.I. = Rs. (x * 6 * 1/2)/100 \n= Rs. 3x/100 and T.D. \n= Rs {(x * 78/12)/(100+(6 * 6/12) )}\n= Rs. 3x/103\n∴ 3x/100-3x/103 = 27 \n=> (309x-300x) = (27 * 100 * 103)\n=> x = ((27*100*103))/9 \n= 30900\n" }, { "code": null, "e": 7598, "s": 7562, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7616, "s": 7598, "text": " Programming Line" }, { "code": null, "e": 7623, "s": 7616, "text": " Print" }, { "code": null, "e": 7634, "s": 7623, "text": " Add Notes" } ]
10 CSS Selectors Every Developer Should Know - GeeksforGeeks
02 Sep, 2021 What’s the first thing for any website to create a good impression on a user? ... Yes...it’s the user interface for any website. Every developer knows how important it is to create a beautiful design for users to interact with any website. Giving styling to the web pages smartly in a minimal amount of time is not an easy task if you don’t have a good knowledge of CSS and it’s selectors. CSS selectors target the specified elements in an HTML document and help developers to apply styling to the web pages. You might have knowledge of some basic CSS selectors but a bit more than basic knowledge helps in achieving your goal faster. Using the right CSS selectors minimize the amount of code, makes it more readable, and makes the CSS simpler to maintain that in the future. There are a wide variety of CSS selectors available. Let’s discuss some important ones to simplify your work in frontend development. This is one of the most basic selector to use in CSS. Element selector allows you to select and give styling to all elements with the same specified element name. If there are multiple elements with the same style definitions, you can group all the elements and apply styling to all of them together. This way you can minimize the code because you won’t have to use class for each of the elements. Example 1: Here, all paragraph on the page will be right-aligned, with a yellow text color p { text-align: right; color: red; } Example 2: Now, look at the following CSS code... h2 { text-align: center; color: yellow; } h3 { text-align: center; color: yellow; } p text-align: center; color: yellow; } You can minimize the above code using the group selector and write the same code as given below: h2, h3, p { text-align: center; color: yellow; } id selector is the other most powerful common selector in CSS. Using the # symbol followed by id name allows you to target by id and apply styling to all specified elements with a selected id. Using this selector sounds good because of its simplicity but keep in mind that id should be unique for the entire web page. It means you are not allowed to assign an id selector for multiple elements. If you won’t assign unique id you will face problems in manipulating a specific element in JavaScript. Also, your code will not be validated by W3C and you will face compatibility issues across different browsers. So instead of creating many #id’s use classes or any other logic for styling, else it will be tough to maintain your CSS later on. Example: #box{ width : 250px; height: 250px; background : yellow; } Class selector is the most useful common selector used by the developers. You can define the class selector using period (.) followed by the class name. It gives styling to all elements with a specified class attribute. It is similar to the id selector but the only difference is, class selector allows you to target multiple elements in a page. You can also use multiple classes (separated by a space) on HTML elements. Example 1: .center{ text-align: center; color: yellow; } Example 2: In the below example, only p elements with class ‘center’ will be affected. p.center { text-align: center; color: yellow; } Using attribute selector, you can select all elements by the name or value of a given attribute and apply styling to them. Example 1: Below is an example of an HTML line which has ‘rel’ attribute with the value of “newfriend” <h3 id="title" class="friend" rel="newfriend">David Walsh</h3> Let’s see how to use attribute selector for ‘rel’ attribute in the above line. h3[rel="newfriend"] { color: yellow; } This selector is frequently used by the developers in code for ‘checkbox’ element. Read the example given below. Example 2: input[type="checkbox"] { color: purple; } It is also frequently used for the anchor tags in the code. Read the example given below. Example 3: a[title] { color: red; } Combinators: These are used to apply styling to the html elements by using the relationship between the selectors. Combinators allows you to mix simple selectors and apply logic between them. Let’s discuss four different combinator selectors in CSS. Descendant selector Child selector Adjacent sibling selector General sibling selector Descendant selector apply styling to only those elements that are descendants of a specified element. This selector is very useful when you need to apply styling only for some specific elements. For example, what if, rather than targeting all ‘h2’ tags, you only need to target the ‘h2’ which are the part of ‘div’ tag only. These are the cases where you can use descendant selectors. Example 1: div h2 { background-color: green; } Example 2: You can also make a chain and use descendant selector. ol li a { background-color: green; } Example 3: In the below example, you can mix it with class selector. .box a{ color :green; } Child selector allows you to selects all elements that are the children of a specified element. Example 1: div > h1 { background-color: green; } The difference between child selector and descendant selector is that the latter will only select direct children. Example 2: CSS: span { background-color: white; } div > span { background-color: yellow; } HTML: <div> <span>Span #1, in the div. <span>Span #2, in the span that's in the div.</span> </span> </div> <span>Span #3, not in the div at all.</span> Result: Example 3: You have a ‘ul’ that has some items and inside these items, there are new ‘ol’ of items, you might want to select a certain style just for the higher-hierarchy list items but not for the nested list’s items. CSS: ul > li { border-top: 5px solid red; } HTML: <ul> <li>Unordered item</li> <li>Unordered item <ol> <li>Item 1</li> <li>Item 2</li> </ol> </li> </ul> Result: Adjacent means “immediately following”. This selector is used when you want to select the elements that immediately follow the specified element (adjacent siblings). In other words it selects the element which is right next to another element at the same level of the hierarchy. Example: Below example select p element that are directly following a ‘div’ element CSS: div + p { background-color: red; } HTML: <div> <p>Paragraph 1 in the div.</p> <p>Paragraph 2 in the div.</p> </div> <p>Paragraph 3. Not in a div.</p> <p>Paragraph 4. Not in a div.</p> Result: General sibling selectors (~) are less strict than adjacent sibling selector. It allows you to select all the elements that are siblings of a specified element even if they are not directly adjacent. Example: Below example selects all ‘p’ elements that are siblings of ‘div’ elements CSS: div ~ p { background-color: red; } HTML: <p>Paragraph 1.</p> <div> <p>Paragraph 2.</p> </div> <p>Paragraph 3.</p> <span>GeeksforGeeks</span> <p>Paragraph 4.</p> Result: It is also called as universal selector (*) and it selects everything in the document and apply styling to them. By default your browser already defines the styling to the element and when you want to reset the browser default styles you can use star selector. For example, instead of using the default styling of your browser such as margin, padding, text-align or font-size, you can define your own styling for the entire elements of your web page.. Example 1: * { text-align: center; color: green; margin: 0; padding: 0; font-size: 30px; border: 0; } Example 2: Select all elements inside <div> elements and set their background color to red. div * { background-color: red; } Did you notice that when you use other selectors like ‘class’ , ‘element’ or ‘id’, they already imply the star selector? h1 { ... } is similar to *h1 { ... } It is generally recommended to use * selector less in your code or use it for testing purpose only because it adds unnecessary too much weight on the browser. If you want to style an element based on the state of a specified element, you can use pseudo classes (:) for that. For example, you can apply styling on an element when a user mouses over it, when a user visit or hover a link when an element gets focus. So this selector is useful to apply styles based on element states. Let’s see the syntax and example. Syntax: selector:pseudo-class { property:value; } Example 1: Read the code below to change a button’s color when the user’s pointer hovers over it button:hover { color: green; } Example 2: a:link { color: red; } /* visited link */ a:visited { color: green; } Example 3: input[type=radio]:checked { border: 2px solid green; } Pseudo element (::) allows you to apply styling to the specific piece or fragment of the selected element. For example, style the first character, or line, of an element. Syntax: selector::pseudo-element { property:value; } Example 1: ::first-line can be used to change the font of the first line of a paragraph. p::first-line { color: green; font-size: 1.2em; text-transform: uppercase; } Example 2: Pseudo element can also be combined with the CSS classes. Read the example given below p.intro::first-letter { color: red; font-size: 1.2em; font-weight: bold; } Example 3: Pseudo element can also be used to insert content before, or after, the content of an element. Read the example given below which insert an image before the content of each ‘h1’ element. h1::before { content: url(abc.gif); } Consider a scenario where you have four unordered lists. If you want to apply CSS only on the third item of the ul, and you don’t have a unique id to hook into, you can use the nth-of-type(n). Basically :nth-of-type selector allows you to select every element that is a specified nth child of a specified type of it parent. n can be any number, keyword, or formula that will specify the position of an element among a group of siblings. If the explanation still sounds complicated then let’s understand with the example. Example 1: In the example given below only the third ‘li’ will be affected by the :nth-of-type style. CSS: li:nth-of-type(3) { color: red; } HTML: <ul> <li>First item.</li> <li>Second item.</li> <li>Third item.</li> <li>Fourth item.</li> </ul> Result: Syntax: :nth-of-type(number) { css declarations; } :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. n can be a number, a keyword, or a formula that will specify the position of an element among a group of siblings. Example 1: CSS: p:nth-child(3) { background: yellow; } HTML: <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> Result: Example 2: p:nth-child(2n) { background: yellow; } Example 3: You can also chain multiple nth-child together for different elements with same styling. div:nth-of-type(4) p:nth-of-child(3) { color: red; } bunnyram19 arorakashish0911 CSS GBlog Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar GET and POST requests using Python
[ { "code": null, "e": 28070, "s": 28042, "text": "\n02 Sep, 2021" }, { "code": null, "e": 28153, "s": 28070, "text": "What’s the first thing for any website to create a good impression on a user? ... " }, { "code": null, "e": 28847, "s": 28153, "text": "Yes...it’s the user interface for any website. Every developer knows how important it is to create a beautiful design for users to interact with any website. Giving styling to the web pages smartly in a minimal amount of time is not an easy task if you don’t have a good knowledge of CSS and it’s selectors. CSS selectors target the specified elements in an HTML document and help developers to apply styling to the web pages. You might have knowledge of some basic CSS selectors but a bit more than basic knowledge helps in achieving your goal faster. Using the right CSS selectors minimize the amount of code, makes it more readable, and makes the CSS simpler to maintain that in the future." }, { "code": null, "e": 28982, "s": 28847, "text": "There are a wide variety of CSS selectors available. Let’s discuss some important ones to simplify your work in frontend development. " }, { "code": null, "e": 29381, "s": 28982, "text": "This is one of the most basic selector to use in CSS. Element selector allows you to select and give styling to all elements with the same specified element name. If there are multiple elements with the same style definitions, you can group all the elements and apply styling to all of them together. This way you can minimize the code because you won’t have to use class for each of the elements. " }, { "code": null, "e": 29474, "s": 29381, "text": "Example 1: Here, all paragraph on the page will be right-aligned, with a yellow text color " }, { "code": null, "e": 29515, "s": 29474, "text": "p {\n text-align: right;\n color: red;\n}" }, { "code": null, "e": 29567, "s": 29515, "text": "Example 2: Now, look at the following CSS code... " }, { "code": null, "e": 29697, "s": 29567, "text": "h2 {\n text-align: center;\n color: yellow;\n}\nh3 {\n text-align: center;\n color: yellow;\n}\np \n text-align: center;\n color: yellow;\n}" }, { "code": null, "e": 29795, "s": 29697, "text": "You can minimize the above code using the group selector and write the same code as given below: " }, { "code": null, "e": 29846, "s": 29795, "text": "h2, h3, p {\n text-align: center;\n color: yellow;\n}" }, { "code": null, "e": 30586, "s": 29846, "text": "id selector is the other most powerful common selector in CSS. Using the # symbol followed by id name allows you to target by id and apply styling to all specified elements with a selected id. Using this selector sounds good because of its simplicity but keep in mind that id should be unique for the entire web page. It means you are not allowed to assign an id selector for multiple elements. If you won’t assign unique id you will face problems in manipulating a specific element in JavaScript. Also, your code will not be validated by W3C and you will face compatibility issues across different browsers. So instead of creating many #id’s use classes or any other logic for styling, else it will be tough to maintain your CSS later on." }, { "code": null, "e": 30596, "s": 30586, "text": "Example: " }, { "code": null, "e": 30655, "s": 30596, "text": "#box{\nwidth : 250px;\nheight: 250px;\nbackground : yellow;\n}" }, { "code": null, "e": 31078, "s": 30655, "text": "Class selector is the most useful common selector used by the developers. You can define the class selector using period (.) followed by the class name. It gives styling to all elements with a specified class attribute. It is similar to the id selector but the only difference is, class selector allows you to target multiple elements in a page. You can also use multiple classes (separated by a space) on HTML elements. " }, { "code": null, "e": 31090, "s": 31078, "text": "Example 1: " }, { "code": null, "e": 31136, "s": 31090, "text": ".center{\ntext-align: center;\ncolor: yellow;\n}" }, { "code": null, "e": 31223, "s": 31136, "text": "Example 2: In the below example, only p elements with class ‘center’ will be affected." }, { "code": null, "e": 31273, "s": 31223, "text": "p.center {\n text-align: center;\n color: yellow;\n}" }, { "code": null, "e": 31397, "s": 31273, "text": "Using attribute selector, you can select all elements by the name or value of a given attribute and apply styling to them. " }, { "code": null, "e": 31500, "s": 31397, "text": "Example 1: Below is an example of an HTML line which has ‘rel’ attribute with the value of “newfriend”" }, { "code": null, "e": 31563, "s": 31500, "text": "<h3 id=\"title\" class=\"friend\" rel=\"newfriend\">David Walsh</h3>" }, { "code": null, "e": 31642, "s": 31563, "text": "Let’s see how to use attribute selector for ‘rel’ attribute in the above line." }, { "code": null, "e": 31683, "s": 31642, "text": "h3[rel=\"newfriend\"] {\n color: yellow;\n}" }, { "code": null, "e": 31796, "s": 31683, "text": "This selector is frequently used by the developers in code for ‘checkbox’ element. Read the example given below." }, { "code": null, "e": 31807, "s": 31796, "text": "Example 2:" }, { "code": null, "e": 31854, "s": 31807, "text": "input[type=\"checkbox\"] {\n color: purple;\n}" }, { "code": null, "e": 31944, "s": 31854, "text": "It is also frequently used for the anchor tags in the code. Read the example given below." }, { "code": null, "e": 31956, "s": 31944, "text": "Example 3: " }, { "code": null, "e": 31983, "s": 31956, "text": "a[title] {\n color: red;\n}" }, { "code": null, "e": 32233, "s": 31983, "text": "Combinators: These are used to apply styling to the html elements by using the relationship between the selectors. Combinators allows you to mix simple selectors and apply logic between them. Let’s discuss four different combinator selectors in CSS." }, { "code": null, "e": 32253, "s": 32233, "text": "Descendant selector" }, { "code": null, "e": 32268, "s": 32253, "text": "Child selector" }, { "code": null, "e": 32294, "s": 32268, "text": "Adjacent sibling selector" }, { "code": null, "e": 32319, "s": 32294, "text": "General sibling selector" }, { "code": null, "e": 32705, "s": 32319, "text": "Descendant selector apply styling to only those elements that are descendants of a specified element. This selector is very useful when you need to apply styling only for some specific elements. For example, what if, rather than targeting all ‘h2’ tags, you only need to target the ‘h2’ which are the part of ‘div’ tag only. These are the cases where you can use descendant selectors. " }, { "code": null, "e": 32716, "s": 32705, "text": "Example 1:" }, { "code": null, "e": 32753, "s": 32716, "text": "div h2 {\n background-color: green;\n}" }, { "code": null, "e": 32819, "s": 32753, "text": "Example 2: You can also make a chain and use descendant selector." }, { "code": null, "e": 32857, "s": 32819, "text": "ol li a {\n background-color: green;\n}" }, { "code": null, "e": 32926, "s": 32857, "text": "Example 3: In the below example, you can mix it with class selector." }, { "code": null, "e": 32950, "s": 32926, "text": ".box a{\ncolor :green;\n}" }, { "code": null, "e": 33047, "s": 32950, "text": "Child selector allows you to selects all elements that are the children of a specified element. " }, { "code": null, "e": 33058, "s": 33047, "text": "Example 1:" }, { "code": null, "e": 33097, "s": 33058, "text": "div > h1 {\n background-color: green;\n}" }, { "code": null, "e": 33213, "s": 33097, "text": "The difference between child selector and descendant selector is that the latter will only select direct children. " }, { "code": null, "e": 33225, "s": 33213, "text": "Example 2: " }, { "code": null, "e": 33230, "s": 33225, "text": "CSS:" }, { "code": null, "e": 33308, "s": 33230, "text": "span {\n background-color: white;\n}\n\ndiv > span {\n background-color: yellow;\n}" }, { "code": null, "e": 33314, "s": 33308, "text": "HTML:" }, { "code": null, "e": 33465, "s": 33314, "text": "<div>\n <span>Span #1, in the div.\n <span>Span #2, in the span that's in the div.</span>\n </span>\n</div>\n<span>Span #3, not in the div at all.</span>" }, { "code": null, "e": 33473, "s": 33465, "text": "Result:" }, { "code": null, "e": 33692, "s": 33473, "text": "Example 3: You have a ‘ul’ that has some items and inside these items, there are new ‘ol’ of items, you might want to select a certain style just for the higher-hierarchy list items but not for the nested list’s items." }, { "code": null, "e": 33698, "s": 33692, "text": "CSS: " }, { "code": null, "e": 33740, "s": 33698, "text": "ul > li {\n border-top: 5px solid red;\n}" }, { "code": null, "e": 33746, "s": 33740, "text": "HTML:" }, { "code": null, "e": 33894, "s": 33746, "text": "<ul>\n <li>Unordered item</li>\n <li>Unordered item\n <ol>\n <li>Item 1</li>\n <li>Item 2</li>\n </ol>\n </li>\n</ul>" }, { "code": null, "e": 33903, "s": 33894, "text": "Result: " }, { "code": null, "e": 34184, "s": 33903, "text": "Adjacent means “immediately following”. This selector is used when you want to select the elements that immediately follow the specified element (adjacent siblings). In other words it selects the element which is right next to another element at the same level of the hierarchy. " }, { "code": null, "e": 34269, "s": 34184, "text": "Example: Below example select p element that are directly following a ‘div’ element " }, { "code": null, "e": 34274, "s": 34269, "text": "CSS:" }, { "code": null, "e": 34310, "s": 34274, "text": "div + p {\n background-color: red;\n}" }, { "code": null, "e": 34316, "s": 34310, "text": "HTML:" }, { "code": null, "e": 34462, "s": 34316, "text": "<div>\n <p>Paragraph 1 in the div.</p>\n <p>Paragraph 2 in the div.</p>\n</div>\n\n<p>Paragraph 3. Not in a div.</p>\n<p>Paragraph 4. Not in a div.</p>" }, { "code": null, "e": 34470, "s": 34462, "text": "Result:" }, { "code": null, "e": 34671, "s": 34470, "text": "General sibling selectors (~) are less strict than adjacent sibling selector. It allows you to select all the elements that are siblings of a specified element even if they are not directly adjacent. " }, { "code": null, "e": 34755, "s": 34671, "text": "Example: Below example selects all ‘p’ elements that are siblings of ‘div’ elements" }, { "code": null, "e": 34760, "s": 34755, "text": "CSS:" }, { "code": null, "e": 34796, "s": 34760, "text": "div ~ p {\n background-color: red;\n}" }, { "code": null, "e": 34802, "s": 34796, "text": "HTML:" }, { "code": null, "e": 34925, "s": 34802, "text": "<p>Paragraph 1.</p>\n\n<div>\n <p>Paragraph 2.</p>\n</div>\n\n<p>Paragraph 3.</p>\n<span>GeeksforGeeks</span>\n<p>Paragraph 4.</p>" }, { "code": null, "e": 34934, "s": 34925, "text": "Result: " }, { "code": null, "e": 35386, "s": 34934, "text": "It is also called as universal selector (*) and it selects everything in the document and apply styling to them. By default your browser already defines the styling to the element and when you want to reset the browser default styles you can use star selector. For example, instead of using the default styling of your browser such as margin, padding, text-align or font-size, you can define your own styling for the entire elements of your web page.." }, { "code": null, "e": 35397, "s": 35386, "text": "Example 1:" }, { "code": null, "e": 35488, "s": 35397, "text": "* {\ntext-align: center;\ncolor: green;\nmargin: 0;\npadding: 0;\nfont-size: 30px;\nborder: 0;\n}" }, { "code": null, "e": 35580, "s": 35488, "text": "Example 2: Select all elements inside <div> elements and set their background color to red." }, { "code": null, "e": 35616, "s": 35580, "text": "div * {\n background-color: red;\n}" }, { "code": null, "e": 35738, "s": 35616, "text": " Did you notice that when you use other selectors like ‘class’ , ‘element’ or ‘id’, they already imply the star selector?" }, { "code": null, "e": 35776, "s": 35738, "text": "h1 {\n...\n}\nis similar to \n*h1 {\n...\n}" }, { "code": null, "e": 35935, "s": 35776, "text": "It is generally recommended to use * selector less in your code or use it for testing purpose only because it adds unnecessary too much weight on the browser." }, { "code": null, "e": 36292, "s": 35935, "text": "If you want to style an element based on the state of a specified element, you can use pseudo classes (:) for that. For example, you can apply styling on an element when a user mouses over it, when a user visit or hover a link when an element gets focus. So this selector is useful to apply styles based on element states. Let’s see the syntax and example." }, { "code": null, "e": 36300, "s": 36292, "text": "Syntax:" }, { "code": null, "e": 36343, "s": 36300, "text": "selector:pseudo-class {\n property:value;\n}" }, { "code": null, "e": 36441, "s": 36343, "text": "Example 1: Read the code below to change a button’s color when the user’s pointer hovers over it" }, { "code": null, "e": 36473, "s": 36441, "text": "button:hover {\n color: green;\n}" }, { "code": null, "e": 36484, "s": 36473, "text": "Example 2:" }, { "code": null, "e": 36556, "s": 36484, "text": "a:link {\n color: red;\n}\n/* visited link */\na:visited {\n color: green;\n}" }, { "code": null, "e": 36567, "s": 36556, "text": "Example 3:" }, { "code": null, "e": 36623, "s": 36567, "text": "input[type=radio]:checked {\n border: 2px solid green;\n}" }, { "code": null, "e": 36795, "s": 36623, "text": "Pseudo element (::) allows you to apply styling to the specific piece or fragment of the selected element. For example, style the first character, or line, of an element. " }, { "code": null, "e": 36803, "s": 36795, "text": "Syntax:" }, { "code": null, "e": 36849, "s": 36803, "text": "selector::pseudo-element {\n property:value;\n}" }, { "code": null, "e": 36940, "s": 36849, "text": "Example 1: ::first-line can be used to change the font of the first line of a paragraph. " }, { "code": null, "e": 37020, "s": 36940, "text": "p::first-line {\n color: green;\n font-size: 1.2em;\n text-transform: uppercase;\n}" }, { "code": null, "e": 37118, "s": 37020, "text": "Example 2: Pseudo element can also be combined with the CSS classes. Read the example given below" }, { "code": null, "e": 37196, "s": 37118, "text": "p.intro::first-letter {\n color: red;\n font-size: 1.2em;\n font-weight: bold;\n}" }, { "code": null, "e": 37394, "s": 37196, "text": "Example 3: Pseudo element can also be used to insert content before, or after, the content of an element. Read the example given below which insert an image before the content of each ‘h1’ element." }, { "code": null, "e": 37433, "s": 37394, "text": "h1::before {\n content: url(abc.gif);\n}" }, { "code": null, "e": 37954, "s": 37433, "text": "Consider a scenario where you have four unordered lists. If you want to apply CSS only on the third item of the ul, and you don’t have a unique id to hook into, you can use the nth-of-type(n). Basically :nth-of-type selector allows you to select every element that is a specified nth child of a specified type of it parent. n can be any number, keyword, or formula that will specify the position of an element among a group of siblings. If the explanation still sounds complicated then let’s understand with the example." }, { "code": null, "e": 38056, "s": 37954, "text": "Example 1: In the example given below only the third ‘li’ will be affected by the :nth-of-type style." }, { "code": null, "e": 38061, "s": 38056, "text": "CSS:" }, { "code": null, "e": 38096, "s": 38061, "text": "li:nth-of-type(3) {\n color: red;\n}" }, { "code": null, "e": 38102, "s": 38096, "text": "HTML:" }, { "code": null, "e": 38199, "s": 38102, "text": "<ul>\n<li>First item.</li>\n<li>Second item.</li>\n<li>Third item.</li>\n<li>Fourth item.</li>\n</ul>" }, { "code": null, "e": 38207, "s": 38199, "text": "Result:" }, { "code": null, "e": 38215, "s": 38207, "text": "Syntax:" }, { "code": null, "e": 38259, "s": 38215, "text": ":nth-of-type(number) {\n css declarations;\n}" }, { "code": null, "e": 38477, "s": 38259, "text": ":nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. n can be a number, a keyword, or a formula that will specify the position of an element among a group of siblings." }, { "code": null, "e": 38488, "s": 38477, "text": "Example 1:" }, { "code": null, "e": 38493, "s": 38488, "text": "CSS:" }, { "code": null, "e": 38533, "s": 38493, "text": "p:nth-child(3) {\n background: yellow;\n}" }, { "code": null, "e": 38539, "s": 38533, "text": "HTML:" }, { "code": null, "e": 38653, "s": 38539, "text": "<p>The first paragraph.</p>\n<p>The second paragraph.</p>\n<p>The third paragraph.</p>\n<p>The fourth paragraph.</p>" }, { "code": null, "e": 38662, "s": 38653, "text": "Result: " }, { "code": null, "e": 38673, "s": 38662, "text": "Example 2:" }, { "code": null, "e": 38714, "s": 38673, "text": "p:nth-child(2n) {\n background: yellow;\n}" }, { "code": null, "e": 38814, "s": 38714, "text": "Example 3: You can also chain multiple nth-child together for different elements with same styling." }, { "code": null, "e": 38868, "s": 38814, "text": "div:nth-of-type(4) p:nth-of-child(3) {\n color: red;\n}" }, { "code": null, "e": 38879, "s": 38868, "text": "bunnyram19" }, { "code": null, "e": 38896, "s": 38879, "text": "arorakashish0911" }, { "code": null, "e": 38900, "s": 38896, "text": "CSS" }, { "code": null, "e": 38906, "s": 38900, "text": "GBlog" }, { "code": null, "e": 38923, "s": 38906, "text": "Web Technologies" }, { "code": null, "e": 39021, "s": 38923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39083, "s": 39021, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39133, "s": 39083, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39191, "s": 39133, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39239, "s": 39191, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39289, "s": 39239, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 39331, "s": 39289, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39405, "s": 39331, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 39433, "s": 39405, "text": "Socket Programming in C/C++" }, { "code": null, "e": 39458, "s": 39433, "text": "DSA Sheet by Love Babbar" } ]
Creating NotePad using PyQt5 - Python - GeeksforGeeks
15 Dec, 2021 In this article we will see how we can create notepad using PyQt5.Notepad is a generic text editor that allows you to create, open, edit, and read plaintext files.PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.Use this command to install PyQt5 : pip install PyQt5 GUI Implementation Steps : 1. Create a Vertical layout 2. Create a QPlainTextEdit object and add it to the layout 3. Create a container i.e QWidget object 4. Set this vertical layout to the container 5. Create a status bar to show status tips 6. Create file menu bar and add file actions below is how file menu bar will look like 7. Create an edit menu bar and add various edit action to it, below is how edit menu bar will look like 8. Create two toolbar for file and edit actions, below is how the toolbars will look like Back End Implementation Steps : 1. Create a path variable and set it to None 2. Add actions to each of the file menu actions these are same of toolbar actions as both share same actions 3. Create a critical method that shows the passed value in the pop up, it is used to show if any error occurs during saving or opening file 4. Create update title method that changes the window title according to the name of the file 5. Inside the file open action, create a try-except block that try to open the file and then update the title and path 6. Inside the save action if path is none call the save as method else save file to the path 7. Inside the save as method save the file at the selected path by user 8. Inside the print action print the file using QPrintDialog object 9. Inside the edit toggle bar action set the line wrap mode of editor according to the checked state 10. Similarly set action for undo, redo, cut, copy, paste and select all using the QPlainTextEdit object built in functions Below is the implementation Python3 # importing required librariesfrom PyQt5.QtGui import *from PyQt5.QtWidgets import *from PyQt5.QtCore import *from PyQt5.QtPrintSupport import *import osimport sys # Creating main window classclass MainWindow(QMainWindow): # constructor def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # setting window geometry self.setGeometry(100, 100, 600, 400) # creating a layout layout = QVBoxLayout() # creating a QPlainTextEdit object self.editor = QPlainTextEdit() # setting font to the editor fixedfont = QFontDatabase.systemFont(QFontDatabase.FixedFont) fixedfont.setPointSize(12) self.editor.setFont(fixedfont) # self.path holds the path of the currently open file. # If none, we haven't got a file open yet (or creating new). self.path = None # adding editor to the layout layout.addWidget(self.editor) # creating a QWidget layout container = QWidget() # setting layout to the container container.setLayout(layout) # making container as central widget self.setCentralWidget(container) # creating a status bar object self.status = QStatusBar() # setting stats bar to the window self.setStatusBar(self.status) # creating a file tool bar file_toolbar = QToolBar("File") # adding file tool bar to the window self.addToolBar(file_toolbar) # creating a file menu file_menu = self.menuBar().addMenu("&File") # creating actions to add in the file menu # creating a open file action open_file_action = QAction("Open file", self) # setting status tip open_file_action.setStatusTip("Open file") # adding action to the open file open_file_action.triggered.connect(self.file_open) # adding this to file menu file_menu.addAction(open_file_action) # adding this to tool bar file_toolbar.addAction(open_file_action) # similarly creating a save action save_file_action = QAction("Save", self) save_file_action.setStatusTip("Save current page") save_file_action.triggered.connect(self.file_save) file_menu.addAction(save_file_action) file_toolbar.addAction(save_file_action) # similarly creating save action saveas_file_action = QAction("Save As", self) saveas_file_action.setStatusTip("Save current page to specified file") saveas_file_action.triggered.connect(self.file_saveas) file_menu.addAction(saveas_file_action) file_toolbar.addAction(saveas_file_action) # for print action print_action = QAction("Print", self) print_action.setStatusTip("Print current page") print_action.triggered.connect(self.file_print) file_menu.addAction(print_action) file_toolbar.addAction(print_action) # creating another tool bar for editing text edit_toolbar = QToolBar("Edit") # adding this tool bar to the main window self.addToolBar(edit_toolbar) # creating a edit menu bar edit_menu = self.menuBar().addMenu("&Edit") # adding actions to the tool bar and menu bar # undo action undo_action = QAction("Undo", self) # adding status tip undo_action.setStatusTip("Undo last change") # when triggered undo the editor undo_action.triggered.connect(self.editor.undo) # adding this to tool and menu bar edit_toolbar.addAction(undo_action) edit_menu.addAction(undo_action) # redo action redo_action = QAction("Redo", self) redo_action.setStatusTip("Redo last change") # when triggered redo the editor redo_action.triggered.connect(self.editor.redo) # adding this to menu and tool bar edit_toolbar.addAction(redo_action) edit_menu.addAction(redo_action) # cut action cut_action = QAction("Cut", self) cut_action.setStatusTip("Cut selected text") # when triggered cut the editor text cut_action.triggered.connect(self.editor.cut) # adding this to menu and tool bar edit_toolbar.addAction(cut_action) edit_menu.addAction(cut_action) # copy action copy_action = QAction("Copy", self) copy_action.setStatusTip("Copy selected text") # when triggered copy the editor text copy_action.triggered.connect(self.editor.copy) # adding this to menu and tool bar edit_toolbar.addAction(copy_action) edit_menu.addAction(copy_action) # paste action paste_action = QAction("Paste", self) paste_action.setStatusTip("Paste from clipboard") # when triggered paste the copied text paste_action.triggered.connect(self.editor.paste) # adding this to menu and tool bar edit_toolbar.addAction(paste_action) edit_menu.addAction(paste_action) # select all action select_action = QAction("Select all", self) select_action.setStatusTip("Select all text") # when this triggered select the whole text select_action.triggered.connect(self.editor.selectAll) # adding this to menu and tool bar edit_toolbar.addAction(select_action) edit_menu.addAction(select_action) # wrap action wrap_action = QAction("Wrap text to window", self) wrap_action.setStatusTip("Check to wrap text to window") # making it checkable wrap_action.setCheckable(True) # making it checked wrap_action.setChecked(True) # adding action wrap_action.triggered.connect(self.edit_toggle_wrap) # adding it to edit menu not to the tool bar edit_menu.addAction(wrap_action) # calling update title method self.update_title() # showing all the components self.show() # creating dialog critical method # to show errors def dialog_critical(self, s): # creating a QMessageBox object dlg = QMessageBox(self) # setting text to the dlg dlg.setText(s) # setting icon to it dlg.setIcon(QMessageBox.Critical) # showing it dlg.show() # action called by file open action def file_open(self): # getting path and bool value path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "Text documents (*.txt);All files (*.*)") # if path is true if path: # try opening path try: with open(path, 'rU') as f: # read the file text = f.read() # if some error occured except Exception as e: # show error using critical method self.dialog_critical(str(e)) # else else: # update path value self.path = path # update the text self.editor.setPlainText(text) # update the title self.update_title() # action called by file save action def file_save(self): # if there is no save path if self.path is None: # call save as method return self.file_saveas() # else call save to path method self._save_to_path(self.path) # action called by save as action def file_saveas(self): # opening path path, _ = QFileDialog.getSaveFileName(self, "Save file", "", "Text documents (*.txt);All files (*.*)") # if dialog is cancelled i.e no path is selected if not path: # return this method # i.e no action performed return # else call save to path method self._save_to_path(path) # save to path method def _save_to_path(self, path): # get the text text = self.editor.toPlainText() # try catch block try: # opening file to write with open(path, 'w') as f: # write text in the file f.write(text) # if error occurs except Exception as e: # show error using critical self.dialog_critical(str(e)) # else do this else: # change path self.path = path # update the title self.update_title() # action called by print def file_print(self): # creating a QPrintDialog dlg = QPrintDialog() # if executed if dlg.exec_(): # print the text self.editor.print_(dlg.printer()) # update title method def update_title(self): # setting window title with prefix as file name # suffix aas PyQt5 Notepad self.setWindowTitle("%s - PyQt5 Notepad" %(os.path.basename(self.path) if self.path else "Untitled")) # action called by edit toggle def edit_toggle_wrap(self): # chaining line wrap mode self.editor.setLineWrapMode(1 if self.editor.lineWrapMode() == 0 else 0 ) # drivers codeif __name__ == '__main__': # creating PyQt5 application app = QApplication(sys.argv) # setting application name app.setApplicationName("PyQt5-Note") # creating a main window object window = MainWindow() # loop app.exec_() Output : sweetyty gabaa406 abhishek0719kadiyan prachisoda1234 PyQt-exercise Python-gui Python-PyQt 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": 24480, "s": 24452, "text": "\n15 Dec, 2021" }, { "code": null, "e": 24883, "s": 24480, "text": "In this article we will see how we can create notepad using PyQt5.Notepad is a generic text editor that allows you to create, open, edit, and read plaintext files.PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.Use this command to install PyQt5 : " }, { "code": null, "e": 24901, "s": 24883, "text": "pip install PyQt5" }, { "code": null, "e": 25234, "s": 24903, "text": "GUI Implementation Steps : 1. Create a Vertical layout 2. Create a QPlainTextEdit object and add it to the layout 3. Create a container i.e QWidget object 4. Set this vertical layout to the container 5. Create a status bar to show status tips 6. Create file menu bar and add file actions below is how file menu bar will look like " }, { "code": null, "e": 25339, "s": 25234, "text": "7. Create an edit menu bar and add various edit action to it, below is how edit menu bar will look like " }, { "code": null, "e": 25430, "s": 25339, "text": "8. Create two toolbar for file and edit actions, below is how the toolbars will look like " }, { "code": null, "e": 26429, "s": 25430, "text": "Back End Implementation Steps : 1. Create a path variable and set it to None 2. Add actions to each of the file menu actions these are same of toolbar actions as both share same actions 3. Create a critical method that shows the passed value in the pop up, it is used to show if any error occurs during saving or opening file 4. Create update title method that changes the window title according to the name of the file 5. Inside the file open action, create a try-except block that try to open the file and then update the title and path 6. Inside the save action if path is none call the save as method else save file to the path 7. Inside the save as method save the file at the selected path by user 8. Inside the print action print the file using QPrintDialog object 9. Inside the edit toggle bar action set the line wrap mode of editor according to the checked state 10. Similarly set action for undo, redo, cut, copy, paste and select all using the QPlainTextEdit object built in functions " }, { "code": null, "e": 26459, "s": 26429, "text": "Below is the implementation " }, { "code": null, "e": 26467, "s": 26459, "text": "Python3" }, { "code": "# importing required librariesfrom PyQt5.QtGui import *from PyQt5.QtWidgets import *from PyQt5.QtCore import *from PyQt5.QtPrintSupport import *import osimport sys # Creating main window classclass MainWindow(QMainWindow): # constructor def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # setting window geometry self.setGeometry(100, 100, 600, 400) # creating a layout layout = QVBoxLayout() # creating a QPlainTextEdit object self.editor = QPlainTextEdit() # setting font to the editor fixedfont = QFontDatabase.systemFont(QFontDatabase.FixedFont) fixedfont.setPointSize(12) self.editor.setFont(fixedfont) # self.path holds the path of the currently open file. # If none, we haven't got a file open yet (or creating new). self.path = None # adding editor to the layout layout.addWidget(self.editor) # creating a QWidget layout container = QWidget() # setting layout to the container container.setLayout(layout) # making container as central widget self.setCentralWidget(container) # creating a status bar object self.status = QStatusBar() # setting stats bar to the window self.setStatusBar(self.status) # creating a file tool bar file_toolbar = QToolBar(\"File\") # adding file tool bar to the window self.addToolBar(file_toolbar) # creating a file menu file_menu = self.menuBar().addMenu(\"&File\") # creating actions to add in the file menu # creating a open file action open_file_action = QAction(\"Open file\", self) # setting status tip open_file_action.setStatusTip(\"Open file\") # adding action to the open file open_file_action.triggered.connect(self.file_open) # adding this to file menu file_menu.addAction(open_file_action) # adding this to tool bar file_toolbar.addAction(open_file_action) # similarly creating a save action save_file_action = QAction(\"Save\", self) save_file_action.setStatusTip(\"Save current page\") save_file_action.triggered.connect(self.file_save) file_menu.addAction(save_file_action) file_toolbar.addAction(save_file_action) # similarly creating save action saveas_file_action = QAction(\"Save As\", self) saveas_file_action.setStatusTip(\"Save current page to specified file\") saveas_file_action.triggered.connect(self.file_saveas) file_menu.addAction(saveas_file_action) file_toolbar.addAction(saveas_file_action) # for print action print_action = QAction(\"Print\", self) print_action.setStatusTip(\"Print current page\") print_action.triggered.connect(self.file_print) file_menu.addAction(print_action) file_toolbar.addAction(print_action) # creating another tool bar for editing text edit_toolbar = QToolBar(\"Edit\") # adding this tool bar to the main window self.addToolBar(edit_toolbar) # creating a edit menu bar edit_menu = self.menuBar().addMenu(\"&Edit\") # adding actions to the tool bar and menu bar # undo action undo_action = QAction(\"Undo\", self) # adding status tip undo_action.setStatusTip(\"Undo last change\") # when triggered undo the editor undo_action.triggered.connect(self.editor.undo) # adding this to tool and menu bar edit_toolbar.addAction(undo_action) edit_menu.addAction(undo_action) # redo action redo_action = QAction(\"Redo\", self) redo_action.setStatusTip(\"Redo last change\") # when triggered redo the editor redo_action.triggered.connect(self.editor.redo) # adding this to menu and tool bar edit_toolbar.addAction(redo_action) edit_menu.addAction(redo_action) # cut action cut_action = QAction(\"Cut\", self) cut_action.setStatusTip(\"Cut selected text\") # when triggered cut the editor text cut_action.triggered.connect(self.editor.cut) # adding this to menu and tool bar edit_toolbar.addAction(cut_action) edit_menu.addAction(cut_action) # copy action copy_action = QAction(\"Copy\", self) copy_action.setStatusTip(\"Copy selected text\") # when triggered copy the editor text copy_action.triggered.connect(self.editor.copy) # adding this to menu and tool bar edit_toolbar.addAction(copy_action) edit_menu.addAction(copy_action) # paste action paste_action = QAction(\"Paste\", self) paste_action.setStatusTip(\"Paste from clipboard\") # when triggered paste the copied text paste_action.triggered.connect(self.editor.paste) # adding this to menu and tool bar edit_toolbar.addAction(paste_action) edit_menu.addAction(paste_action) # select all action select_action = QAction(\"Select all\", self) select_action.setStatusTip(\"Select all text\") # when this triggered select the whole text select_action.triggered.connect(self.editor.selectAll) # adding this to menu and tool bar edit_toolbar.addAction(select_action) edit_menu.addAction(select_action) # wrap action wrap_action = QAction(\"Wrap text to window\", self) wrap_action.setStatusTip(\"Check to wrap text to window\") # making it checkable wrap_action.setCheckable(True) # making it checked wrap_action.setChecked(True) # adding action wrap_action.triggered.connect(self.edit_toggle_wrap) # adding it to edit menu not to the tool bar edit_menu.addAction(wrap_action) # calling update title method self.update_title() # showing all the components self.show() # creating dialog critical method # to show errors def dialog_critical(self, s): # creating a QMessageBox object dlg = QMessageBox(self) # setting text to the dlg dlg.setText(s) # setting icon to it dlg.setIcon(QMessageBox.Critical) # showing it dlg.show() # action called by file open action def file_open(self): # getting path and bool value path, _ = QFileDialog.getOpenFileName(self, \"Open file\", \"\", \"Text documents (*.txt);All files (*.*)\") # if path is true if path: # try opening path try: with open(path, 'rU') as f: # read the file text = f.read() # if some error occured except Exception as e: # show error using critical method self.dialog_critical(str(e)) # else else: # update path value self.path = path # update the text self.editor.setPlainText(text) # update the title self.update_title() # action called by file save action def file_save(self): # if there is no save path if self.path is None: # call save as method return self.file_saveas() # else call save to path method self._save_to_path(self.path) # action called by save as action def file_saveas(self): # opening path path, _ = QFileDialog.getSaveFileName(self, \"Save file\", \"\", \"Text documents (*.txt);All files (*.*)\") # if dialog is cancelled i.e no path is selected if not path: # return this method # i.e no action performed return # else call save to path method self._save_to_path(path) # save to path method def _save_to_path(self, path): # get the text text = self.editor.toPlainText() # try catch block try: # opening file to write with open(path, 'w') as f: # write text in the file f.write(text) # if error occurs except Exception as e: # show error using critical self.dialog_critical(str(e)) # else do this else: # change path self.path = path # update the title self.update_title() # action called by print def file_print(self): # creating a QPrintDialog dlg = QPrintDialog() # if executed if dlg.exec_(): # print the text self.editor.print_(dlg.printer()) # update title method def update_title(self): # setting window title with prefix as file name # suffix aas PyQt5 Notepad self.setWindowTitle(\"%s - PyQt5 Notepad\" %(os.path.basename(self.path) if self.path else \"Untitled\")) # action called by edit toggle def edit_toggle_wrap(self): # chaining line wrap mode self.editor.setLineWrapMode(1 if self.editor.lineWrapMode() == 0 else 0 ) # drivers codeif __name__ == '__main__': # creating PyQt5 application app = QApplication(sys.argv) # setting application name app.setApplicationName(\"PyQt5-Note\") # creating a main window object window = MainWindow() # loop app.exec_()", "e": 35936, "s": 26467, "text": null }, { "code": null, "e": 35947, "s": 35936, "text": "Output : " }, { "code": null, "e": 35958, "s": 35949, "text": "sweetyty" }, { "code": null, "e": 35967, "s": 35958, "text": "gabaa406" }, { "code": null, "e": 35987, "s": 35967, "text": "abhishek0719kadiyan" }, { "code": null, "e": 36002, "s": 35987, "text": "prachisoda1234" }, { "code": null, "e": 36016, "s": 36002, "text": "PyQt-exercise" }, { "code": null, "e": 36027, "s": 36016, "text": "Python-gui" }, { "code": null, "e": 36039, "s": 36027, "text": "Python-PyQt" }, { "code": null, "e": 36046, "s": 36039, "text": "Python" }, { "code": null, "e": 36144, "s": 36046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36162, "s": 36144, "text": "Python Dictionary" }, { "code": null, "e": 36197, "s": 36162, "text": "Read a file line by line in Python" }, { "code": null, "e": 36219, "s": 36197, "text": "Enumerate() in Python" }, { "code": null, "e": 36251, "s": 36219, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36281, "s": 36251, "text": "Iterate over a list in Python" }, { "code": null, "e": 36323, "s": 36281, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 36349, "s": 36323, "text": "Python String | replace()" }, { "code": null, "e": 36386, "s": 36349, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 36429, "s": 36386, "text": "Python program to convert a list to string" } ]
How to check if a Python variable exists? - GeeksforGeeks
29 Dec, 2020 Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function. To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table. Example:Examples: Checking local variable existence def func(): # defining local variable a_variable = 0 # using locals() function # for checking existence in symbol table is_local_var = "a_variable" in locals() # printing result print(is_local_var) # driver codefunc() Output: True To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table. Example: Examples: Checking global variable existence def func(): # defining variable a_variable = 0 # using globals() function check # if global variable exist is_global_var = "a_variable" in globals() # printing result print(is_global_var) # driver codefunc() Output: False Python function-programs Python-Functions 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": "\n29 Dec, 2020" }, { "code": null, "e": 24441, "s": 24212, "text": "Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function." }, { "code": null, "e": 24575, "s": 24441, "text": "To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table." }, { "code": null, "e": 24627, "s": 24575, "text": "Example:Examples: Checking local variable existence" }, { "code": "def func(): # defining local variable a_variable = 0 # using locals() function # for checking existence in symbol table is_local_var = \"a_variable\" in locals() # printing result print(is_local_var) # driver codefunc()", "e": 24874, "s": 24627, "text": null }, { "code": null, "e": 24882, "s": 24874, "text": "Output:" }, { "code": null, "e": 24888, "s": 24882, "text": "True\n" }, { "code": null, "e": 25025, "s": 24888, "text": "To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table." }, { "code": null, "e": 25034, "s": 25025, "text": "Example:" }, { "code": null, "e": 25079, "s": 25034, "text": "Examples: Checking global variable existence" }, { "code": "def func(): # defining variable a_variable = 0 # using globals() function check # if global variable exist is_global_var = \"a_variable\" in globals() # printing result print(is_global_var) # driver codefunc()", "e": 25316, "s": 25079, "text": null }, { "code": null, "e": 25324, "s": 25316, "text": "Output:" }, { "code": null, "e": 25331, "s": 25324, "text": "False\n" }, { "code": null, "e": 25356, "s": 25331, "text": "Python function-programs" }, { "code": null, "e": 25373, "s": 25356, "text": "Python-Functions" }, { "code": null, "e": 25380, "s": 25373, "text": "Python" }, { "code": null, "e": 25478, "s": 25380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25487, "s": 25478, "text": "Comments" }, { "code": null, "e": 25500, "s": 25487, "text": "Old Comments" }, { "code": null, "e": 25532, "s": 25500, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25588, "s": 25532, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25609, "s": 25588, "text": "Python OOPs Concepts" }, { "code": null, "e": 25648, "s": 25609, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25690, "s": 25648, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25717, "s": 25690, "text": "Python Classes and Objects" }, { "code": null, "e": 25748, "s": 25717, "text": "Python | os.path.join() method" }, { "code": null, "e": 25790, "s": 25748, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25826, "s": 25790, "text": "Python | Pandas dataframe.groupby()" } ]
PyQt5 – Set minimum window size | setMinimumWidth and setMinimumHeight method - GeeksforGeeks
26 Mar, 2020 When we create a window, by default the window size is resizable although, we can use setMinimumSize() method to set the minimum size of the window. But what if we want to set minimum length only for width or height only, in order to do so we use setMinimumWidth() method to set minimum width and setMinimumHeight() method to set minimum height. When we use these method other length will be variable i.e there will be no minimum length to it, it can shrinks as much it can. Syntax : self.setMinimumWidth(width) self.setMinimumHeight(height) Argument : Both takes integer as argument. Action performed.setMinimumWidth() sets the minimum width.setMinimumHeight() sets the minimum height. Code for setting minimum width : # importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") width = 200 height = 200 # setting the minimum width self.setMinimumWidth(width) # creating a label widget self.label_1 = QLabel("Minimum width", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Code for setting minimum width : # importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") width = 200 height = 200 # setting the minimum width self.setMinimumHeight(height) # creating a label widget self.label_1 = QLabel("Minimum height", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt 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() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24376, "s": 23901, "text": "When we create a window, by default the window size is resizable although, we can use setMinimumSize() method to set the minimum size of the window. But what if we want to set minimum length only for width or height only, in order to do so we use setMinimumWidth() method to set minimum width and setMinimumHeight() method to set minimum height. When we use these method other length will be variable i.e there will be no minimum length to it, it can shrinks as much it can." }, { "code": null, "e": 24385, "s": 24376, "text": "Syntax :" }, { "code": null, "e": 24444, "s": 24385, "text": "self.setMinimumWidth(width)\nself.setMinimumHeight(height)\n" }, { "code": null, "e": 24487, "s": 24444, "text": "Argument : Both takes integer as argument." }, { "code": null, "e": 24589, "s": 24487, "text": "Action performed.setMinimumWidth() sets the minimum width.setMinimumHeight() sets the minimum height." }, { "code": null, "e": 24622, "s": 24589, "text": "Code for setting minimum width :" }, { "code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") width = 200 height = 200 # setting the minimum width self.setMinimumWidth(width) # creating a label widget self.label_1 = QLabel(\"Minimum width\", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25502, "s": 24622, "text": null }, { "code": null, "e": 25511, "s": 25502, "text": "Output :" }, { "code": null, "e": 25545, "s": 25511, "text": " Code for setting minimum width :" }, { "code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") width = 200 height = 200 # setting the minimum width self.setMinimumHeight(height) # creating a label widget self.label_1 = QLabel(\"Minimum height\", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26428, "s": 25545, "text": null }, { "code": null, "e": 26437, "s": 26428, "text": "Output :" }, { "code": null, "e": 26448, "s": 26437, "text": "Python-gui" }, { "code": null, "e": 26460, "s": 26448, "text": "Python-PyQt" }, { "code": null, "e": 26467, "s": 26460, "text": "Python" }, { "code": null, "e": 26565, "s": 26467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26574, "s": 26565, "text": "Comments" }, { "code": null, "e": 26587, "s": 26574, "text": "Old Comments" }, { "code": null, "e": 26619, "s": 26587, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26675, "s": 26619, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26717, "s": 26675, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26759, "s": 26717, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26795, "s": 26759, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26817, "s": 26795, "text": "Defaultdict in Python" }, { "code": null, "e": 26856, "s": 26817, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26883, "s": 26856, "text": "Python Classes and Objects" }, { "code": null, "e": 26914, "s": 26883, "text": "Python | os.path.join() method" } ]
How do I get the parent directory in Python?
In Python 3.4+ you can use the pathlib module to get the parent directory. from pathlib import Path print(Path('/home/username').parent) This will give the output: /home In older versions, you can call the os.path.join on your path and '..'(represents parent directory) and then find its absolute path using os.path.abspath. import os print(os.path.abspath(os.path.join('/home/username', '..'))) This will give the output: /home
[ { "code": null, "e": 1137, "s": 1062, "text": "In Python 3.4+ you can use the pathlib module to get the parent directory." }, { "code": null, "e": 1199, "s": 1137, "text": "from pathlib import Path\nprint(Path('/home/username').parent)" }, { "code": null, "e": 1226, "s": 1199, "text": "This will give the output:" }, { "code": null, "e": 1232, "s": 1226, "text": "/home" }, { "code": null, "e": 1387, "s": 1232, "text": "In older versions, you can call the os.path.join on your path and '..'(represents parent directory) and then find its absolute path using os.path.abspath." }, { "code": null, "e": 1458, "s": 1387, "text": "import os\nprint(os.path.abspath(os.path.join('/home/username', '..')))" }, { "code": null, "e": 1485, "s": 1458, "text": "This will give the output:" }, { "code": null, "e": 1491, "s": 1485, "text": "/home" } ]
Difference between Thread and Runnable in Java
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of the Thread class. This subclass should override the run method of the Thread class. An instance of the subclass can then be allocated and started. The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it. class RunnableExample implements Runnable{ public void run(){ System.out.println("Thread is running for Runnable Implementation"); } public static void main(String args[]){ RunnableExample runnable=new RunnableExample(); Thread t1 =new Thread(runnable); t1.start(); } } class ThreadExample extends Thread{ public void run(){ System.out.println("Thread is running"); } public static void main(String args[]){ ThreadExample t1=new ThreadExample (); t1.start(); } }
[ { "code": null, "e": 1311, "s": 1062, "text": "There are two ways to create a new thread of execution. One is to declare a class to be a subclass of the Thread class. This subclass should override the run method of the Thread class. An instance of the subclass can then be allocated and started." }, { "code": null, "e": 1554, "s": 1311, "text": "The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started." }, { "code": null, "e": 1737, "s": 1554, "text": "Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it." }, { "code": null, "e": 2043, "s": 1737, "text": "class RunnableExample implements Runnable{\n public void run(){\n System.out.println(\"Thread is running for Runnable Implementation\");\n }\n public static void main(String args[]){\n RunnableExample runnable=new RunnableExample();\n Thread t1 =new Thread(runnable);\n t1.start();\n }\n}" }, { "code": null, "e": 2266, "s": 2043, "text": "class ThreadExample extends Thread{\n public void run(){\n System.out.println(\"Thread is running\");\n }\n public static void main(String args[]){\n ThreadExample t1=new ThreadExample ();\n t1.start();\n }\n}" } ]
tf.keras and TensorFlow: Batch Normalization to train deep neural networks faster | by Chris Rawles | Towards Data Science
Training deep neural networks can be time consuming. In particular, training can be significantly impeded by vanishing gradients, which occurs when a network stops updating because the gradients, particularly in earlier layers, have approached zero values. Incorporating Xavier weight-initialization and ReLu activation functions helps counter the vanishing gradient problem. These techniques also help with the opposite, yet closely related issue of exploding gradients, where the gradients become extremely large preventing the model from updating. Perhaps the most powerful tool for combatting the vanishing and exploding gradients issue is Batch Normalization. Batch Normalization works like this: for each unit in a given layer, first compute the z score, and then apply a linear transformation using two trained variables γ and β. Batch Normalization is typically done prior to the non-linear activation function (see below figure), however applying it after the activation function can also be beneficial. Check out this lecture for more detail of how the technique works. Batch Normalization can be implemented in three ways in TensorFlow. Using: tf.keras.layers.BatchNormalizationtf.layers.batch_normalizationtf.nn.batch_normalization tf.keras.layers.BatchNormalization tf.layers.batch_normalization tf.nn.batch_normalization 08/18/2018 update: The DNNClassifier and DNNRegressor now have a batch_norm parameter, which makes it possible and easy to do batch normalization with a canned estimator. 11/12/2019 update: This has gotten even easier with TF 2.0 using tf.keras, you can simply add in a BatchNormalization layer and do not need to worry about control_dependencies. The tf.keras module became part of the core TensorFlow API in version 1.4. and provides a high level API for building TensorFlow models; so I will show you how to do it in Keras. The tf.layers.batch_normalization function has similar functionality, but Keras often proves to be an easier way to write model functions in TensorFlow. The second code block with tf.GraphKeys.UPDATE_OPS is important. Using tf.keras.layers.BatchNormalization, for each unit in the network, TensorFlow continually estimates the mean and variance of the weights over the training dataset. These are then stored in the tf.GraphKeys.UPDATE_OPS variable. After training, these stored values are used to apply Batch Normalization at prediction time. The training set mean and variance from each unit can be observed by printing extra_ops, which contains a list for each layer in the network: print(extra_ops)[<tf.Tensor ‘batch_normalization/AssignMovingAvg:0’ shape=(500,) dtype=float32_ref>, # layer 1 mean values <tf.Tensor ‘batch_normalization/AssignMovingAvg_1:0’ shape=(500,) dtype=float32_ref>, # layer 1 variances ...] While Batch Normalization is also available in the tf.nn module, it requires extra bookkeeping, as the mean and variance are required arguments for the function. Thus the user has to manually compute mean and variance at both the batch level and training set level. It is, thus, a lower abstraction level than tf.keras.layers or tf.layers; avoid the tf.nn implementation. Below, I apply Batch Normalization to the prominent MNIST dataset using TensorFlow. Check out the code here. MNIST is an easy dataset to analyze and doesn’t require many layers to achieve low classification error. However, we can still build a deep network and observe how Batch Normalization affects convergence. Let’s build a custom estimator using the tf.estimator API. First we build the model: After we define our model function, let’s build the custom estimator and train and evaluate our model: Let’s test how Batch Normalization impacts models of varying depths. After we wrap our code into a Python package, we can fire off multiple experiments in parallel using Cloud ML Engine: The below plot show the number of training iterations (1 iteration contains a batch size of 500) required to reach 90% testing accuracy — an easy target — as a function of network depth. It’s evident that Batch Normalization significantly speeds up training for the deeper networks. Without Batch Normalization, the number of training steps increases with each subsequent layer, but with it, the number of training steps is near constant. And in practice, on more difficult datasets, more layers is a prerequisite for success. Similarly, as shown below, for a fully connected network with 7 hidden layers, the convergence time without Batch Normalization is significantly slower. The above experiments utilize the commonly used ReLu activation function. Though obviously not immune to the vanishing gradient effect as shown above, the ReLu activation fares much better than the sigmoid or tanh activation functions. The vulnerability of the sigmoid activation function to vanishing gradients is rather intuitive to understand. At larger magnitude (very positive or negative) values, the sigmoid function “saturates” — i.e. the derivative of the sigmoid function approaches zero. And when many nodes saturate, the number of updates decreases, and network stops training. The same 7-layer network trains significantly slower using sigmoid activation functions without using Batch Normalization. With Batch Normalization, the network converges in a similar number of iterations when using ReLu. On the other hand, other activation functions, such as the exponential ReLu or leaky ReLu functions, can help combat the vanishing gradient issue as they have non-zero derivatives for both positive and negative large numbers. Finally, it is important to note that Batch Normalization incurs an extra time cost to training. Though Batch Normalization typically decreases the number of training steps to reach convergence, it brings an extra time cost because it introduces an additional operation and also introduces two new trained parameters per unit. Incorporating XLA and fused Batch Normalization (fused argument in tf.layers.batch_normalization) could help speed up the Batch Normalization operation by combining several individual operations into a single kernel. Regardless, Batch Normalization can be a very valuable tool for speeding the training of deep neural networks. As always with training deep neural networks, the best way to figure out if an approach will help for your problem is to try it!
[ { "code": null, "e": 723, "s": 172, "text": "Training deep neural networks can be time consuming. In particular, training can be significantly impeded by vanishing gradients, which occurs when a network stops updating because the gradients, particularly in earlier layers, have approached zero values. Incorporating Xavier weight-initialization and ReLu activation functions helps counter the vanishing gradient problem. These techniques also help with the opposite, yet closely related issue of exploding gradients, where the gradients become extremely large preventing the model from updating." }, { "code": null, "e": 1252, "s": 723, "text": "Perhaps the most powerful tool for combatting the vanishing and exploding gradients issue is Batch Normalization. Batch Normalization works like this: for each unit in a given layer, first compute the z score, and then apply a linear transformation using two trained variables γ and β. Batch Normalization is typically done prior to the non-linear activation function (see below figure), however applying it after the activation function can also be beneficial. Check out this lecture for more detail of how the technique works." }, { "code": null, "e": 1327, "s": 1252, "text": "Batch Normalization can be implemented in three ways in TensorFlow. Using:" }, { "code": null, "e": 1416, "s": 1327, "text": "tf.keras.layers.BatchNormalizationtf.layers.batch_normalizationtf.nn.batch_normalization" }, { "code": null, "e": 1451, "s": 1416, "text": "tf.keras.layers.BatchNormalization" }, { "code": null, "e": 1481, "s": 1451, "text": "tf.layers.batch_normalization" }, { "code": null, "e": 1507, "s": 1481, "text": "tf.nn.batch_normalization" }, { "code": null, "e": 1678, "s": 1507, "text": "08/18/2018 update: The DNNClassifier and DNNRegressor now have a batch_norm parameter, which makes it possible and easy to do batch normalization with a canned estimator." }, { "code": null, "e": 1855, "s": 1678, "text": "11/12/2019 update: This has gotten even easier with TF 2.0 using tf.keras, you can simply add in a BatchNormalization layer and do not need to worry about control_dependencies." }, { "code": null, "e": 2187, "s": 1855, "text": "The tf.keras module became part of the core TensorFlow API in version 1.4. and provides a high level API for building TensorFlow models; so I will show you how to do it in Keras. The tf.layers.batch_normalization function has similar functionality, but Keras often proves to be an easier way to write model functions in TensorFlow." }, { "code": null, "e": 2720, "s": 2187, "text": "The second code block with tf.GraphKeys.UPDATE_OPS is important. Using tf.keras.layers.BatchNormalization, for each unit in the network, TensorFlow continually estimates the mean and variance of the weights over the training dataset. These are then stored in the tf.GraphKeys.UPDATE_OPS variable. After training, these stored values are used to apply Batch Normalization at prediction time. The training set mean and variance from each unit can be observed by printing extra_ops, which contains a list for each layer in the network:" }, { "code": null, "e": 2954, "s": 2720, "text": "print(extra_ops)[<tf.Tensor ‘batch_normalization/AssignMovingAvg:0’ shape=(500,) dtype=float32_ref>, # layer 1 mean values <tf.Tensor ‘batch_normalization/AssignMovingAvg_1:0’ shape=(500,) dtype=float32_ref>, # layer 1 variances ...]" }, { "code": null, "e": 3326, "s": 2954, "text": "While Batch Normalization is also available in the tf.nn module, it requires extra bookkeeping, as the mean and variance are required arguments for the function. Thus the user has to manually compute mean and variance at both the batch level and training set level. It is, thus, a lower abstraction level than tf.keras.layers or tf.layers; avoid the tf.nn implementation." }, { "code": null, "e": 3640, "s": 3326, "text": "Below, I apply Batch Normalization to the prominent MNIST dataset using TensorFlow. Check out the code here. MNIST is an easy dataset to analyze and doesn’t require many layers to achieve low classification error. However, we can still build a deep network and observe how Batch Normalization affects convergence." }, { "code": null, "e": 3725, "s": 3640, "text": "Let’s build a custom estimator using the tf.estimator API. First we build the model:" }, { "code": null, "e": 3828, "s": 3725, "text": "After we define our model function, let’s build the custom estimator and train and evaluate our model:" }, { "code": null, "e": 4015, "s": 3828, "text": "Let’s test how Batch Normalization impacts models of varying depths. After we wrap our code into a Python package, we can fire off multiple experiments in parallel using Cloud ML Engine:" }, { "code": null, "e": 4542, "s": 4015, "text": "The below plot show the number of training iterations (1 iteration contains a batch size of 500) required to reach 90% testing accuracy — an easy target — as a function of network depth. It’s evident that Batch Normalization significantly speeds up training for the deeper networks. Without Batch Normalization, the number of training steps increases with each subsequent layer, but with it, the number of training steps is near constant. And in practice, on more difficult datasets, more layers is a prerequisite for success." }, { "code": null, "e": 4695, "s": 4542, "text": "Similarly, as shown below, for a fully connected network with 7 hidden layers, the convergence time without Batch Normalization is significantly slower." }, { "code": null, "e": 5285, "s": 4695, "text": "The above experiments utilize the commonly used ReLu activation function. Though obviously not immune to the vanishing gradient effect as shown above, the ReLu activation fares much better than the sigmoid or tanh activation functions. The vulnerability of the sigmoid activation function to vanishing gradients is rather intuitive to understand. At larger magnitude (very positive or negative) values, the sigmoid function “saturates” — i.e. the derivative of the sigmoid function approaches zero. And when many nodes saturate, the number of updates decreases, and network stops training." }, { "code": null, "e": 5507, "s": 5285, "text": "The same 7-layer network trains significantly slower using sigmoid activation functions without using Batch Normalization. With Batch Normalization, the network converges in a similar number of iterations when using ReLu." }, { "code": null, "e": 5733, "s": 5507, "text": "On the other hand, other activation functions, such as the exponential ReLu or leaky ReLu functions, can help combat the vanishing gradient issue as they have non-zero derivatives for both positive and negative large numbers." }, { "code": null, "e": 6060, "s": 5733, "text": "Finally, it is important to note that Batch Normalization incurs an extra time cost to training. Though Batch Normalization typically decreases the number of training steps to reach convergence, it brings an extra time cost because it introduces an additional operation and also introduces two new trained parameters per unit." }, { "code": null, "e": 6277, "s": 6060, "text": "Incorporating XLA and fused Batch Normalization (fused argument in tf.layers.batch_normalization) could help speed up the Batch Normalization operation by combining several individual operations into a single kernel." } ]
Conjugate Prior Explained. With examples & proofs | by Aerin Kim | Towards Data Science
Prior probability is the probability of an event before we see the data.In Bayesian Inference, the prior is our guess about the probability based on what we know now, before new data becomes available. Conjugate prior just can not be understood without knowing Bayesian inference. For the rest of the blog, I’ll assume you know the concepts of prior, sampling and posterior. For some likelihood functions, if you choose a certain prior, the posterior ends up being in the same distribution as the prior. Such a prior then is called a Conjugate Prior. It is always best understood through examples. Below is the code to calculate the posterior of the binomial likelihood. θ is the probability of success and our goal is to pick the θ that maximizes the posterior probability. A question to you: Is there anything that concerns you in the code block above? There are two things that make the posterior calculation expensive. First, we are computing the posterior for every single θ. Why do we have to calculate the posterior for thousands of thetas? Because you are normalizing the posterior (line 21). Even if you choose not to normalize the posterior, the end goal is to find the maximum of the posteriors (Maximum a posteriori). In order to find the maximum in a vanilla way, we need to consider every candidate — the likelihood P(X|θ) for every θ. Second, if there is no closed-form formula of the posterior distribution, we have to find the maximum by numerical optimization, such as gradient descent or newtons method. When you know that your prior is a conjugate prior, you can skip the posterior = likelihood * prior computation. Furthermore, if your prior distribution has a closed-form form expression, you already know what the maximum posterior is going to be. In the example above, the beta distribution is a conjugate prior to the binomial likelihood. What does this mean? It means during the modeling phase, we already know the posterior will also be a beta distribution. Therefore, after carrying out more experiments, you can compute the posterior simply by adding the number of acceptances and rejections to the existing parameters α, β respectively, instead of multiplying the likelihood with the prior distribution. This is very convenient! (Proof in the next section.) As a data/ML scientist, your model is never complete. You have to update your model as more data come in (and that’s why we use Bayesian Inference).As you saw, the computations in Bayesian Inference can be heavy or sometimes even intractable. However, if we could use the closed-form formula of the conjugate prior, the computation becomes very light. When we use the Beta distribution as a prior, a posterior of binomial likelihood will also follow the beta distribution. What do the PDFs of Binomial and Beta look like? Let’s plug them into the famous Bayes formula. θ is the probability of success. x is the number of successes. n is the total number of trials, therefore n-x is the number of failures. The prior distribution P(θ) was Beta(α, β) and after getting x successes and n-x failures from the experiments, the posterior also becomes a Beta distribution with parameters (x+α, n-x+β). What’s nice here is you will know this analytically without doing the computation. The Beta distribution is a conjugate prior for the Bernoulli, binomial, negative binomial and geometric distributions (seems like those are the distributions that involve success & failure). <Beta posterior>Beta prior * Bernoulli likelihood → Beta posteriorBeta prior * Binomial likelihood → Beta posteriorBeta prior * Negative Binomial likelihood → Beta posteriorBeta prior * Geometric likelihood → Beta posterior<Gamma posterior>Gamma prior * Poisson likelihood → Gamma posteriorGamma prior * Exponential likelihood → Gamma posterior<Normal posterior> Normal prior * Normal likelihood (mean) → Normal posterior This is why these three distributions (Beta, Gamma and Normal) are used a lot as priors. An interesting way to put this is that even if you do all those experiments and multiply your likelihood to the prior, your initial choice of the prior distribution was so good that the final distribution is the same as the prior. Conjugate prior P(θ) in an equation: P(θ) such that P(θ|D) = P(θ) Conjugate prior = Convenient prior A few things to note: When we use the conjugate prior, sequential estimation (updating the counts after each observation) gives the same result as a batch estimation.In order to find the maximum posterior, you don’t have to normalize the multiplication of likelihood (sampling) and the prior (the integration for every possible θ in the denominator). When we use the conjugate prior, sequential estimation (updating the counts after each observation) gives the same result as a batch estimation. In order to find the maximum posterior, you don’t have to normalize the multiplication of likelihood (sampling) and the prior (the integration for every possible θ in the denominator). You can still find the maximum without normalizing. However, if you want to compare posteriors from different models, or calculate the point estimates, you need to normalize.
[ { "code": null, "e": 373, "s": 171, "text": "Prior probability is the probability of an event before we see the data.In Bayesian Inference, the prior is our guess about the probability based on what we know now, before new data becomes available." }, { "code": null, "e": 452, "s": 373, "text": "Conjugate prior just can not be understood without knowing Bayesian inference." }, { "code": null, "e": 546, "s": 452, "text": "For the rest of the blog, I’ll assume you know the concepts of prior, sampling and posterior." }, { "code": null, "e": 722, "s": 546, "text": "For some likelihood functions, if you choose a certain prior, the posterior ends up being in the same distribution as the prior. Such a prior then is called a Conjugate Prior." }, { "code": null, "e": 946, "s": 722, "text": "It is always best understood through examples. Below is the code to calculate the posterior of the binomial likelihood. θ is the probability of success and our goal is to pick the θ that maximizes the posterior probability." }, { "code": null, "e": 1026, "s": 946, "text": "A question to you: Is there anything that concerns you in the code block above?" }, { "code": null, "e": 1094, "s": 1026, "text": "There are two things that make the posterior calculation expensive." }, { "code": null, "e": 1152, "s": 1094, "text": "First, we are computing the posterior for every single θ." }, { "code": null, "e": 1521, "s": 1152, "text": "Why do we have to calculate the posterior for thousands of thetas? Because you are normalizing the posterior (line 21). Even if you choose not to normalize the posterior, the end goal is to find the maximum of the posteriors (Maximum a posteriori). In order to find the maximum in a vanilla way, we need to consider every candidate — the likelihood P(X|θ) for every θ." }, { "code": null, "e": 1694, "s": 1521, "text": "Second, if there is no closed-form formula of the posterior distribution, we have to find the maximum by numerical optimization, such as gradient descent or newtons method." }, { "code": null, "e": 1942, "s": 1694, "text": "When you know that your prior is a conjugate prior, you can skip the posterior = likelihood * prior computation. Furthermore, if your prior distribution has a closed-form form expression, you already know what the maximum posterior is going to be." }, { "code": null, "e": 2459, "s": 1942, "text": "In the example above, the beta distribution is a conjugate prior to the binomial likelihood. What does this mean? It means during the modeling phase, we already know the posterior will also be a beta distribution. Therefore, after carrying out more experiments, you can compute the posterior simply by adding the number of acceptances and rejections to the existing parameters α, β respectively, instead of multiplying the likelihood with the prior distribution. This is very convenient! (Proof in the next section.)" }, { "code": null, "e": 2811, "s": 2459, "text": "As a data/ML scientist, your model is never complete. You have to update your model as more data come in (and that’s why we use Bayesian Inference).As you saw, the computations in Bayesian Inference can be heavy or sometimes even intractable. However, if we could use the closed-form formula of the conjugate prior, the computation becomes very light." }, { "code": null, "e": 2932, "s": 2811, "text": "When we use the Beta distribution as a prior, a posterior of binomial likelihood will also follow the beta distribution." }, { "code": null, "e": 2981, "s": 2932, "text": "What do the PDFs of Binomial and Beta look like?" }, { "code": null, "e": 3028, "s": 2981, "text": "Let’s plug them into the famous Bayes formula." }, { "code": null, "e": 3061, "s": 3028, "text": "θ is the probability of success." }, { "code": null, "e": 3091, "s": 3061, "text": "x is the number of successes." }, { "code": null, "e": 3165, "s": 3091, "text": "n is the total number of trials, therefore n-x is the number of failures." }, { "code": null, "e": 3354, "s": 3165, "text": "The prior distribution P(θ) was Beta(α, β) and after getting x successes and n-x failures from the experiments, the posterior also becomes a Beta distribution with parameters (x+α, n-x+β)." }, { "code": null, "e": 3437, "s": 3354, "text": "What’s nice here is you will know this analytically without doing the computation." }, { "code": null, "e": 3628, "s": 3437, "text": "The Beta distribution is a conjugate prior for the Bernoulli, binomial, negative binomial and geometric distributions (seems like those are the distributions that involve success & failure)." }, { "code": null, "e": 4050, "s": 3628, "text": "<Beta posterior>Beta prior * Bernoulli likelihood → Beta posteriorBeta prior * Binomial likelihood → Beta posteriorBeta prior * Negative Binomial likelihood → Beta posteriorBeta prior * Geometric likelihood → Beta posterior<Gamma posterior>Gamma prior * Poisson likelihood → Gamma posteriorGamma prior * Exponential likelihood → Gamma posterior<Normal posterior> Normal prior * Normal likelihood (mean) → Normal posterior" }, { "code": null, "e": 4139, "s": 4050, "text": "This is why these three distributions (Beta, Gamma and Normal) are used a lot as priors." }, { "code": null, "e": 4370, "s": 4139, "text": "An interesting way to put this is that even if you do all those experiments and multiply your likelihood to the prior, your initial choice of the prior distribution was so good that the final distribution is the same as the prior." }, { "code": null, "e": 4407, "s": 4370, "text": "Conjugate prior P(θ) in an equation:" }, { "code": null, "e": 4436, "s": 4407, "text": "P(θ) such that P(θ|D) = P(θ)" }, { "code": null, "e": 4471, "s": 4436, "text": "Conjugate prior = Convenient prior" }, { "code": null, "e": 4493, "s": 4471, "text": "A few things to note:" }, { "code": null, "e": 4822, "s": 4493, "text": "When we use the conjugate prior, sequential estimation (updating the counts after each observation) gives the same result as a batch estimation.In order to find the maximum posterior, you don’t have to normalize the multiplication of likelihood (sampling) and the prior (the integration for every possible θ in the denominator)." }, { "code": null, "e": 4967, "s": 4822, "text": "When we use the conjugate prior, sequential estimation (updating the counts after each observation) gives the same result as a batch estimation." }, { "code": null, "e": 5152, "s": 4967, "text": "In order to find the maximum posterior, you don’t have to normalize the multiplication of likelihood (sampling) and the prior (the integration for every possible θ in the denominator)." } ]
A new plot theme for Matplotlib — Gadfly | by Jonny Brooks-Bartlett | Towards Data Science
I’ve made a plotting theme for Matplotlib that’s inspired by the default plotting theme used in Gadfly for the Julia programming language. Typically I’d just write the code in Julia, which is what I’ve done for many of my previous blog posts. However, since upgrading to Julia v1.0, I’ve been unable to import Gadfly, which means no more pretty Gadfly plots. So I said to myself “Jonny, it’s time to just create the theme yourself”. And I did! (If you want to find out how to use this theme then skip to the last section) When plotting using the Seaborn, the default aesthetics change a little. I haven’t worked out how to change this exactly but I’m not too fussed about it. For example, boxplots are very different (see below) When plotting withsns.lmplot the legend is plotted outside of the axes and does not have a border (below). It also draw the left and bottom spines by default too. This theme isn’t installed in the set of themes that come with matplotlib. Therefore, if you want to use the theme you have a few options. I’ll list a couple of the options here but you can learn about all of the ways by reading the matplotlib documentation on Customizing Matplotlib with style sheets and rcParams. Copy the matplotlibrc style sheet contents at the end of this blog post and save it in the same directory as the script from which you want to do your plotting. Save it under the name matplotlibrc . Then it should just work. Again, copy the matplotlibrc style sheet contents at the end of this blog post but this time save as in mpl_configdir/stylelib as <style-name>.mplstyle. You can find out where mpl_configdir is with matplotlib.get_configdir(). I had to create the stylelib directory because it wasn’t already in the mpl_configdir directory. Once you’ve saved the file in the right directory you can then set the theme with import matplotlib.pyplot as pltplt.style.use(<style-name>) So I saved the file as gadfly.mplstyle and I can set the theme with plt.style.use('gadfly')
[ { "code": null, "e": 616, "s": 172, "text": "I’ve made a plotting theme for Matplotlib that’s inspired by the default plotting theme used in Gadfly for the Julia programming language. Typically I’d just write the code in Julia, which is what I’ve done for many of my previous blog posts. However, since upgrading to Julia v1.0, I’ve been unable to import Gadfly, which means no more pretty Gadfly plots. So I said to myself “Jonny, it’s time to just create the theme yourself”. And I did!" }, { "code": null, "e": 694, "s": 616, "text": "(If you want to find out how to use this theme then skip to the last section)" }, { "code": null, "e": 901, "s": 694, "text": "When plotting using the Seaborn, the default aesthetics change a little. I haven’t worked out how to change this exactly but I’m not too fussed about it. For example, boxplots are very different (see below)" }, { "code": null, "e": 1064, "s": 901, "text": "When plotting withsns.lmplot the legend is plotted outside of the axes and does not have a border (below). It also draw the left and bottom spines by default too." }, { "code": null, "e": 1380, "s": 1064, "text": "This theme isn’t installed in the set of themes that come with matplotlib. Therefore, if you want to use the theme you have a few options. I’ll list a couple of the options here but you can learn about all of the ways by reading the matplotlib documentation on Customizing Matplotlib with style sheets and rcParams." }, { "code": null, "e": 1605, "s": 1380, "text": "Copy the matplotlibrc style sheet contents at the end of this blog post and save it in the same directory as the script from which you want to do your plotting. Save it under the name matplotlibrc . Then it should just work." }, { "code": null, "e": 1928, "s": 1605, "text": "Again, copy the matplotlibrc style sheet contents at the end of this blog post but this time save as in mpl_configdir/stylelib as <style-name>.mplstyle. You can find out where mpl_configdir is with matplotlib.get_configdir(). I had to create the stylelib directory because it wasn’t already in the mpl_configdir directory." }, { "code": null, "e": 2010, "s": 1928, "text": "Once you’ve saved the file in the right directory you can then set the theme with" }, { "code": null, "e": 2069, "s": 2010, "text": "import matplotlib.pyplot as pltplt.style.use(<style-name>)" } ]
New Features in ECMAScript 2021 Update - GeeksforGeeks
14 Jul, 2021 ECMAScript is a part of JavaScript language which is mostly used in web technology, building websites, or web apps. ECMAScript is growing as one of the world’s most widely used general-purpose programming languages. It is majorly used in embedding with web browsers and also adopted for server and embedded applications. New updates to ECMAScript will release out this July. The new improvements are introduced to make JavaScript more powerful and also make working easy for developers. It provides new functions, simple ways to do complex works, and much more. New updates: The new JavaScript features in ECMAScript 2021 are as follows: 1. Logical assignment operators: Logical assignment operators introduce new operators which combine logical operators and assignment expressions. And & Equals (&&=): It assigns when the value is truthy. Previous version:let x = 1; if(x){ a = 10; } Output: x = 10New version:let x = 1; x &&= 10; Output: x = 10 Previous version: let x = 1; if(x){ a = 10; } Output: x = 10 New version: let x = 1; x &&= 10; Output: x = 10 OR & Equals (||=): It assigns when the value is falsy. The assignment operation happens only if x is a falsy value. If x contains 1 which is a truthy value, assignment does not happen. Here x contains 0 therefore assignment happens.Previous version:let x = 0; x = x || 10; Output: x = 10 New version:let x = 0; x ||= 10 Output: x = 10 Previous version: let x = 0; x = x || 10; Output: x = 10 New version: let x = 0; x ||= 10 Output: x = 10 Nullish coalescing & Equals (??=): Symbol ?? is a nullish coalescing operator in JavaScript. It checks if a value is null or undefined.let x; let y = 10; x ??= y; console.log(x); console.log(y);Output: The value of x is undefined, therefore the right-hand side expression is evaluated and sets x to 10.10 10 let x; let y = 10; x ??= y; console.log(x); console.log(y); Output: The value of x is undefined, therefore the right-hand side expression is evaluated and sets x to 10. 10 10 2. Numeric separators: To improve readability and to separate groups of digits, numeric literals use underscores as separators. // A billion dollar that I want to earn const money = 1_000_000_000; const money = 1_000_000_000.00; It also can be used for Binary, Hex, Octal bases. 3. String replaceAll(): If we want to replace all instances of a substring in string then this new method replaceAll() is very useful. const s = "You are reading JavaScript 2021 new updates."; console.log(s.replaceAll("JavaScript", "ECMAScript")); Output : You are reading ECMAScript 2021 new updates. 4. Promise.any: The Promise.any() method returns a promise that will resolve as soon as one of the promises is resolved. It is the opposite of the Promise.all() method which waits for all promises to resolve before it resolves. What will happen when all the promises are rejected, The method will throw an AggregateError exception with the rejection reason. We have written the code inside a try-catch block. const promiseOne = new Promise((resolve, reject) => { setTimeout(() => reject(), 1000); }); const promiseTwo = new Promise((resolve, reject) => { setTimeout(() => reject(), 2000); }); const promiseThree = new Promise((resolve, reject) => { setTimeout(() => reject(), 3000); }); try { const first = await Promise.any([ promiseOne, promiseTwo, promiseThree ]); // If any of the promises was satisfied. } catch (error) { console.log(error); // AggregateError: If all promises were rejected } Output: await is only valid in async functions and the top-level bodies of modules 5. Private class methods: Private methods have scope inside the class only, so outside the class, they are not accessible. Previous version: class GfG { showMe() { console.log("I am a geek") } #notShowMe() { console.log("Hidden informations") } } const gfg = new GfG() gfg.showMe() gfg.notShowMe() Output: Error is shown as follows. This is because notShowMe() is now a private method inside the class GfG and can only be accessed via a public method inside the class. gfg.notShowMe is not a function New version: class GfG { showMe() { console.log("I am a geek"); } #notShowMe() { console.log("Hidden informations"); } showAll() { this.showMe() this.#notShowMe(); } } const gfg = new GfG(); gfg.showAll(); Output: We create a new public method called showAll() inside the class GfG. From this public method, we can access the private method #notShowMe() and since our new method is public we get the following result. I am a geek Hidden informations 6. Private Getters and Setters: Just like private methods, now we can make getters and setters so that they can only be accessed inside a class or by instance created. class GfG { get #Name() { return "GeeksforGeeks" } get viewName() { return this.#Name } } let name = new GfG(); console.log(name.viewName); Output: GeeksforGeeks JavaScript-Methods javascript-operators JavaScript-Questions JavaScript Web Technologies 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": "\n14 Jul, 2021" }, { "code": null, "e": 25255, "s": 24934, "text": "ECMAScript is a part of JavaScript language which is mostly used in web technology, building websites, or web apps. ECMAScript is growing as one of the world’s most widely used general-purpose programming languages. It is majorly used in embedding with web browsers and also adopted for server and embedded applications." }, { "code": null, "e": 25496, "s": 25255, "text": "New updates to ECMAScript will release out this July. The new improvements are introduced to make JavaScript more powerful and also make working easy for developers. It provides new functions, simple ways to do complex works, and much more." }, { "code": null, "e": 25572, "s": 25496, "text": "New updates: The new JavaScript features in ECMAScript 2021 are as follows:" }, { "code": null, "e": 25718, "s": 25572, "text": "1. Logical assignment operators: Logical assignment operators introduce new operators which combine logical operators and assignment expressions." }, { "code": null, "e": 25884, "s": 25718, "text": "And & Equals (&&=): It assigns when the value is truthy. Previous version:let x = 1;\nif(x){\n a = 10;\n} Output: x = 10New version:let x = 1;\nx &&= 10; Output: x = 10" }, { "code": null, "e": 25902, "s": 25884, "text": "Previous version:" }, { "code": null, "e": 25932, "s": 25902, "text": "let x = 1;\nif(x){\n a = 10;\n}" }, { "code": null, "e": 25942, "s": 25932, "text": " Output: " }, { "code": null, "e": 25949, "s": 25942, "text": "x = 10" }, { "code": null, "e": 25962, "s": 25949, "text": "New version:" }, { "code": null, "e": 25983, "s": 25962, "text": "let x = 1;\nx &&= 10;" }, { "code": null, "e": 25993, "s": 25983, "text": " Output: " }, { "code": null, "e": 26000, "s": 25993, "text": "x = 10" }, { "code": null, "e": 26336, "s": 26000, "text": "OR & Equals (||=): It assigns when the value is falsy. The assignment operation happens only if x is a falsy value. If x contains 1 which is a truthy value, assignment does not happen. Here x contains 0 therefore assignment happens.Previous version:let x = 0;\nx = x || 10; Output: x = 10 New version:let x = 0;\nx ||= 10 Output: x = 10" }, { "code": null, "e": 26354, "s": 26336, "text": "Previous version:" }, { "code": null, "e": 26378, "s": 26354, "text": "let x = 0;\nx = x || 10;" }, { "code": null, "e": 26387, "s": 26378, "text": " Output:" }, { "code": null, "e": 26395, "s": 26387, "text": " x = 10" }, { "code": null, "e": 26410, "s": 26397, "text": "New version:" }, { "code": null, "e": 26430, "s": 26410, "text": "let x = 0;\nx ||= 10" }, { "code": null, "e": 26439, "s": 26430, "text": " Output:" }, { "code": null, "e": 26447, "s": 26439, "text": " x = 10" }, { "code": null, "e": 26755, "s": 26447, "text": "Nullish coalescing & Equals (??=): Symbol ?? is a nullish coalescing operator in JavaScript. It checks if a value is null or undefined.let x;\nlet y = 10;\nx ??= y;\nconsole.log(x);\nconsole.log(y);Output: The value of x is undefined, therefore the right-hand side expression is evaluated and sets x to 10.10\n10" }, { "code": null, "e": 26815, "s": 26755, "text": "let x;\nlet y = 10;\nx ??= y;\nconsole.log(x);\nconsole.log(y);" }, { "code": null, "e": 26924, "s": 26815, "text": "Output: The value of x is undefined, therefore the right-hand side expression is evaluated and sets x to 10." }, { "code": null, "e": 26930, "s": 26924, "text": "10\n10" }, { "code": null, "e": 27058, "s": 26930, "text": "2. Numeric separators: To improve readability and to separate groups of digits, numeric literals use underscores as separators." }, { "code": null, "e": 27160, "s": 27058, "text": "// A billion dollar that I want to earn\nconst money = 1_000_000_000;\n\nconst money = 1_000_000_000.00;" }, { "code": null, "e": 27211, "s": 27160, "text": " It also can be used for Binary, Hex, Octal bases." }, { "code": null, "e": 27346, "s": 27211, "text": "3. String replaceAll(): If we want to replace all instances of a substring in string then this new method replaceAll() is very useful." }, { "code": null, "e": 27459, "s": 27346, "text": "const s = \"You are reading JavaScript 2021 new updates.\";\nconsole.log(s.replaceAll(\"JavaScript\", \"ECMAScript\"));" }, { "code": null, "e": 27470, "s": 27459, "text": " Output : " }, { "code": null, "e": 27515, "s": 27470, "text": "You are reading ECMAScript 2021 new updates." }, { "code": null, "e": 27743, "s": 27515, "text": "4. Promise.any: The Promise.any() method returns a promise that will resolve as soon as one of the promises is resolved. It is the opposite of the Promise.all() method which waits for all promises to resolve before it resolves." }, { "code": null, "e": 27924, "s": 27743, "text": "What will happen when all the promises are rejected, The method will throw an AggregateError exception with the rejection reason. We have written the code inside a try-catch block." }, { "code": null, "e": 28436, "s": 27924, "text": "const promiseOne = new Promise((resolve, reject) => {\n setTimeout(() => reject(), 1000);\n});\n\nconst promiseTwo = new Promise((resolve, reject) => {\n setTimeout(() => reject(), 2000);\n});\n\nconst promiseThree = new Promise((resolve, reject) => {\n setTimeout(() => reject(), 3000);\n});\n\ntry {\n const first = await Promise.any([\n promiseOne, promiseTwo, promiseThree\n ]);\n // If any of the promises was satisfied.\n} catch (error) {\n console.log(error);\n // AggregateError: If all promises were rejected\n}" }, { "code": null, "e": 28446, "s": 28438, "text": "Output:" }, { "code": null, "e": 28521, "s": 28446, "text": "await is only valid in async functions and the top-level bodies of modules" }, { "code": null, "e": 28644, "s": 28521, "text": "5. Private class methods: Private methods have scope inside the class only, so outside the class, they are not accessible." }, { "code": null, "e": 28662, "s": 28644, "text": "Previous version:" }, { "code": null, "e": 28838, "s": 28662, "text": "class GfG {\n showMe() {\n console.log(\"I am a geek\")\n }\n #notShowMe() {\n console.log(\"Hidden informations\")\n }\n}\n\nconst gfg = new GfG()\n\ngfg.showMe()\ngfg.notShowMe() " }, { "code": null, "e": 29009, "s": 28838, "text": "Output: Error is shown as follows. This is because notShowMe() is now a private method inside the class GfG and can only be accessed via a public method inside the class." }, { "code": null, "e": 29041, "s": 29009, "text": "gfg.notShowMe is not a function" }, { "code": null, "e": 29054, "s": 29041, "text": "New version:" }, { "code": null, "e": 29276, "s": 29054, "text": "class GfG {\n showMe() {\n console.log(\"I am a geek\");\n }\n #notShowMe() {\n console.log(\"Hidden informations\");\n }\n showAll() {\n this.showMe()\n this.#notShowMe();\n }\n}\n\nconst gfg = new GfG();\ngfg.showAll();" }, { "code": null, "e": 29488, "s": 29276, "text": "Output: We create a new public method called showAll() inside the class GfG. From this public method, we can access the private method #notShowMe() and since our new method is public we get the following result." }, { "code": null, "e": 29520, "s": 29488, "text": "I am a geek\nHidden informations" }, { "code": null, "e": 29688, "s": 29520, "text": "6. Private Getters and Setters: Just like private methods, now we can make getters and setters so that they can only be accessed inside a class or by instance created." }, { "code": null, "e": 29848, "s": 29688, "text": "class GfG {\n get #Name() {\n return \"GeeksforGeeks\"\n }\n \n get viewName() {\n return this.#Name\n }\n}\n\nlet name = new GfG();\nconsole.log(name.viewName);" }, { "code": null, "e": 29856, "s": 29848, "text": "Output:" }, { "code": null, "e": 29871, "s": 29856, "text": " GeeksforGeeks" }, { "code": null, "e": 29890, "s": 29871, "text": "JavaScript-Methods" }, { "code": null, "e": 29911, "s": 29890, "text": "javascript-operators" }, { "code": null, "e": 29932, "s": 29911, "text": "JavaScript-Questions" }, { "code": null, "e": 29943, "s": 29932, "text": "JavaScript" }, { "code": null, "e": 29960, "s": 29943, "text": "Web Technologies" }, { "code": null, "e": 30058, "s": 29960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30067, "s": 30058, "text": "Comments" }, { "code": null, "e": 30080, "s": 30067, "text": "Old Comments" }, { "code": null, "e": 30141, "s": 30080, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30182, "s": 30141, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30236, "s": 30182, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30276, "s": 30236, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30338, "s": 30276, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 30394, "s": 30338, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30427, "s": 30394, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30489, "s": 30427, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30532, "s": 30489, "text": "How to fetch data from an API in ReactJS ?" } ]
EJB - Callbacks
Callback is a mechanism by which the life cycle of an enterprise bean can be intercepted. EJB 3.0 specification has specified callbacks for which callback handler methods are created. EJB Container calls these callbacks. We can define callback methods in the EJB class itself or in a separate class. EJB 3.0 has provided many annotations for callbacks. Following is the list of callback annotations for stateless bean − Following is the list of callback annotations for stateful bean − Following is the list of callback annotations for message driven bean − Following is the list of callback annotations for entity bean − Let us create a test EJB application to test various callbacks in EJB. Create a project with a name EjbComponent under a package com.tutorialspoint.stateless as explained in the EJB - Create Application chapter. You can also use the project created in EJB - Persistence chapter as such for this chapter to add various callbacks to EJB. Create LibrarySessionBean.java and LibrarySessionBeanRemote as explained in the EJB - Create Application chapter. Keep rest of the files unchanged. Use Beans created in the EJB - Persistence chapter. Add callback methods as shown below. Keep rest of the files unchanged. Create a java class BookCallbackListener under package com.tutorialspoint.callback. This class will demonstrates the separation of callback methods. Clean and Build the application to make sure business logic is working as per the requirements. Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB. package com.tutorialspoint.callback; import javax.persistence.PrePersist; import javax.persistence.PostLoad; import javax.persistence.PostPersist; import javax.persistence.PostRemove; import javax.persistence.PostUpdate; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import com.tutorialspoint.entity.Book; public class BookCallbackListener { @PrePersist public void prePersist(Book book) { System.out.println("BookCallbackListener.prePersist:" + "Book to be created with book id: "+book.getId()); } @PostPersist public void postPersist(Object book) { System.out.println("BookCallbackListener.postPersist::" + "Book created with book id: "+((Book)book).getId()); } @PreRemove public void preRemove(Book book) { System.out.println("BookCallbackListener.preRemove:" + " About to delete Book: " + book.getId()); } @PostRemove public void postRemove(Book book) { System.out.println("BookCallbackListener.postRemove::" + " Deleted Book: " + book.getId()); } @PreUpdate public void preUpdate(Book book) { System.out.println("BookCallbackListener.preUpdate::" + " About to update Book: " + book.getId()); } @PostUpdate public void postUpdate(Book book) { System.out.println("BookCallbackListener.postUpdate::" + " Updated Book: " + book.getId()); } @PostLoad public void postLoad(Book book) { System.out.println("BookCallbackListener.postLoad::" + " Loaded Book: " + book.getId()); } } package com.tutorialspoint.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="books") public class Book implements Serializable{ private int id; private String name; public Book() { } @Id @GeneratedValue(strategy= GenerationType.IDENTITY) @Column(name="id") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } package com.tutorialspoint.stateful; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.PostActivate; import javax.ejb.PrePassivate; import javax.ejb.Stateful; @Stateful public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote { List<String> bookShelf; public LibraryStatefulSessionBean() { bookShelf = new ArrayList<String>(); } public void addBook(String bookName) { bookShelf.add(bookName); } public List<String> getBooks() { return bookShelf; } @PostConstruct public void postConstruct() { System.out.println("LibraryStatefulSessionBean.postConstruct::" + " bean created."); } @PreDestroy public void preDestroy() { System.out.println("LibraryStatefulSessionBean.preDestroy:" + " bean removed."); } @PostActivate public void postActivate() { System.out.println("LibraryStatefulSessionBean.postActivate:" + " bean activated."); } @PrePassivate public void prePassivate() { System.out.println("LibraryStatefulSessionBean.prePassivate:" + " bean passivated."); } } package com.tutorialspoint.stateful; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryStatefulSessionBeanRemote { void addBook(String bookName); List getBooks(); } package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public LibraryPersistentBean() {} @PersistenceContext(unitName="EntityEjbPU") private EntityManager entityManager; public void addBook(Book book) { entityManager.persist(book); } public List<Book> getBooks() { return entityManager.createQuery("From Book") .getResultList(); } @PostConstruct public void postConstruct() { System.out.println("postConstruct:: LibraryPersistentBean session bean" + " created with entity Manager object: "); } @PreDestroy public void preDestroy() { System.out.println("preDestroy: LibraryPersistentBean session" + " bean is removed "); } } package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryPersistentBeanRemote { void addBook(Book bookName); List<Book> getBooks(); } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote. JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote. We will be using this lookup string to get remote business object of type - com.tutorialspoint.stateless.LibraryPersistentBeanRemote We will be using this lookup string to get remote business object of type - com.tutorialspoint.stateless.LibraryPersistentBeanRemote ... 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBeanRemote ejbName: LibraryPersistentBean ... java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. InitialContext object will be used to lookup stateless session bean. package com.tutorialspoint.test; import com.tutorialspoint.stateful.LibrarySessionBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream("jndi.properties")); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testEntityEjb(); } private void showGUI() { System.out.println("**********************"); System.out.println("Welcome to Book Store"); System.out.println("**********************"); System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: "); } private void testEntityEjb() { try { int choice = 1; LibraryPersistentBeanRemote libraryBean = (LibraryPersistentBeanRemote) ctx.lookup("LibraryPersistentBean/remote"); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print("Enter book name: "); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println("Book(s) entered so far: " + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+". " + book.getName()); i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. Load properties from jndi.properties and initialize the InitialContext object. In testStatelessEjb() method, jndi lookup is done with the name - "LibrarySessionBean/remote" to obtain the remote business object (stateless EJB). In testStatelessEjb() method, jndi lookup is done with the name - "LibrarySessionBean/remote" to obtain the remote business object (stateless EJB). Then user is shown a library store User Interface and he/she is asked to enter a choice. Then user is shown a library store User Interface and he/she is asked to enter a choice. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in the database. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in the database. If user enters 2, system retrieves books using stateless session bean getBooks() method and exits. If user enters 2, system retrieves books using stateless session bean getBooks() method and exits. Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console. run: ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 1 Enter book name: Learn Java ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 2 Book(s) entered so far: 1 1. Learn Java BUILD SUCCESSFUL (total time: 13 seconds) You can find the following callback entries in JBoss log 14:08:34,293 INFO [STDOUT] postConstruct:: LibraryPersistentBean session bean created with entity Manager object ... 16:39:09,484 INFO [STDOUT] BookCallbackListener.prePersist:: Book to be created with book id: 0 16:39:09,531 INFO [STDOUT] BookCallbackListener.postPersist:: Book created with book id: 1 16:39:09,900 INFO [STDOUT] BookCallbackListener.postLoad:: Loaded Book: 1 ... Print Add Notes Bookmark this page
[ { "code": null, "e": 2400, "s": 2047, "text": "Callback is a mechanism by which the life cycle of an enterprise bean can be intercepted. EJB 3.0 specification has specified callbacks for which callback handler methods are created. EJB Container calls these callbacks. We can define callback methods in the EJB class itself or in a separate class. EJB 3.0 has provided many annotations for callbacks." }, { "code": null, "e": 2467, "s": 2400, "text": "Following is the list of callback annotations for stateless bean −" }, { "code": null, "e": 2533, "s": 2467, "text": "Following is the list of callback annotations for stateful bean −" }, { "code": null, "e": 2605, "s": 2533, "text": "Following is the list of callback annotations for message driven bean −" }, { "code": null, "e": 2669, "s": 2605, "text": "Following is the list of callback annotations for entity bean −" }, { "code": null, "e": 2740, "s": 2669, "text": "Let us create a test EJB application to test various callbacks in EJB." }, { "code": null, "e": 3005, "s": 2740, "text": "Create a project with a name EjbComponent under a package com.tutorialspoint.stateless as explained in the EJB - Create Application chapter. You can also use the project created in EJB - Persistence chapter as such for this chapter to add various callbacks to EJB." }, { "code": null, "e": 3153, "s": 3005, "text": "Create LibrarySessionBean.java and LibrarySessionBeanRemote as explained in the EJB - Create Application chapter. Keep rest of the files unchanged." }, { "code": null, "e": 3276, "s": 3153, "text": "Use Beans created in the EJB - Persistence chapter. Add callback methods as shown below. Keep rest of the files unchanged." }, { "code": null, "e": 3425, "s": 3276, "text": "Create a java class BookCallbackListener under package com.tutorialspoint.callback. This class will demonstrates the separation of callback methods." }, { "code": null, "e": 3521, "s": 3425, "text": "Clean and Build the application to make sure business logic is working as per the requirements." }, { "code": null, "e": 3688, "s": 3521, "text": "Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet." }, { "code": null, "e": 3853, "s": 3688, "text": "Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB." }, { "code": null, "e": 5440, "s": 3853, "text": "package com.tutorialspoint.callback;\n\nimport javax.persistence.PrePersist;\nimport javax.persistence.PostLoad;\nimport javax.persistence.PostPersist;\nimport javax.persistence.PostRemove;\nimport javax.persistence.PostUpdate;\nimport javax.persistence.PreRemove;\nimport javax.persistence.PreUpdate;\n\nimport com.tutorialspoint.entity.Book;\n\npublic class BookCallbackListener {\n \n @PrePersist\n public void prePersist(Book book) {\n System.out.println(\"BookCallbackListener.prePersist:\" \n + \"Book to be created with book id: \"+book.getId());\n }\n\n @PostPersist\n public void postPersist(Object book) {\n System.out.println(\"BookCallbackListener.postPersist::\"\n + \"Book created with book id: \"+((Book)book).getId());\n }\n\n @PreRemove\n public void preRemove(Book book) {\n System.out.println(\"BookCallbackListener.preRemove:\"\n + \" About to delete Book: \" + book.getId());\n }\n\n @PostRemove\n public void postRemove(Book book) {\n System.out.println(\"BookCallbackListener.postRemove::\"\n + \" Deleted Book: \" + book.getId());\n }\n\n @PreUpdate\n public void preUpdate(Book book) {\n System.out.println(\"BookCallbackListener.preUpdate::\"\n + \" About to update Book: \" + book.getId());\n }\n\n @PostUpdate\n public void postUpdate(Book book) {\n System.out.println(\"BookCallbackListener.postUpdate::\"\n + \" Updated Book: \" + book.getId());\n }\n\n @PostLoad\n public void postLoad(Book book) {\n System.out.println(\"BookCallbackListener.postLoad::\"\n + \" Loaded Book: \" + book.getId());\n }\n}" }, { "code": null, "e": 6233, "s": 5440, "text": "package com.tutorialspoint.entity;\n \nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EntityListeners;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n \n@Entity\n@Table(name=\"books\")\npublic class Book implements Serializable{\n \n private int id;\n private String name;\n \n public Book() { \n }\n \n @Id\n @GeneratedValue(strategy= GenerationType.IDENTITY)\n @Column(name=\"id\")\n public int getId() {\n return id;\n }\n \n public void setId(int id) {\n this.id = id;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n } \n}" }, { "code": null, "e": 7480, "s": 6233, "text": "package com.tutorialspoint.stateful;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.annotation.PostConstruct;\nimport javax.annotation.PreDestroy;\n\nimport javax.ejb.PostActivate;\nimport javax.ejb.PrePassivate;\nimport javax.ejb.Stateful;\n\n@Stateful\npublic class LibraryStatefulSessionBean \n implements LibraryStatefulSessionBeanRemote {\n List<String> bookShelf; \n\n public LibraryStatefulSessionBean() {\n bookShelf = new ArrayList<String>();\n }\n\n public void addBook(String bookName) {\n bookShelf.add(bookName);\n } \n\n public List<String> getBooks() {\n return bookShelf;\n }\n\n @PostConstruct\n public void postConstruct() {\n System.out.println(\"LibraryStatefulSessionBean.postConstruct::\"\n + \" bean created.\");\n }\n\n @PreDestroy\n public void preDestroy() {\n System.out.println(\"LibraryStatefulSessionBean.preDestroy:\"\n + \" bean removed.\");\n }\n\n @PostActivate\n public void postActivate() {\n System.out.println(\"LibraryStatefulSessionBean.postActivate:\"\n + \" bean activated.\");\n }\n\n @PrePassivate\n public void prePassivate() {\n System.out.println(\"LibraryStatefulSessionBean.prePassivate:\"\n + \" bean passivated.\");\n } \n}" }, { "code": null, "e": 7683, "s": 7480, "text": "package com.tutorialspoint.stateful;\n\nimport java.util.List;\nimport javax.ejb.Remote;\n\n@Remote\npublic interface LibraryStatefulSessionBeanRemote {\n void addBook(String bookName);\n List getBooks();\n}" }, { "code": null, "e": 8750, "s": 7683, "text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.util.List;\n\nimport javax.annotation.PostConstruct;\nimport javax.annotation.PreDestroy;\n\nimport javax.ejb.Stateless;\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\n\n@Stateless\npublic class LibraryPersistentBean \n implements LibraryPersistentBeanRemote {\n \n public LibraryPersistentBean() {}\n\n @PersistenceContext(unitName=\"EntityEjbPU\")\n private EntityManager entityManager; \n\n public void addBook(Book book) {\n entityManager.persist(book);\n } \n\n public List<Book> getBooks() { \n return entityManager.createQuery(\"From Book\")\n .getResultList();\n }\n\n @PostConstruct\n public void postConstruct() {\n System.out.println(\"postConstruct:: LibraryPersistentBean session bean\"\n + \" created with entity Manager object: \");\n }\n\n @PreDestroy\n public void preDestroy() {\n System.out.println(\"preDestroy: LibraryPersistentBean session\"\n + \" bean is removed \");\n }\n}" }, { "code": null, "e": 8999, "s": 8750, "text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.util.List;\nimport javax.ejb.Remote;\n\n@Remote\npublic interface LibraryPersistentBeanRemote {\n\n void addBook(Book bookName);\n\n List<Book> getBooks();\n \n}" }, { "code": null, "e": 9078, "s": 8999, "text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log." }, { "code": null, "e": 9157, "s": 9078, "text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log." }, { "code": null, "e": 9255, "s": 9157, "text": "JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote." }, { "code": null, "e": 9353, "s": 9255, "text": "JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote." }, { "code": null, "e": 9486, "s": 9353, "text": "We will be using this lookup string to get remote business object of type -\ncom.tutorialspoint.stateless.LibraryPersistentBeanRemote" }, { "code": null, "e": 9619, "s": 9486, "text": "We will be using this lookup string to get remote business object of type -\ncom.tutorialspoint.stateless.LibraryPersistentBeanRemote" }, { "code": null, "e": 10177, "s": 9619, "text": "...\n16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface\n LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBeanRemote ejbName: LibraryPersistentBean\n... \n" }, { "code": null, "e": 10345, "s": 10177, "text": "java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\njava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces\njava.naming.provider.url=localhost" }, { "code": null, "e": 10435, "s": 10345, "text": "These properties are used to initialize the InitialContext object of java naming service." }, { "code": null, "e": 10525, "s": 10435, "text": "These properties are used to initialize the InitialContext object of java naming service." }, { "code": null, "e": 10594, "s": 10525, "text": "InitialContext object will be used to lookup stateless session bean." }, { "code": null, "e": 10663, "s": 10594, "text": "InitialContext object will be used to lookup stateless session bean." }, { "code": null, "e": 13279, "s": 10663, "text": "package com.tutorialspoint.test;\n \nimport com.tutorialspoint.stateful.LibrarySessionBeanRemote;\n\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\nimport java.util.List;\nimport java.util.Properties;\n\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n\npublic class EJBTester {\n\n BufferedReader brConsoleReader = null; \n Properties props;\n InitialContext ctx;\n {\n props = new Properties();\n try {\n props.load(new FileInputStream(\"jndi.properties\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n try {\n ctx = new InitialContext(props); \n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n brConsoleReader = \n new BufferedReader(new InputStreamReader(System.in));\n }\n \n public static void main(String[] args) {\n\n EJBTester ejbTester = new EJBTester();\n\n ejbTester.testEntityEjb();\n }\n \n private void showGUI() {\n System.out.println(\"**********************\");\n System.out.println(\"Welcome to Book Store\");\n System.out.println(\"**********************\");\n System.out.print(\"Options \\n1. Add Book\\n2. Exit \\nEnter Choice: \");\n }\n \n private void testEntityEjb() { \n try {\n int choice = 1; \n\n LibraryPersistentBeanRemote libraryBean = \n (LibraryPersistentBeanRemote)\n ctx.lookup(\"LibraryPersistentBean/remote\");\n\n while (choice != 2) {\n String bookName;\n showGUI();\n String strChoice = brConsoleReader.readLine();\n choice = Integer.parseInt(strChoice);\n if (choice == 1) {\n System.out.print(\"Enter book name: \");\n bookName = brConsoleReader.readLine();\n Book book = new Book();\n book.setName(bookName);\n libraryBean.addBook(book); \n } else if (choice == 2) {\n break;\n }\n }\n\n List<Book> booksList = libraryBean.getBooks();\n\n System.out.println(\"Book(s) entered so far: \" + booksList.size());\n int i = 0;\n for (Book book:booksList) {\n System.out.println((i+1)+\". \" + book.getName());\n i++;\n } \n\n } catch (Exception e) {\n System.out.println(e.getMessage());\n e.printStackTrace();\n }finally {\n try {\n if(brConsoleReader !=null) {\n brConsoleReader.close();\n }\n } catch (IOException ex) {\n System.out.println(ex.getMessage());\n }\n } \n } \n}" }, { "code": null, "e": 13320, "s": 13279, "text": "EJBTester performs the following tasks −" }, { "code": null, "e": 13399, "s": 13320, "text": "Load properties from jndi.properties and initialize the InitialContext object." }, { "code": null, "e": 13478, "s": 13399, "text": "Load properties from jndi.properties and initialize the InitialContext object." }, { "code": null, "e": 13626, "s": 13478, "text": "In testStatelessEjb() method, jndi lookup is done with the name - \"LibrarySessionBean/remote\" to obtain the remote business object (stateless EJB)." }, { "code": null, "e": 13774, "s": 13626, "text": "In testStatelessEjb() method, jndi lookup is done with the name - \"LibrarySessionBean/remote\" to obtain the remote business object (stateless EJB)." }, { "code": null, "e": 13863, "s": 13774, "text": "Then user is shown a library store User Interface and he/she is asked to enter a choice." }, { "code": null, "e": 13952, "s": 13863, "text": "Then user is shown a library store User Interface and he/she is asked to enter a choice." }, { "code": null, "e": 14120, "s": 13952, "text": "If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in the database." }, { "code": null, "e": 14288, "s": 14120, "text": "If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in the database." }, { "code": null, "e": 14387, "s": 14288, "text": "If user enters 2, system retrieves books using stateless session bean getBooks() method and exits." }, { "code": null, "e": 14486, "s": 14387, "text": "If user enters 2, system retrieves books using stateless session bean getBooks() method and exits." }, { "code": null, "e": 14581, "s": 14486, "text": "Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file." }, { "code": null, "e": 14630, "s": 14581, "text": "Verify the following output in Netbeans console." }, { "code": null, "e": 14974, "s": 14630, "text": "run:\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 1\nEnter book name: Learn Java\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 2\nBook(s) entered so far: 1\n1. Learn Java\nBUILD SUCCESSFUL (total time: 13 seconds)\n" }, { "code": null, "e": 15031, "s": 14974, "text": "You can find the following callback entries in JBoss log" }, { "code": null, "e": 15418, "s": 15031, "text": "14:08:34,293 INFO [STDOUT] postConstruct:: LibraryPersistentBean session bean created with entity Manager object\n...\n16:39:09,484 INFO [STDOUT] BookCallbackListener.prePersist:: Book to be created with book id: 0\n16:39:09,531 INFO [STDOUT] BookCallbackListener.postPersist:: Book created with book id: 1\n16:39:09,900 INFO [STDOUT] BookCallbackListener.postLoad:: Loaded Book: 1\n...\n" }, { "code": null, "e": 15425, "s": 15418, "text": " Print" }, { "code": null, "e": 15436, "s": 15425, "text": " Add Notes" } ]
OpenNLP - Sentence Detection
While processing a natural language, deciding the beginning and end of the sentences is one of the problems to be addressed. This process is known as Sentence Boundary Disambiguation (SBD) or simply sentence breaking. The techniques we use to detect the sentences in the given text, depends on the language of the text. We can detect the sentences in the given text in Java using, Regular Expressions, and a set of simple rules. For example, let us assume a period, a question mark, or an exclamation mark ends a sentence in the given text, then we can split the sentence using the split() method of the String class. Here, we have to pass a regular expression in String format. Following is the program which determines the sentences in a given text using Java regular expressions (split method). Save this program in a file with the name SentenceDetection_RE.java. public class SentenceDetection_RE { public static void main(String args[]){ String sentence = " Hi. How are you? Welcome to Tutorialspoint. " + "We provide free tutorials on various technologies"; String simple = "[.?!]"; String[] splitString = (sentence.split(simple)); for (String string : splitString) System.out.println(string); } } Compile and execute the saved java file from the command prompt using the following commands. javac SentenceDetection_RE.java java SentenceDetection_RE On executing, the above program creates a PDF document displaying the following message. Hi How are you Welcome to Tutorialspoint We provide free tutorials on various technologies To detect sentences, OpenNLP uses a predefined model, a file named en-sent.bin. This predefined model is trained to detect sentences in a given raw text. The opennlp.tools.sentdetect package contains the classes and interfaces that are used to perform the sentence detection task. To detect a sentence using OpenNLP library, you need to − Load the en-sent.bin model using the SentenceModel class Load the en-sent.bin model using the SentenceModel class Instantiate the SentenceDetectorME class. Instantiate the SentenceDetectorME class. Detect the sentences using the sentDetect() method of this class. Detect the sentences using the sentDetect() method of this class. Following are the steps to be followed to write a program which detects the sentences from the given raw text. The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect. To load a sentence detection model − Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor). Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor). Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block − Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block − //Loading sentence detector model InputStream inputStream = new FileInputStream("C:/OpenNLP_models/ensent.bin"); SentenceModel model = new SentenceModel(inputStream); The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence. Instantiate this class and pass the model object created in the previous step, as shown below. //Instantiating the SentenceDetectorME class SentenceDetectorME detector = new SentenceDetectorME(model); The sentDetect() method of the SentenceDetectorME class is used to detect the sentences in the raw text passed to it. This method accepts a String variable as a parameter. Invoke this method by passing the String format of the sentence to this method. //Detecting the sentence String sentences[] = detector.sentDetect(sentence); Example Following is the program which detects the sentences in a given raw text. Save this program in a file with named SentenceDetectionME.java. import java.io.FileInputStream; import java.io.InputStream; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; public class SentenceDetectionME { public static void main(String args[]) throws Exception { String sentence = "Hi. How are you? Welcome to Tutorialspoint. " + "We provide free tutorials on various technologies"; //Loading sentence detector model InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin"); SentenceModel model = new SentenceModel(inputStream); //Instantiating the SentenceDetectorME class SentenceDetectorME detector = new SentenceDetectorME(model); //Detecting the sentence String sentences[] = detector.sentDetect(sentence); //Printing the sentences for(String sent : sentences) System.out.println(sent); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac SentenceDetectorME.java java SentenceDetectorME On executing, the above program reads the given String and detects the sentences in it and displays the following output. Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies We can also detect the positions of the sentences using the sentPosDetect() method of the SentenceDetectorME class. Following are the steps to be followed to write a program which detects the positions of the sentences from the given raw text. The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect. To load a sentence detection model − Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor). Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor). Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block. Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block. //Loading sentence detector model InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin"); SentenceModel model = new SentenceModel(inputStream); The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence. Instantiate this class and pass the model object created in the previous step. //Instantiating the SentenceDetectorME class SentenceDetectorME detector = new SentenceDetectorME(model); The sentPosDetect() method of the SentenceDetectorME class is used to detect the positions of the sentences in the raw text passed to it. This method accepts a String variable as a parameter. Invoke this method by passing the String format of the sentence as a parameter to this method. //Detecting the position of the sentences in the paragraph Span[] spans = detector.sentPosDetect(sentence); The sentPosDetect() method of the SentenceDetectorME class returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets. You can store the spans returned by the sentPosDetect() method in the Span array and print them, as shown in the following code block. //Printing the sentences and their spans of a sentence for (Span span : spans) System.out.println(paragraph.substring(span); Example Following is the program which detects the sentences in the given raw text. Save this program in a file with named SentenceDetectionME.java. import java.io.FileInputStream; import java.io.InputStream; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.util.Span; public class SentencePosDetection { public static void main(String args[]) throws Exception { String paragraph = "Hi. How are you? Welcome to Tutorialspoint. " + "We provide free tutorials on various technologies"; //Loading sentence detector model InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin"); SentenceModel model = new SentenceModel(inputStream); //Instantiating the SentenceDetectorME class SentenceDetectorME detector = new SentenceDetectorME(model); //Detecting the position of the sentences in the raw text Span spans[] = detector.sentPosDetect(paragraph); //Printing the spans of the sentences in the paragraph for (Span span : spans) System.out.println(span); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac SentencePosDetection.java java SentencePosDetection On executing, the above program reads the given String and detects the sentences in it and displays the following output. [0..16) [17..43) [44..93) The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the sentences and their spans (positions) together, as shown in the following code block. for (Span span : spans) System.out.println(sen.substring(span.getStart(), span.getEnd())+" "+ span); Following is the program to detect the sentences from the given raw text and display them along with their positions. Save this program in a file with name SentencesAndPosDetection.java. import java.io.FileInputStream; import java.io.InputStream; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.util.Span; public class SentencesAndPosDetection { public static void main(String args[]) throws Exception { String sen = "Hi. How are you? Welcome to Tutorialspoint." + " We provide free tutorials on various technologies"; //Loading a sentence model InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin"); SentenceModel model = new SentenceModel(inputStream); //Instantiating the SentenceDetectorME class SentenceDetectorME detector = new SentenceDetectorME(model); //Detecting the position of the sentences in the paragraph Span[] spans = detector.sentPosDetect(sen); //Printing the sentences and their spans of a paragraph for (Span span : spans) System.out.println(sen.substring(span.getStart(), span.getEnd())+" "+ span); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac SentencesAndPosDetection.java java SentencesAndPosDetection On executing, the above program reads the given String and detects the sentences along with their positions and displays the following output. Hi. How are you? [0..16) Welcome to Tutorialspoint. [17..43) We provide free tutorials on various technologies [44..93) The getSentenceProbabilities() method of the SentenceDetectorME class returns the probabilities associated with the most recent calls to the sentDetect() method. //Getting the probabilities of the last decoded sequence double[] probs = detector.getSentenceProbabilities(); Following is the program to print the probabilities associated with the calls to the sentDetect() method. Save this program in a file with the name SentenceDetectionMEProbs.java. import java.io.FileInputStream; import java.io.InputStream; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; public class SentenceDetectionMEProbs { public static void main(String args[]) throws Exception { String sentence = "Hi. How are you? Welcome to Tutorialspoint. " + "We provide free tutorials on various technologies"; //Loading sentence detector model InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin"); SentenceModel model = new SentenceModel(inputStream); //Instantiating the SentenceDetectorME class SentenceDetectorME detector = new SentenceDetectorME(model); //Detecting the sentence String sentences[] = detector.sentDetect(sentence); //Printing the sentences for(String sent : sentences) System.out.println(sent); //Getting the probabilities of the last decoded sequence double[] probs = detector.getSentenceProbabilities(); System.out.println(" "); for(int i = 0; i<probs.length; i++) System.out.println(probs[i]); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac SentenceDetectionMEProbs.java java SentenceDetectionMEProbs On executing, the above program reads the given String and detects the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the sentDetect() method, as shown below. Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies 0.9240246995179983 0.9957680129995953 1.0 Print Add Notes Bookmark this page
[ { "code": null, "e": 2070, "s": 1852, "text": "While processing a natural language, deciding the beginning and end of the sentences is one of the problems to be addressed. This process is known as Sentence Boundary Disambiguation (SBD) or simply sentence breaking." }, { "code": null, "e": 2172, "s": 2070, "text": "The techniques we use to detect the sentences in the given text, depends on the language of the text." }, { "code": null, "e": 2281, "s": 2172, "text": "We can detect the sentences in the given text in Java using, Regular Expressions, and a set of simple rules." }, { "code": null, "e": 2531, "s": 2281, "text": "For example, let us assume a period, a question mark, or an exclamation mark ends a sentence in the given text, then we can split the sentence using the split() method of the String class. Here, we have to pass a regular expression in String format." }, { "code": null, "e": 2719, "s": 2531, "text": "Following is the program which determines the sentences in a given text using Java regular expressions (split method). Save this program in a file with the name SentenceDetection_RE.java." }, { "code": null, "e": 3142, "s": 2719, "text": "public class SentenceDetection_RE { \n public static void main(String args[]){ \n \n String sentence = \" Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n String simple = \"[.?!]\"; \n String[] splitString = (sentence.split(simple)); \n for (String string : splitString) \n System.out.println(string); \n } \n}" }, { "code": null, "e": 3236, "s": 3142, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 3295, "s": 3236, "text": "javac SentenceDetection_RE.java \njava SentenceDetection_RE" }, { "code": null, "e": 3384, "s": 3295, "text": "On executing, the above program creates a PDF document displaying the following message." }, { "code": null, "e": 3479, "s": 3384, "text": "Hi \nHow are you \nWelcome to Tutorialspoint \nWe provide free tutorials on various technologies\n" }, { "code": null, "e": 3633, "s": 3479, "text": "To detect sentences, OpenNLP uses a predefined model, a file named en-sent.bin. This predefined model is trained to detect sentences in a given raw text." }, { "code": null, "e": 3760, "s": 3633, "text": "The opennlp.tools.sentdetect package contains the classes and interfaces that are used to perform the sentence detection task." }, { "code": null, "e": 3818, "s": 3760, "text": "To detect a sentence using OpenNLP library, you need to −" }, { "code": null, "e": 3875, "s": 3818, "text": "Load the en-sent.bin model using the SentenceModel class" }, { "code": null, "e": 3932, "s": 3875, "text": "Load the en-sent.bin model using the SentenceModel class" }, { "code": null, "e": 3974, "s": 3932, "text": "Instantiate the SentenceDetectorME class." }, { "code": null, "e": 4016, "s": 3974, "text": "Instantiate the SentenceDetectorME class." }, { "code": null, "e": 4082, "s": 4016, "text": "Detect the sentences using the sentDetect() method of this class." }, { "code": null, "e": 4148, "s": 4082, "text": "Detect the sentences using the sentDetect() method of this class." }, { "code": null, "e": 4259, "s": 4148, "text": "Following are the steps to be followed to write a program which detects the sentences from the given raw text." }, { "code": null, "e": 4396, "s": 4259, "text": "The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect." }, { "code": null, "e": 4433, "s": 4396, "text": "To load a sentence detection model −" }, { "code": null, "e": 4577, "s": 4433, "text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)." }, { "code": null, "e": 4721, "s": 4577, "text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)." }, { "code": null, "e": 4877, "s": 4721, "text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block −" }, { "code": null, "e": 5033, "s": 4877, "text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block −" }, { "code": null, "e": 5202, "s": 5033, "text": "//Loading sentence detector model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/ensent.bin\"); \nSentenceModel model = new SentenceModel(inputStream);" }, { "code": null, "e": 5471, "s": 5202, "text": "The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence." }, { "code": null, "e": 5566, "s": 5471, "text": "Instantiate this class and pass the model object created in the previous step, as shown below." }, { "code": null, "e": 5673, "s": 5566, "text": "//Instantiating the SentenceDetectorME class \nSentenceDetectorME detector = new SentenceDetectorME(model);" }, { "code": null, "e": 5845, "s": 5673, "text": "The sentDetect() method of the SentenceDetectorME class is used to detect the sentences in the raw text passed to it. This method accepts a String variable as a parameter." }, { "code": null, "e": 5925, "s": 5845, "text": "Invoke this method by passing the String format of the sentence to this method." }, { "code": null, "e": 6003, "s": 5925, "text": "//Detecting the sentence \nString sentences[] = detector.sentDetect(sentence);" }, { "code": null, "e": 6011, "s": 6003, "text": "Example" }, { "code": null, "e": 6150, "s": 6011, "text": "Following is the program which detects the sentences in a given raw text. Save this program in a file with named SentenceDetectionME.java." }, { "code": null, "e": 7105, "s": 6150, "text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \n\npublic class SentenceDetectionME { \n \n public static void main(String args[]) throws Exception { \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading sentence detector model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class \n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the sentence\n String sentences[] = detector.sentDetect(sentence); \n \n //Printing the sentences \n for(String sent : sentences) \n System.out.println(sent); \n } \n}" }, { "code": null, "e": 7200, "s": 7105, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 7255, "s": 7200, "text": "javac SentenceDetectorME.java \njava SentenceDetectorME" }, { "code": null, "e": 7377, "s": 7255, "text": "On executing, the above program reads the given String and detects the sentences in it and displays the following output." }, { "code": null, "e": 7474, "s": 7377, "text": "Hi. How are you? \nWelcome to Tutorialspoint. \nWe provide free tutorials on various technologies\n" }, { "code": null, "e": 7590, "s": 7474, "text": "We can also detect the positions of the sentences using the sentPosDetect() method of the SentenceDetectorME class." }, { "code": null, "e": 7718, "s": 7590, "text": "Following are the steps to be followed to write a program which detects the positions of the sentences from the given raw text." }, { "code": null, "e": 7855, "s": 7718, "text": "The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect." }, { "code": null, "e": 7892, "s": 7855, "text": "To load a sentence detection model −" }, { "code": null, "e": 8036, "s": 7892, "text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)." }, { "code": null, "e": 8180, "s": 8036, "text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)." }, { "code": null, "e": 8336, "s": 8180, "text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block." }, { "code": null, "e": 8492, "s": 8336, "text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block." }, { "code": null, "e": 8662, "s": 8492, "text": "//Loading sentence detector model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \nSentenceModel model = new SentenceModel(inputStream);" }, { "code": null, "e": 8931, "s": 8662, "text": "The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence." }, { "code": null, "e": 9010, "s": 8931, "text": "Instantiate this class and pass the model object created in the previous step." }, { "code": null, "e": 9118, "s": 9010, "text": "//Instantiating the SentenceDetectorME class \nSentenceDetectorME detector = new SentenceDetectorME(model); " }, { "code": null, "e": 9310, "s": 9118, "text": "The sentPosDetect() method of the SentenceDetectorME class is used to detect the positions of the sentences in the raw text passed to it. This method accepts a String variable as a parameter." }, { "code": null, "e": 9405, "s": 9310, "text": "Invoke this method by passing the String format of the sentence as a parameter to this method." }, { "code": null, "e": 9516, "s": 9405, "text": "//Detecting the position of the sentences in the paragraph \nSpan[] spans = detector.sentPosDetect(sentence); " }, { "code": null, "e": 9728, "s": 9516, "text": "The sentPosDetect() method of the SentenceDetectorME class returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets." }, { "code": null, "e": 9863, "s": 9728, "text": "You can store the spans returned by the sentPosDetect() method in the Span array and print them, as shown in the following code block." }, { "code": null, "e": 9999, "s": 9863, "text": "//Printing the sentences and their spans of a sentence \nfor (Span span : spans) \nSystem.out.println(paragraph.substring(span); " }, { "code": null, "e": 10007, "s": 9999, "text": "Example" }, { "code": null, "e": 10148, "s": 10007, "text": "Following is the program which detects the sentences in the given raw text. Save this program in a file with named SentenceDetectionME.java." }, { "code": null, "e": 11201, "s": 10148, "text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n \nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \nimport opennlp.tools.util.Span;\n\npublic class SentencePosDetection { \n \n public static void main(String args[]) throws Exception { \n \n String paragraph = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading sentence detector model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class \n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the position of the sentences in the raw text \n Span spans[] = detector.sentPosDetect(paragraph); \n \n //Printing the spans of the sentences in the paragraph \n for (Span span : spans) \n System.out.println(span); \n } \n}" }, { "code": null, "e": 11296, "s": 11201, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 11355, "s": 11296, "text": "javac SentencePosDetection.java \njava SentencePosDetection" }, { "code": null, "e": 11477, "s": 11355, "text": "On executing, the above program reads the given String and detects the sentences in it and displays the following output." }, { "code": null, "e": 11506, "s": 11477, "text": "[0..16) \n[17..43) \n[44..93)\n" }, { "code": null, "e": 11744, "s": 11506, "text": "The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the sentences and their spans (positions) together, as shown in the following code block." }, { "code": null, "e": 11858, "s": 11744, "text": "for (Span span : spans) \n System.out.println(sen.substring(span.getStart(), span.getEnd())+\" \"+ span); " }, { "code": null, "e": 12045, "s": 11858, "text": "Following is the program to detect the sentences from the given raw text and display them along with their positions. Save this program in a file with name SentencesAndPosDetection.java." }, { "code": null, "e": 13136, "s": 12045, "text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \nimport opennlp.tools.util.Span; \n \npublic class SentencesAndPosDetection { \n \n public static void main(String args[]) throws Exception { \n \n String sen = \"Hi. How are you? Welcome to Tutorialspoint.\" \n + \" We provide free tutorials on various technologies\"; \n //Loading a sentence model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class \n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the position of the sentences in the paragraph \n Span[] spans = detector.sentPosDetect(sen); \n \n //Printing the sentences and their spans of a paragraph \n for (Span span : spans) \n System.out.println(sen.substring(span.getStart(), span.getEnd())+\" \"+ span); \n } \n} " }, { "code": null, "e": 13231, "s": 13136, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 13298, "s": 13231, "text": "javac SentencesAndPosDetection.java \njava SentencesAndPosDetection" }, { "code": null, "e": 13441, "s": 13298, "text": "On executing, the above program reads the given String and detects the sentences along with their positions and displays the following output." }, { "code": null, "e": 13565, "s": 13441, "text": "Hi. How are you? [0..16) \nWelcome to Tutorialspoint. [17..43) \nWe provide free tutorials on various technologies [44..93)\n" }, { "code": null, "e": 13727, "s": 13565, "text": "The getSentenceProbabilities() method of the SentenceDetectorME class returns the probabilities associated with the most recent calls to the sentDetect() method." }, { "code": null, "e": 13847, "s": 13727, "text": "//Getting the probabilities of the last decoded sequence \ndouble[] probs = detector.getSentenceProbabilities(); \n" }, { "code": null, "e": 14026, "s": 13847, "text": "Following is the program to print the probabilities associated with the calls to the sentDetect() method. Save this program in a file with the name SentenceDetectionMEProbs.java." }, { "code": null, "e": 15268, "s": 14026, "text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \n\npublic class SentenceDetectionMEProbs { \n \n public static void main(String args[]) throws Exception { \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading sentence detector model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\");\n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class\n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the sentence \n String sentences[] = detector.sentDetect(sentence); \n \n //Printing the sentences \n for(String sent : sentences) \n System.out.println(sent); \n \n //Getting the probabilities of the last decoded sequence \n double[] probs = detector.getSentenceProbabilities(); \n \n System.out.println(\" \"); \n \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n} " }, { "code": null, "e": 15363, "s": 15268, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 15431, "s": 15363, "text": "javac SentenceDetectionMEProbs.java \njava SentenceDetectionMEProbs\n" }, { "code": null, "e": 15658, "s": 15431, "text": "On executing, the above program reads the given String and detects the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the sentDetect() method, as shown below." }, { "code": null, "e": 15804, "s": 15658, "text": "Hi. How are you? \nWelcome to Tutorialspoint. \nWe provide free tutorials on various technologies \n \n0.9240246995179983 \n0.9957680129995953 \n1.0\n" }, { "code": null, "e": 15811, "s": 15804, "text": " Print" }, { "code": null, "e": 15822, "s": 15811, "text": " Add Notes" } ]
Express.js | app.post() Function - GeeksforGeeks
10 Jun, 2020 The app.post() function routes the HTTP POST requests to the specified path with the specified callback functions. Syntax: app.post(path, callback [, callback ...]) Arguments: Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above. Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above. A string representing a path. A path pattern. A regular expression pattern to match paths. An array of combinations of any of the above. Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above. A middleware function. A series of middleware functions (separated by commas). An array of middleware functions. A combination of all of the above. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Filename: index.js var express = require('express');var app = express();var PORT = 3000; app.post('/', (req, res) => { res.send("POST Request Called")}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now make POST request to http://localhost:3000/ and you will get the following output:POST Request Called The project structure will look like this: Make sure you have installed express module using following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now make POST request to http://localhost:3000/ and you will get the following output:POST Request Called POST Request Called So this is how you can use the express app.post() function which routes HTTP POST requests to the specified path with the specified callback functions. Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Top 10 Front End Developer Skills That You Need in 2022 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24310, "s": 24282, "text": "\n10 Jun, 2020" }, { "code": null, "e": 24425, "s": 24310, "text": "The app.post() function routes the HTTP POST requests to the specified path with the specified callback functions." }, { "code": null, "e": 24433, "s": 24425, "text": "Syntax:" }, { "code": null, "e": 24475, "s": 24433, "text": "app.post(path, callback [, callback ...])" }, { "code": null, "e": 24486, "s": 24475, "text": "Arguments:" }, { "code": null, "e": 24878, "s": 24486, "text": "Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above." }, { "code": null, "e": 25090, "s": 24878, "text": "Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above." }, { "code": null, "e": 25120, "s": 25090, "text": "A string representing a path." }, { "code": null, "e": 25136, "s": 25120, "text": "A path pattern." }, { "code": null, "e": 25181, "s": 25136, "text": "A regular expression pattern to match paths." }, { "code": null, "e": 25227, "s": 25181, "text": "An array of combinations of any of the above." }, { "code": null, "e": 25408, "s": 25227, "text": "Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above." }, { "code": null, "e": 25431, "s": 25408, "text": "A middleware function." }, { "code": null, "e": 25487, "s": 25431, "text": "A series of middleware functions (separated by commas)." }, { "code": null, "e": 25521, "s": 25487, "text": "An array of middleware functions." }, { "code": null, "e": 25556, "s": 25521, "text": "A combination of all of the above." }, { "code": null, "e": 25588, "s": 25556, "text": "Installation of express module:" }, { "code": null, "e": 25979, "s": 25588, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 26100, "s": 25979, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 26120, "s": 26100, "text": "npm install express" }, { "code": null, "e": 26244, "s": 26120, "text": "After installing express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 26264, "s": 26244, "text": "npm version express" }, { "code": null, "e": 26412, "s": 26264, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 26426, "s": 26412, "text": "node index.js" }, { "code": null, "e": 26445, "s": 26426, "text": "Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.post('/', (req, res) => { res.send(\"POST Request Called\")}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);}); ", "e": 26698, "s": 26445, "text": null }, { "code": null, "e": 26724, "s": 26698, "text": "Steps to run the program:" }, { "code": null, "e": 27047, "s": 26724, "text": "The project structure will look like this:Make sure you have installed express module using following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow make POST request to http://localhost:3000/ and you will get the following output:POST Request Called" }, { "code": null, "e": 27090, "s": 27047, "text": "The project structure will look like this:" }, { "code": null, "e": 27178, "s": 27090, "text": "Make sure you have installed express module using following command:npm install express" }, { "code": null, "e": 27198, "s": 27178, "text": "npm install express" }, { "code": null, "e": 27287, "s": 27198, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 27301, "s": 27287, "text": "node index.js" }, { "code": null, "e": 27309, "s": 27301, "text": "Output:" }, { "code": null, "e": 27340, "s": 27309, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 27446, "s": 27340, "text": "Now make POST request to http://localhost:3000/ and you will get the following output:POST Request Called" }, { "code": null, "e": 27466, "s": 27446, "text": "POST Request Called" }, { "code": null, "e": 27618, "s": 27466, "text": "So this is how you can use the express app.post() function which routes HTTP POST requests to the specified path with the specified callback functions." }, { "code": null, "e": 27629, "s": 27618, "text": "Express.js" }, { "code": null, "e": 27637, "s": 27629, "text": "Node.js" }, { "code": null, "e": 27654, "s": 27637, "text": "Web Technologies" }, { "code": null, "e": 27752, "s": 27654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27761, "s": 27752, "text": "Comments" }, { "code": null, "e": 27774, "s": 27761, "text": "Old Comments" }, { "code": null, "e": 27803, "s": 27774, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27833, "s": 27803, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27890, "s": 27833, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27944, "s": 27890, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27981, "s": 27944, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28037, "s": 27981, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28099, "s": 28037, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28142, "s": 28099, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28192, "s": 28142, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sales vs. Profit (Quadrant) Analysis in Tableau | by Sree | Towards Data Science
To quickly identify the best performing categories in any sales dataset using quadrant analysis in Tableau. Details: A quadrant chart is nothing but a scatter plot that has four equal components. Each quadrant upholds data points that have similar characteristics. Here is a step-by-step approach on how to do a quadrant analysis plot in Tableau using the Superstore sales dataset so as to identify the best performing categories in terms of sales and profit: Step 1: Open a new Tableau file and import the ‘superstore’ public dataset into the workbook. In case if you haven’t worked with Tableau before, please download the ‘Tableau Public’ from the following URL: https://public.tableau.com/en-us/s/download Step 2: Our objective is to evaluate the performance of various sub-categories based on sales and profit metrics. So, import ‘Orders’ table into the workspace; drag and drop aggregated ‘Sales’ and ‘Profit’ metrics into the rows & columns. Step 3: Bring in sub-categories to life by dragging and dropping the ‘sub-categories’ field to the ‘Label’ and the analytics pane. Step 4: Create a calculated field for the reference lines: Reference Line for Profit = WINDOW_AVG(SUM([Profit]))Reference Line for Sales = WINDOW_AVG(SUM([Sales])) Drag both reference line calculations to ‘Detail’ and the analytics pane. Edit both reference line calculations, one for sales and the other for profit. Step 5: Create a calculated field for ‘Quadrant (Colour Indicator)’: Quadrant (Colour Indicator)=IF [Reference Line for Profit]>= WINDOW_AVG(SUM([Profit]))AND [Reference Line for Sales]>= WINDOW_AVG(SUM([Sales]))THEN 'UPPER RIGHT'ELSEIF[Reference Line for Profit]< WINDOW_AVG(SUM([Profit]))AND [Reference Line for Sales]>= WINDOW_AVG(SUM([Sales]))THEN 'LOWER RIGHT'ELSEIF[Reference Line for Profit]> WINDOW_AVG(SUM([Profit]))AND [Reference Line for Sales]< WINDOW_AVG(SUM([Sales]))THEN 'UPPER LEFT'ELSE 'LOWER LEFT'END Drag ‘Quadrant (Colour Indicator’) to colour and edit the table calculation; select ‘sub-category’ as specific dimensions. Step 6: Further, create a calculated field for the rank and drag this to tooltip: Sales Rank = RANK(SUM([Sales]))Profit Rank = RANK(SUM([Profit]))Count of Sub-Category = WINDOW_COUNT(COUNTD([Sub-Category])) For each one of these calculated fields: Edit table calculation & select ‘sub-category’ as specific dimensions. Step 7: Give a title, format axes and add reference lines. Step 8: Fix the size of the BI widget and set up the tooltip. Tooltip: <Sub-Category>Sales:<SUM(Sales)>Sales Rank:<AGG(Sales Rank)>/<AGG(Count of Sub-Category)>Profit:<SUM(Profit)>Profit Rank:<AGG(Profit Rank)>/<AGG(Count of Sub-Category)> Step 9: Generate Insights: (1) We can clearly see from the quadrant plots that phones, storage and binders get sold the most by yielding maximum sales and profit to the superstore. So, let the sales team know how important those products are for our annual revenue. (2) On the other hand, we can see a large volume of tables and machines getting sold but their profit seems to be surprisingly lower than the peers. Are we underselling? Should we increase the price of the products? (3) Not many Appliances are getting sold from the Superstore whilst their profit margin seems to be really high. Hence, let the sales team know that it would be good if the team can come up with more innovative measures to drive up the sales of those appliances. (4) Lastly, revisit our sales and marketing strategy to ensure that an adequate number of furnishings, bookcases and art get sold with a revised markup price. Conclusion: So, in this article, we briefly looked into the fundamentals of interactive quadrant analysis in Tableau and to reap insights from similar & dissimilar data points. From here, we can proceed with the exploratory data analysis either in R or Python to identify other significant components in the dataset that actually drive sales. GitHub Repository I have learned (and continue to learn) from many folks in Github. Hence sharing my Tableau file in a public GitHub Repository in case if it benefits any seekers online. Also, feel free to reach out to me if you need any help in understanding the fundamentals of Data visualization in Tableau. Happy to share what I know:) Hope this helps! About the Author:
[ { "code": null, "e": 279, "s": 171, "text": "To quickly identify the best performing categories in any sales dataset using quadrant analysis in Tableau." }, { "code": null, "e": 631, "s": 279, "text": "Details: A quadrant chart is nothing but a scatter plot that has four equal components. Each quadrant upholds data points that have similar characteristics. Here is a step-by-step approach on how to do a quadrant analysis plot in Tableau using the Superstore sales dataset so as to identify the best performing categories in terms of sales and profit:" }, { "code": null, "e": 881, "s": 631, "text": "Step 1: Open a new Tableau file and import the ‘superstore’ public dataset into the workbook. In case if you haven’t worked with Tableau before, please download the ‘Tableau Public’ from the following URL: https://public.tableau.com/en-us/s/download" }, { "code": null, "e": 1120, "s": 881, "text": "Step 2: Our objective is to evaluate the performance of various sub-categories based on sales and profit metrics. So, import ‘Orders’ table into the workspace; drag and drop aggregated ‘Sales’ and ‘Profit’ metrics into the rows & columns." }, { "code": null, "e": 1251, "s": 1120, "text": "Step 3: Bring in sub-categories to life by dragging and dropping the ‘sub-categories’ field to the ‘Label’ and the analytics pane." }, { "code": null, "e": 1310, "s": 1251, "text": "Step 4: Create a calculated field for the reference lines:" }, { "code": null, "e": 1415, "s": 1310, "text": "Reference Line for Profit = WINDOW_AVG(SUM([Profit]))Reference Line for Sales = WINDOW_AVG(SUM([Sales]))" }, { "code": null, "e": 1568, "s": 1415, "text": "Drag both reference line calculations to ‘Detail’ and the analytics pane. Edit both reference line calculations, one for sales and the other for profit." }, { "code": null, "e": 1637, "s": 1568, "text": "Step 5: Create a calculated field for ‘Quadrant (Colour Indicator)’:" }, { "code": null, "e": 2087, "s": 1637, "text": "Quadrant (Colour Indicator)=IF [Reference Line for Profit]>= WINDOW_AVG(SUM([Profit]))AND [Reference Line for Sales]>= WINDOW_AVG(SUM([Sales]))THEN 'UPPER RIGHT'ELSEIF[Reference Line for Profit]< WINDOW_AVG(SUM([Profit]))AND [Reference Line for Sales]>= WINDOW_AVG(SUM([Sales]))THEN 'LOWER RIGHT'ELSEIF[Reference Line for Profit]> WINDOW_AVG(SUM([Profit]))AND [Reference Line for Sales]< WINDOW_AVG(SUM([Sales]))THEN 'UPPER LEFT'ELSE 'LOWER LEFT'END" }, { "code": null, "e": 2210, "s": 2087, "text": "Drag ‘Quadrant (Colour Indicator’) to colour and edit the table calculation; select ‘sub-category’ as specific dimensions." }, { "code": null, "e": 2292, "s": 2210, "text": "Step 6: Further, create a calculated field for the rank and drag this to tooltip:" }, { "code": null, "e": 2417, "s": 2292, "text": "Sales Rank = RANK(SUM([Sales]))Profit Rank = RANK(SUM([Profit]))Count of Sub-Category = WINDOW_COUNT(COUNTD([Sub-Category]))" }, { "code": null, "e": 2529, "s": 2417, "text": "For each one of these calculated fields: Edit table calculation & select ‘sub-category’ as specific dimensions." }, { "code": null, "e": 2588, "s": 2529, "text": "Step 7: Give a title, format axes and add reference lines." }, { "code": null, "e": 2650, "s": 2588, "text": "Step 8: Fix the size of the BI widget and set up the tooltip." }, { "code": null, "e": 2659, "s": 2650, "text": "Tooltip:" }, { "code": null, "e": 2828, "s": 2659, "text": "<Sub-Category>Sales:<SUM(Sales)>Sales Rank:<AGG(Sales Rank)>/<AGG(Count of Sub-Category)>Profit:<SUM(Profit)>Profit Rank:<AGG(Profit Rank)>/<AGG(Count of Sub-Category)>" }, { "code": null, "e": 2855, "s": 2828, "text": "Step 9: Generate Insights:" }, { "code": null, "e": 3094, "s": 2855, "text": "(1) We can clearly see from the quadrant plots that phones, storage and binders get sold the most by yielding maximum sales and profit to the superstore. So, let the sales team know how important those products are for our annual revenue." }, { "code": null, "e": 3310, "s": 3094, "text": "(2) On the other hand, we can see a large volume of tables and machines getting sold but their profit seems to be surprisingly lower than the peers. Are we underselling? Should we increase the price of the products?" }, { "code": null, "e": 3573, "s": 3310, "text": "(3) Not many Appliances are getting sold from the Superstore whilst their profit margin seems to be really high. Hence, let the sales team know that it would be good if the team can come up with more innovative measures to drive up the sales of those appliances." }, { "code": null, "e": 3732, "s": 3573, "text": "(4) Lastly, revisit our sales and marketing strategy to ensure that an adequate number of furnishings, bookcases and art get sold with a revised markup price." }, { "code": null, "e": 3744, "s": 3732, "text": "Conclusion:" }, { "code": null, "e": 4075, "s": 3744, "text": "So, in this article, we briefly looked into the fundamentals of interactive quadrant analysis in Tableau and to reap insights from similar & dissimilar data points. From here, we can proceed with the exploratory data analysis either in R or Python to identify other significant components in the dataset that actually drive sales." }, { "code": null, "e": 4093, "s": 4075, "text": "GitHub Repository" }, { "code": null, "e": 4432, "s": 4093, "text": "I have learned (and continue to learn) from many folks in Github. Hence sharing my Tableau file in a public GitHub Repository in case if it benefits any seekers online. Also, feel free to reach out to me if you need any help in understanding the fundamentals of Data visualization in Tableau. Happy to share what I know:) Hope this helps!" } ]
OpenShift - CLI Operations
OpenShift CLI is capable of performing all basic and advance configuration, management, addition, and deployment of applications. We can perform different kinds of operations using OC commands. This client helps you develop, build, deploy, and run your applications on any OpenShift or Kubernetes compatible platform. It also includes the administrative commands for managing a cluster under the 'adm' subcommand. Following table lists the basic OC commands. Types An introduction to concepts and type Login Log in to a server new-project Request a new project new-app Create a new application Status Show an overview of the current project Project Switch to another project Projects Display existing projects Explain Documentation of resources Cluster Start and stop OpenShift cluster Log in to your server and save the login for subsequent use. First-time users of the client should run this command to connect to a server, establish an authenticated session, and save a connection to the configuration file. The default configuration will be saved to your home directory under ".kube/config". The information required to login -- like username and password, a session token, or the server details can be provided through flags. If not provided, the command will prompt for user input as needed. Usage oc login [URL] [options] Example # Log in interactively oc login # Log in to the given server with the given certificate authority file oc login localhost:8443 --certificate-authority = /path/to/cert.crt # Log in to the given server with the given credentials (will not prompt interactively) oc login localhost:8443 --username = myuser --password=mypass Options − -p, --password = " − Password, will prompt if not provided -u, --username = " − Username, will prompt if not provided --certificate-authority = " − Path to a cert. file for the certificate authority --insecure-skip-tls-verify = false − If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure --token = " − Bearer token for authentication to the API server To get the complete details regarding any command, use the oc <Command Name> --help command. Following table lists the build and deploy commands. Rollout Manage a Kubernetes deployment or OpenShift deploy Deploy View, start, cancel, or retry a deployment Rollback Revert part of an application back to the previous state new-build Create a new build configuration start-build Start a new build cancel-build Cancel running, pending, or new builds import-image Imports images from a Docker registry Tag Tag the existing images into image streams Following table lists the application management commands. Get Display one or many resources Describe Show details of a specific resource or a group of resources Edit Edit a resource on the server Set Commands that help set specific features on objects Label Update the labels on a resource Annotate Update the annotations on a resource Expose Expose a replicated application as a service or route Delete Delete one or more resources Scale Change the number of pods in a deployment Autoscale Autoscale a deployment config, deployment, replication, Controller or replica set Secrets Manage secrets Serviceaccounts Manage service accounts in your project Following table lists the troubleshooting and debugging commands. logs Print the logs for a resource Rsh Start a shell session in a pod Rsync Copy files between the local filesystem and a pod port-forward Forward one or more local ports to a pod Debug Launch a new instance of a pod for debugging Exec Execute a command in a container Procy Run a proxy to the Kubernetes API server Attach Attach to a running container Run Run a particular image on the cluster Cp Copy files and directories to and from containers Following table lists the advanced commands. adm Tools for managing a cluster create Create a resource by filename or stdin replace Replace a resource by filename or stdin apply Apply a configuration to a resource by filename or stdin patch Update field(s) of a resource using strategic merge patch process Process a template into list of resources export Export resources so they can be used elsewhere extract Extract secrets or config maps to disk idle Idle scalable resources observe Observe changes to the resources and react to them (experimental) policy Manage authorization policy auth Inspect authorization convert Convert config files between different API versions import Commands that import applications Following table lists the setting commands. Logout End the current server session Config Change the configuration files for the client Whoami Return information about the current session Completion Output shell completion code for the specified shell (bash or zsh) 70 Lectures 4 hours Cloud Passion 19 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2078, "s": 1948, "text": "OpenShift CLI is capable of performing all basic and advance configuration, management, addition, and deployment of applications." }, { "code": null, "e": 2362, "s": 2078, "text": "We can perform different kinds of operations using OC commands. This client helps you develop, build, deploy, and run your applications on any OpenShift or Kubernetes compatible platform. It also includes the administrative commands for managing a cluster under the 'adm' subcommand." }, { "code": null, "e": 2407, "s": 2362, "text": "Following table lists the basic OC commands." }, { "code": null, "e": 2413, "s": 2407, "text": "Types" }, { "code": null, "e": 2450, "s": 2413, "text": "An introduction to concepts and type" }, { "code": null, "e": 2456, "s": 2450, "text": "Login" }, { "code": null, "e": 2475, "s": 2456, "text": "Log in to a server" }, { "code": null, "e": 2487, "s": 2475, "text": "new-project" }, { "code": null, "e": 2509, "s": 2487, "text": "Request a new project" }, { "code": null, "e": 2517, "s": 2509, "text": "new-app" }, { "code": null, "e": 2542, "s": 2517, "text": "Create a new application" }, { "code": null, "e": 2549, "s": 2542, "text": "Status" }, { "code": null, "e": 2589, "s": 2549, "text": "Show an overview of the current project" }, { "code": null, "e": 2597, "s": 2589, "text": "Project" }, { "code": null, "e": 2623, "s": 2597, "text": "Switch to another project" }, { "code": null, "e": 2632, "s": 2623, "text": "Projects" }, { "code": null, "e": 2658, "s": 2632, "text": "Display existing projects" }, { "code": null, "e": 2666, "s": 2658, "text": "Explain" }, { "code": null, "e": 2693, "s": 2666, "text": "Documentation of resources" }, { "code": null, "e": 2701, "s": 2693, "text": "Cluster" }, { "code": null, "e": 2734, "s": 2701, "text": "Start and stop OpenShift cluster" }, { "code": null, "e": 3044, "s": 2734, "text": "Log in to your server and save the login for subsequent use. First-time users of the client should run this command to connect to a server, establish an authenticated session, and save a connection to the configuration file. The default configuration will be saved to your home directory under \".kube/config\"." }, { "code": null, "e": 3246, "s": 3044, "text": "The information required to login -- like username and password, a session token, or the server details can be provided through flags. If not provided, the command will prompt for user input as needed." }, { "code": null, "e": 3252, "s": 3246, "text": "Usage" }, { "code": null, "e": 3278, "s": 3252, "text": "oc login [URL] [options]\n" }, { "code": null, "e": 3286, "s": 3278, "text": "Example" }, { "code": null, "e": 3610, "s": 3286, "text": "# Log in interactively\noc login\n\n# Log in to the given server with the given certificate authority file\noc login localhost:8443 --certificate-authority = /path/to/cert.crt\n\n# Log in to the given server with the given credentials (will not prompt interactively)\noc login localhost:8443 --username = myuser --password=mypass\n" }, { "code": null, "e": 3620, "s": 3610, "text": "Options −" }, { "code": null, "e": 3679, "s": 3620, "text": "-p, --password = \" − Password, will prompt if not provided" }, { "code": null, "e": 3738, "s": 3679, "text": "-u, --username = \" − Username, will prompt if not provided" }, { "code": null, "e": 3819, "s": 3738, "text": "--certificate-authority = \" − Path to a cert. file for the certificate authority" }, { "code": null, "e": 3971, "s": 3819, "text": "--insecure-skip-tls-verify = false − If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure" }, { "code": null, "e": 4035, "s": 3971, "text": "--token = \" − Bearer token for authentication to the API server" }, { "code": null, "e": 4128, "s": 4035, "text": "To get the complete details regarding any command, use the oc <Command Name> --help command." }, { "code": null, "e": 4181, "s": 4128, "text": "Following table lists the build and deploy commands." }, { "code": null, "e": 4189, "s": 4181, "text": "Rollout" }, { "code": null, "e": 4240, "s": 4189, "text": "Manage a Kubernetes deployment or OpenShift deploy" }, { "code": null, "e": 4247, "s": 4240, "text": "Deploy" }, { "code": null, "e": 4290, "s": 4247, "text": "View, start, cancel, or retry a deployment" }, { "code": null, "e": 4299, "s": 4290, "text": "Rollback" }, { "code": null, "e": 4356, "s": 4299, "text": "Revert part of an application back to the previous state" }, { "code": null, "e": 4366, "s": 4356, "text": "new-build" }, { "code": null, "e": 4399, "s": 4366, "text": "Create a new build configuration" }, { "code": null, "e": 4411, "s": 4399, "text": "start-build" }, { "code": null, "e": 4429, "s": 4411, "text": "Start a new build" }, { "code": null, "e": 4442, "s": 4429, "text": "cancel-build" }, { "code": null, "e": 4481, "s": 4442, "text": "Cancel running, pending, or new builds" }, { "code": null, "e": 4494, "s": 4481, "text": "import-image" }, { "code": null, "e": 4532, "s": 4494, "text": "Imports images from a Docker registry" }, { "code": null, "e": 4536, "s": 4532, "text": "Tag" }, { "code": null, "e": 4579, "s": 4536, "text": "Tag the existing images into image streams" }, { "code": null, "e": 4638, "s": 4579, "text": "Following table lists the application management commands." }, { "code": null, "e": 4642, "s": 4638, "text": "Get" }, { "code": null, "e": 4672, "s": 4642, "text": "Display one or many resources" }, { "code": null, "e": 4681, "s": 4672, "text": "Describe" }, { "code": null, "e": 4741, "s": 4681, "text": "Show details of a specific resource or a group of resources" }, { "code": null, "e": 4746, "s": 4741, "text": "Edit" }, { "code": null, "e": 4776, "s": 4746, "text": "Edit a resource on the server" }, { "code": null, "e": 4780, "s": 4776, "text": "Set" }, { "code": null, "e": 4832, "s": 4780, "text": "Commands that help set specific features on objects" }, { "code": null, "e": 4838, "s": 4832, "text": "Label" }, { "code": null, "e": 4870, "s": 4838, "text": "Update the labels on a resource" }, { "code": null, "e": 4879, "s": 4870, "text": "Annotate" }, { "code": null, "e": 4916, "s": 4879, "text": "Update the annotations on a resource" }, { "code": null, "e": 4923, "s": 4916, "text": "Expose" }, { "code": null, "e": 4977, "s": 4923, "text": "Expose a replicated application as a service or route" }, { "code": null, "e": 4984, "s": 4977, "text": "Delete" }, { "code": null, "e": 5013, "s": 4984, "text": "Delete one or more resources" }, { "code": null, "e": 5019, "s": 5013, "text": "Scale" }, { "code": null, "e": 5061, "s": 5019, "text": "Change the number of pods in a deployment" }, { "code": null, "e": 5071, "s": 5061, "text": "Autoscale" }, { "code": null, "e": 5153, "s": 5071, "text": "Autoscale a deployment config, deployment, replication, Controller or replica set" }, { "code": null, "e": 5161, "s": 5153, "text": "Secrets" }, { "code": null, "e": 5176, "s": 5161, "text": "Manage secrets" }, { "code": null, "e": 5192, "s": 5176, "text": "Serviceaccounts" }, { "code": null, "e": 5232, "s": 5192, "text": "Manage service accounts in your project" }, { "code": null, "e": 5298, "s": 5232, "text": "Following table lists the troubleshooting and debugging commands." }, { "code": null, "e": 5303, "s": 5298, "text": "logs" }, { "code": null, "e": 5333, "s": 5303, "text": "Print the logs for a resource" }, { "code": null, "e": 5337, "s": 5333, "text": "Rsh" }, { "code": null, "e": 5368, "s": 5337, "text": "Start a shell session in a pod" }, { "code": null, "e": 5374, "s": 5368, "text": "Rsync" }, { "code": null, "e": 5424, "s": 5374, "text": "Copy files between the local filesystem and a pod" }, { "code": null, "e": 5437, "s": 5424, "text": "port-forward" }, { "code": null, "e": 5478, "s": 5437, "text": "Forward one or more local ports to a pod" }, { "code": null, "e": 5484, "s": 5478, "text": "Debug" }, { "code": null, "e": 5529, "s": 5484, "text": "Launch a new instance of a pod for debugging" }, { "code": null, "e": 5534, "s": 5529, "text": "Exec" }, { "code": null, "e": 5567, "s": 5534, "text": "Execute a command in a container" }, { "code": null, "e": 5573, "s": 5567, "text": "Procy" }, { "code": null, "e": 5614, "s": 5573, "text": "Run a proxy to the Kubernetes API server" }, { "code": null, "e": 5621, "s": 5614, "text": "Attach" }, { "code": null, "e": 5651, "s": 5621, "text": "Attach to a running container" }, { "code": null, "e": 5655, "s": 5651, "text": "Run" }, { "code": null, "e": 5693, "s": 5655, "text": "Run a particular image on the cluster" }, { "code": null, "e": 5696, "s": 5693, "text": "Cp" }, { "code": null, "e": 5746, "s": 5696, "text": "Copy files and directories to and from containers" }, { "code": null, "e": 5791, "s": 5746, "text": "Following table lists the advanced commands." }, { "code": null, "e": 5795, "s": 5791, "text": "adm" }, { "code": null, "e": 5824, "s": 5795, "text": "Tools for managing a cluster" }, { "code": null, "e": 5831, "s": 5824, "text": "create" }, { "code": null, "e": 5870, "s": 5831, "text": "Create a resource by filename or stdin" }, { "code": null, "e": 5878, "s": 5870, "text": "replace" }, { "code": null, "e": 5918, "s": 5878, "text": "Replace a resource by filename or stdin" }, { "code": null, "e": 5924, "s": 5918, "text": "apply" }, { "code": null, "e": 5981, "s": 5924, "text": "Apply a configuration to a resource by filename or stdin" }, { "code": null, "e": 5987, "s": 5981, "text": "patch" }, { "code": null, "e": 6045, "s": 5987, "text": "Update field(s) of a resource using strategic merge patch" }, { "code": null, "e": 6053, "s": 6045, "text": "process" }, { "code": null, "e": 6095, "s": 6053, "text": "Process a template into list of resources" }, { "code": null, "e": 6102, "s": 6095, "text": "export" }, { "code": null, "e": 6149, "s": 6102, "text": "Export resources so they can be used elsewhere" }, { "code": null, "e": 6157, "s": 6149, "text": "extract" }, { "code": null, "e": 6196, "s": 6157, "text": "Extract secrets or config maps to disk" }, { "code": null, "e": 6201, "s": 6196, "text": "idle" }, { "code": null, "e": 6225, "s": 6201, "text": "Idle scalable resources" }, { "code": null, "e": 6233, "s": 6225, "text": "observe" }, { "code": null, "e": 6299, "s": 6233, "text": "Observe changes to the resources and react to them (experimental)" }, { "code": null, "e": 6306, "s": 6299, "text": "policy" }, { "code": null, "e": 6334, "s": 6306, "text": "Manage authorization policy" }, { "code": null, "e": 6339, "s": 6334, "text": "auth" }, { "code": null, "e": 6361, "s": 6339, "text": "Inspect authorization" }, { "code": null, "e": 6369, "s": 6361, "text": "convert" }, { "code": null, "e": 6421, "s": 6369, "text": "Convert config files between different API versions" }, { "code": null, "e": 6428, "s": 6421, "text": "import" }, { "code": null, "e": 6462, "s": 6428, "text": "Commands that import applications" }, { "code": null, "e": 6506, "s": 6462, "text": "Following table lists the setting commands." }, { "code": null, "e": 6513, "s": 6506, "text": "Logout" }, { "code": null, "e": 6544, "s": 6513, "text": "End the current server session" }, { "code": null, "e": 6551, "s": 6544, "text": "Config" }, { "code": null, "e": 6597, "s": 6551, "text": "Change the configuration files for the client" }, { "code": null, "e": 6604, "s": 6597, "text": "Whoami" }, { "code": null, "e": 6649, "s": 6604, "text": "Return information about the current session" }, { "code": null, "e": 6660, "s": 6649, "text": "Completion" }, { "code": null, "e": 6727, "s": 6660, "text": "Output shell completion code for the specified shell (bash or zsh)" }, { "code": null, "e": 6760, "s": 6727, "text": "\n 70 Lectures \n 4 hours \n" }, { "code": null, "e": 6775, "s": 6760, "text": " Cloud Passion" }, { "code": null, "e": 6808, "s": 6775, "text": "\n 19 Lectures \n 1 hours \n" }, { "code": null, "e": 6828, "s": 6808, "text": " Pranjal Srivastava" }, { "code": null, "e": 6863, "s": 6828, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6883, "s": 6863, "text": " Pranjal Srivastava" }, { "code": null, "e": 6890, "s": 6883, "text": " Print" }, { "code": null, "e": 6901, "s": 6890, "text": " Add Notes" } ]
jQuery - DOM Traversing
jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method. Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions. Consider a simple document with the following HTML content − <html> <head> <title>The JQuery Example</title> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 Above every list has its own index, and can be located directly by using eq(index) method as below example. Above every list has its own index, and can be located directly by using eq(index) method as below example. Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on. Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on. Following is a simple example which adds the color to second list item. <html> <head> <title>The JQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").eq(2).addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax. Following is a simple example which applies color to the lists associated with middle class − <html> <head> <title>The JQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").filter(".middle").addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li class = "top">list item 1</li> <li class = "top">list item 2</li> <li class = "middle">list item 3</li> <li class = "middle">list item 4</li> <li class = "bottom">list item 5</li> <li class = "bottom">list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 The find( selector ) method can be used to locate all the descendant elements of a particular type of elements. The selector can be written using any selector syntax. Following is an example which selects all the <span> elements available inside different <p> elements − <html> <head> <title>The JQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("p").find("span").addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <p>This is 1st paragraph and <span>THIS IS RED</span></p> <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p> </body> </html> This will produce following result − This is 1st paragraph and THIS IS RED This is 2nd paragraph and THIS IS ALSO RED Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements − Reduce the set of matched elements to a single element. Removes all elements from the set of matched elements that do not match the specified selector(s). Removes all elements from the set of matched elements that do not match the specified function. Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements). Removes elements matching the specified selector from the set of matched elements. Selects a subset of the matched elements. Following table lists down other useful methods which you can use to locate various elements in a DOM − Adds more elements, matched by the given selector, to the set of matched elements. Add the previous selection to the current selection. Get a set of elements containing all of the unique immediate children of each of the matched set of elements. Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe. Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state. Searches for descendant elements that match the specified selectors. Get a set of elements containing the unique next siblings of each of the given set of elements. Find all sibling elements after the current element. Returns a jQuery collection with the positioned parent of the first matched element. Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements. Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). Get a set of elements containing the unique previous siblings of each of the matched set of elements. Find all sibling elements in front of the current element. Get a set of elements containing all of the unique siblings of each of the matched set of elements. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2636, "s": 2322, "text": "jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method. Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions." }, { "code": null, "e": 2697, "s": 2636, "text": "Consider a simple document with the following HTML content −" }, { "code": null, "e": 3048, "s": 2697, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3085, "s": 3048, "text": "This will produce following result −" }, { "code": null, "e": 3097, "s": 3085, "text": "list item 1" }, { "code": null, "e": 3109, "s": 3097, "text": "list item 2" }, { "code": null, "e": 3121, "s": 3109, "text": "list item 3" }, { "code": null, "e": 3133, "s": 3121, "text": "list item 4" }, { "code": null, "e": 3145, "s": 3133, "text": "list item 5" }, { "code": null, "e": 3157, "s": 3145, "text": "list item 6" }, { "code": null, "e": 3265, "s": 3157, "text": "Above every list has its own index, and can be located directly by using eq(index) method as below example." }, { "code": null, "e": 3373, "s": 3265, "text": "Above every list has its own index, and can be located directly by using eq(index) method as below example." }, { "code": null, "e": 3491, "s": 3373, "text": "Every child element starts its index from zero, thus, list item 2 would be accessed by using $(\"li\").eq(1) and so on." }, { "code": null, "e": 3609, "s": 3491, "text": "Every child element starts its index from zero, thus, list item 2 would be accessed by using $(\"li\").eq(1) and so on." }, { "code": null, "e": 3681, "s": 3609, "text": "Following is a simple example which adds the color to second list item." }, { "code": null, "e": 4421, "s": 3681, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").eq(2).addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4458, "s": 4421, "text": "This will produce following result −" }, { "code": null, "e": 4470, "s": 4458, "text": "list item 1" }, { "code": null, "e": 4482, "s": 4470, "text": "list item 2" }, { "code": null, "e": 4494, "s": 4482, "text": "list item 3" }, { "code": null, "e": 4506, "s": 4494, "text": "list item 4" }, { "code": null, "e": 4518, "s": 4506, "text": "list item 5" }, { "code": null, "e": 4530, "s": 4518, "text": "list item 6" }, { "code": null, "e": 4732, "s": 4530, "text": "The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax." }, { "code": null, "e": 4827, "s": 4732, "text": "Following is a simple example which applies color to the lists associated with middle class −" }, { "code": null, "e": 5675, "s": 4827, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").filter(\".middle\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li class = \"top\">list item 1</li>\n <li class = \"top\">list item 2</li>\n <li class = \"middle\">list item 3</li>\n <li class = \"middle\">list item 4</li>\n <li class = \"bottom\">list item 5</li>\n <li class = \"bottom\">list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5712, "s": 5675, "text": "This will produce following result −" }, { "code": null, "e": 5724, "s": 5712, "text": "list item 1" }, { "code": null, "e": 5736, "s": 5724, "text": "list item 2" }, { "code": null, "e": 5748, "s": 5736, "text": "list item 3" }, { "code": null, "e": 5760, "s": 5748, "text": "list item 4" }, { "code": null, "e": 5772, "s": 5760, "text": "list item 5" }, { "code": null, "e": 5784, "s": 5772, "text": "list item 6" }, { "code": null, "e": 5951, "s": 5784, "text": "The find( selector ) method can be used to locate all the descendant elements of a particular type of elements. The selector can be written using any selector syntax." }, { "code": null, "e": 6055, "s": 5951, "text": "Following is an example which selects all the <span> elements available inside different <p> elements −" }, { "code": null, "e": 6682, "s": 6055, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"p\").find(\"span\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <p>This is 1st paragraph and <span>THIS IS RED</span></p>\n <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>\n </body>\n</html>" }, { "code": null, "e": 6719, "s": 6682, "text": "This will produce following result −" }, { "code": null, "e": 6757, "s": 6719, "text": "This is 1st paragraph and THIS IS RED" }, { "code": null, "e": 6800, "s": 6757, "text": "This is 2nd paragraph and THIS IS ALSO RED" }, { "code": null, "e": 6921, "s": 6800, "text": "Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements −" }, { "code": null, "e": 6977, "s": 6921, "text": "Reduce the set of matched elements to a single element." }, { "code": null, "e": 7076, "s": 6977, "text": "Removes all elements from the set of matched elements that do not match the specified selector(s)." }, { "code": null, "e": 7172, "s": 7076, "text": "Removes all elements from the set of matched elements that do not match the specified function." }, { "code": null, "e": 7307, "s": 7172, "text": "Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector." }, { "code": null, "e": 7443, "s": 7307, "text": "Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements)." }, { "code": null, "e": 7526, "s": 7443, "text": "Removes elements matching the specified selector from the set of matched elements." }, { "code": null, "e": 7568, "s": 7526, "text": "Selects a subset of the matched elements." }, { "code": null, "e": 7672, "s": 7568, "text": "Following table lists down other useful methods which you can use to locate various elements in a DOM −" }, { "code": null, "e": 7755, "s": 7672, "text": "Adds more elements, matched by the given selector, to the set of matched elements." }, { "code": null, "e": 7808, "s": 7755, "text": "Add the previous selection to the current selection." }, { "code": null, "e": 7918, "s": 7808, "text": "Get a set of elements containing all of the unique immediate children of each of the matched set of elements." }, { "code": null, "e": 8046, "s": 7918, "text": "Get a set of elements containing the closest parent element that matches the specified selector, the starting element included." }, { "code": null, "e": 8177, "s": 8046, "text": "Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe." }, { "code": null, "e": 8285, "s": 8177, "text": "Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state." }, { "code": null, "e": 8354, "s": 8285, "text": "Searches for descendant elements that match the specified selectors." }, { "code": null, "e": 8450, "s": 8354, "text": "Get a set of elements containing the unique next siblings of each of the given set of elements." }, { "code": null, "e": 8503, "s": 8450, "text": "Find all sibling elements after the current element." }, { "code": null, "e": 8588, "s": 8503, "text": "Returns a jQuery collection with the positioned parent of the first matched element." }, { "code": null, "e": 8718, "s": 8588, "text": "Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements." }, { "code": null, "e": 8834, "s": 8718, "text": "Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element)." }, { "code": null, "e": 8936, "s": 8834, "text": "Get a set of elements containing the unique previous siblings of each of the matched set of elements." }, { "code": null, "e": 8995, "s": 8936, "text": "Find all sibling elements in front of the current element." }, { "code": null, "e": 9095, "s": 8995, "text": "Get a set of elements containing all of the unique siblings of each of the matched set of elements." }, { "code": null, "e": 9128, "s": 9095, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 9142, "s": 9128, "text": " Mahesh Kumar" }, { "code": null, "e": 9177, "s": 9142, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9191, "s": 9177, "text": " Pratik Singh" }, { "code": null, "e": 9226, "s": 9191, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9243, "s": 9226, "text": " Frahaan Hussain" }, { "code": null, "e": 9276, "s": 9243, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 9304, "s": 9276, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9337, "s": 9304, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 9358, "s": 9337, "text": " Sandip Bhattacharya" }, { "code": null, "e": 9390, "s": 9358, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 9407, "s": 9390, "text": " Laurence Svekis" }, { "code": null, "e": 9414, "s": 9407, "text": " Print" }, { "code": null, "e": 9425, "s": 9414, "text": " Add Notes" } ]
Print array of strings in sorted order without copying one string into another - GeeksforGeeks
26 Apr, 2021 Given an array of n strings. The task is to print the strings in sorted order. The approach should be such that no string should be copied to another string during the sorting process. Examples: Input : {"geeks", "for", "geeks", "quiz") Output : for geeks geeks quiz Input : {"ball", "pen", "apple", "kite"} Output : apple ball kite pen Approach: It has the following steps: Maintain another array indexed_arr which stores/maintain the index of each string.We can apply any sorting technique to this indexed_arr. Maintain another array indexed_arr which stores/maintain the index of each string. We can apply any sorting technique to this indexed_arr. An Illustration: --> str[] = {"world", "hello"} --> corresponding index array will be indexed_arr = {0, 1} --> Now, how the strings are compared and accordingly values in indexed_arr are changed. --> Comparison process: if (str[index[0]].compare(str[index[1]] > 0 temp = index[0] index[0] = index[1] index[1] = temp // after sorting values of // indexed_arr = {1, 0} --> for i=0 to 1 print str[index[i]] This is how the strings are compared and their corresponding indexes in the indexed_arr are being manipulated/swapped so that after the sorting process is completed, the order of indexes in the indexed_arr gives us the sorted order of the strings. C++ Java Python 3 C# Javascript // C++ implementation to print array of strings in sorted// order without copying one string into another#include <bits/stdc++.h> using namespace std; // function to print strings in sorted ordervoid printInSortedOrder(string arr[], int n){ int index[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i=0; i<n; i++) index[i] = i; // selection sort technique is applied for (i=0; i<n-1; i++) { min = i; for (j=i+1; j<n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].compare(arr[index[j]]) > 0) min = j; } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i=0; i<n; i++) cout << arr[index[i]] << " ";} // Driver program to test aboveint main(){ string arr[] = {"geeks", "quiz", "geeks", "for"}; int n = 4; printInSortedOrder(arr, n); return 0;} //Java implementation to print array of strings in sorted// order without copying one string into another class GFG { // function to print strings in sorted order static void printInSortedOrder(String arr[], int n) { int index[] = new int[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i = 0; i < n; i++) { index[i] = i; } // selection sort technique is applied for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].compareTo(arr[index[j]]) > 0) { min = j; } } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i = 0; i < n; i++) { System.out.print(arr[index[i]] + " "); } } // Driver program to test above static public void main(String[] args) { String arr[] = {"geeks", "quiz", "geeks", "for"}; int n = 4; printInSortedOrder(arr, n); }} // This code is contributed by 29AjayKumar # Python 3 implementation to print array# of strings in sorted order without# copying one string into another # function to print strings in sorted orderdef printInSortedOrder(arr, n): index = [0] * n # Initially the index of the strings # are assigned to the 'index[]' for i in range(n): index[i] = i # selection sort technique is applied for i in range(n - 1): min = i for j in range(i + 1, n): # with the help of 'index[]' # strings are being compared if (arr[index[min]] > arr[index[j]]): min = j # index of the smallest string is placed # at the ith index of 'index[]' if (min != i): index[min], index[i] = index[i], index[min] # printing strings in sorted order for i in range(n): print(arr[index[i]], end = " ") # Driver Codeif __name__ == "__main__": arr = ["geeks", "quiz", "geeks", "for"] n = 4 printInSortedOrder(arr, n) # This code is contributed by ita_c //C# implementation to print an array of strings in sorted// order without copying one string into another using System;public class GFG { // function to print strings in sorted order static void printInSortedOrder(String []arr, int n) { int []index = new int[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i = 0; i < n; i++) { index[i] = i; } // selection sort technique is applied for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].CompareTo(arr[index[j]]) > 0) { min = j; } } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i = 0; i < n; i++) { Console.Write(arr[index[i]] + " "); } } // Driver program to test above static public void Main() { String []arr = {"geeks", "quiz", "geeks", "for"}; int n = 4; printInSortedOrder(arr, n); }} // This code is contributed by 29AjayKumar <script>//Javascript implementation to print array of strings in sorted// order without copying one string into another // function to print strings in sorted order function printInSortedOrder(arr,n) { let index = new Array(n); let i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i = 0; i < n; i++) { index[i] = i; } // selection sort technique is applied for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]]>(arr[index[j]]) ) { min = j; } } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { let temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i = 0; i < n; i++) { document.write(arr[index[i]] + " "); } } // Driver program to test above let arr=["geeks", "quiz", "geeks", "for"]; let n = 4; printInSortedOrder(arr, n); // This code is contributed by avanitrachhadiya2155</script> Output: for geeks geeks quiz Time Complexity: O(n2)The approach can have its usage when we have to minimize the number of disc writes as in the case of an array of structures. The structure values are compared, but their values are not being swapped, instead, their index is maintained in another array, which is manipulated to keep the indexes in an order which represents the sorted array of structures. 29AjayKumar ukasp Akanksha_Rai avanitrachhadiya2155 Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Chocolate Distribution Problem 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 Longest Common Subsequence | DP-4
[ { "code": null, "e": 26323, "s": 26295, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26508, "s": 26323, "text": "Given an array of n strings. The task is to print the strings in sorted order. The approach should be such that no string should be copied to another string during the sorting process." }, { "code": null, "e": 26518, "s": 26508, "text": "Examples:" }, { "code": null, "e": 26661, "s": 26518, "text": "Input : {\"geeks\", \"for\", \"geeks\", \"quiz\")\nOutput : for geeks geeks quiz\n\nInput : {\"ball\", \"pen\", \"apple\", \"kite\"}\nOutput : apple ball kite pen" }, { "code": null, "e": 26700, "s": 26661, "text": "Approach: It has the following steps: " }, { "code": null, "e": 26838, "s": 26700, "text": "Maintain another array indexed_arr which stores/maintain the index of each string.We can apply any sorting technique to this indexed_arr." }, { "code": null, "e": 26921, "s": 26838, "text": "Maintain another array indexed_arr which stores/maintain the index of each string." }, { "code": null, "e": 26977, "s": 26921, "text": "We can apply any sorting technique to this indexed_arr." }, { "code": null, "e": 26996, "s": 26977, "text": "An Illustration: " }, { "code": null, "e": 27679, "s": 26996, "text": "--> str[] = {\"world\", \"hello\"}\n--> corresponding index array will be\n indexed_arr = {0, 1}\n--> Now, how the strings are compared and \n accordingly values in indexed_arr are changed.\n--> Comparison process:\n if (str[index[0]].compare(str[index[1]] > 0\n temp = index[0]\n index[0] = index[1]\n index[1] = temp\n\n// after sorting values of\n// indexed_arr = {1, 0}\n--> for i=0 to 1\n print str[index[i]]\n\nThis is how the strings are compared and their \ncorresponding indexes in the indexed_arr\nare being manipulated/swapped so that after the sorting process\nis completed, the order of indexes in the indexed_arr\ngives us the sorted order of the strings." }, { "code": null, "e": 27683, "s": 27679, "text": "C++" }, { "code": null, "e": 27688, "s": 27683, "text": "Java" }, { "code": null, "e": 27697, "s": 27688, "text": "Python 3" }, { "code": null, "e": 27700, "s": 27697, "text": "C#" }, { "code": null, "e": 27711, "s": 27700, "text": "Javascript" }, { "code": "// C++ implementation to print array of strings in sorted// order without copying one string into another#include <bits/stdc++.h> using namespace std; // function to print strings in sorted ordervoid printInSortedOrder(string arr[], int n){ int index[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i=0; i<n; i++) index[i] = i; // selection sort technique is applied for (i=0; i<n-1; i++) { min = i; for (j=i+1; j<n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].compare(arr[index[j]]) > 0) min = j; } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i=0; i<n; i++) cout << arr[index[i]] << \" \";} // Driver program to test aboveint main(){ string arr[] = {\"geeks\", \"quiz\", \"geeks\", \"for\"}; int n = 4; printInSortedOrder(arr, n); return 0;}", "e": 28922, "s": 27711, "text": null }, { "code": "//Java implementation to print array of strings in sorted// order without copying one string into another class GFG { // function to print strings in sorted order static void printInSortedOrder(String arr[], int n) { int index[] = new int[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i = 0; i < n; i++) { index[i] = i; } // selection sort technique is applied for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].compareTo(arr[index[j]]) > 0) { min = j; } } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i = 0; i < n; i++) { System.out.print(arr[index[i]] + \" \"); } } // Driver program to test above static public void main(String[] args) { String arr[] = {\"geeks\", \"quiz\", \"geeks\", \"for\"}; int n = 4; printInSortedOrder(arr, n); }} // This code is contributed by 29AjayKumar", "e": 30352, "s": 28922, "text": null }, { "code": "# Python 3 implementation to print array# of strings in sorted order without# copying one string into another # function to print strings in sorted orderdef printInSortedOrder(arr, n): index = [0] * n # Initially the index of the strings # are assigned to the 'index[]' for i in range(n): index[i] = i # selection sort technique is applied for i in range(n - 1): min = i for j in range(i + 1, n): # with the help of 'index[]' # strings are being compared if (arr[index[min]] > arr[index[j]]): min = j # index of the smallest string is placed # at the ith index of 'index[]' if (min != i): index[min], index[i] = index[i], index[min] # printing strings in sorted order for i in range(n): print(arr[index[i]], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [\"geeks\", \"quiz\", \"geeks\", \"for\"] n = 4 printInSortedOrder(arr, n) # This code is contributed by ita_c", "e": 31403, "s": 30352, "text": null }, { "code": " //C# implementation to print an array of strings in sorted// order without copying one string into another using System;public class GFG { // function to print strings in sorted order static void printInSortedOrder(String []arr, int n) { int []index = new int[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i = 0; i < n; i++) { index[i] = i; } // selection sort technique is applied for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].CompareTo(arr[index[j]]) > 0) { min = j; } } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i = 0; i < n; i++) { Console.Write(arr[index[i]] + \" \"); } } // Driver program to test above static public void Main() { String []arr = {\"geeks\", \"quiz\", \"geeks\", \"for\"}; int n = 4; printInSortedOrder(arr, n); }} // This code is contributed by 29AjayKumar", "e": 32850, "s": 31403, "text": null }, { "code": "<script>//Javascript implementation to print array of strings in sorted// order without copying one string into another // function to print strings in sorted order function printInSortedOrder(arr,n) { let index = new Array(n); let i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i = 0; i < n; i++) { index[i] = i; } // selection sort technique is applied for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]]>(arr[index[j]]) ) { min = j; } } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { let temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i = 0; i < n; i++) { document.write(arr[index[i]] + \" \"); } } // Driver program to test above let arr=[\"geeks\", \"quiz\", \"geeks\", \"for\"]; let n = 4; printInSortedOrder(arr, n); // This code is contributed by avanitrachhadiya2155</script>", "e": 34227, "s": 32850, "text": null }, { "code": null, "e": 34237, "s": 34227, "text": "Output: " }, { "code": null, "e": 34258, "s": 34237, "text": "for geeks geeks quiz" }, { "code": null, "e": 34636, "s": 34258, "text": "Time Complexity: O(n2)The approach can have its usage when we have to minimize the number of disc writes as in the case of an array of structures. The structure values are compared, but their values are not being swapped, instead, their index is maintained in another array, which is manipulated to keep the indexes in an order which represents the sorted array of structures. " }, { "code": null, "e": 34648, "s": 34636, "text": "29AjayKumar" }, { "code": null, "e": 34654, "s": 34648, "text": "ukasp" }, { "code": null, "e": 34667, "s": 34654, "text": "Akanksha_Rai" }, { "code": null, "e": 34688, "s": 34667, "text": "avanitrachhadiya2155" }, { "code": null, "e": 34696, "s": 34688, "text": "Sorting" }, { "code": null, "e": 34704, "s": 34696, "text": "Strings" }, { "code": null, "e": 34712, "s": 34704, "text": "Strings" }, { "code": null, "e": 34720, "s": 34712, "text": "Sorting" }, { "code": null, "e": 34818, "s": 34720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34841, "s": 34818, "text": "std::sort() in C++ STL" }, { "code": null, "e": 34885, "s": 34841, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 34896, "s": 34885, "text": "Radix Sort" }, { "code": null, "e": 34920, "s": 34896, "text": "Merge two sorted arrays" }, { "code": null, "e": 34951, "s": 34920, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34997, "s": 34951, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35022, "s": 34997, "text": "Reverse a string in Java" }, { "code": null, "e": 35082, "s": 35022, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35097, "s": 35082, "text": "C++ Data Types" } ]
Python | Pandas Series.dt.date - GeeksforGeeks
20 Mar, 2019 Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.date attribute return a numpy array of python datetime.date objects. Syntax: Series.dt.date Parameter : None Returns : numpy array Example #1: Use Series.dt.date attribute to return the date property of the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr) Output : Now we will use Series.dt.date attribute to return the date property of the underlying data of the given Series object. # return the dateresult = sr.dt.date # print the resultprint(result) Output : As we can see in the output, the Series.dt.date attribute has successfully accessed and returned the date property of the underlying data in the given series object. Example #2 : Use Series.dt.date attribute to return the date property of the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.dt.date attribute to return the date property of the underlying data of the given Series object. # return the dateresult = sr.dt.date # print the resultprint(result) Output :As we can see in the output, the Series.dt.date attribute has successfully accessed and returned the date property of the underlying data in the given series object. Python pandas-series-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 26093, "s": 26065, "text": "\n20 Mar, 2019" }, { "code": null, "e": 26283, "s": 26093, "text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.date attribute return a numpy array of python datetime.date objects." }, { "code": null, "e": 26306, "s": 26283, "text": "Syntax: Series.dt.date" }, { "code": null, "e": 26323, "s": 26306, "text": "Parameter : None" }, { "code": null, "e": 26345, "s": 26323, "text": "Returns : numpy array" }, { "code": null, "e": 26465, "s": 26345, "text": "Example #1: Use Series.dt.date attribute to return the date property of the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)", "e": 26858, "s": 26465, "text": null }, { "code": null, "e": 26867, "s": 26858, "text": "Output :" }, { "code": null, "e": 26987, "s": 26867, "text": "Now we will use Series.dt.date attribute to return the date property of the underlying data of the given Series object." }, { "code": "# return the dateresult = sr.dt.date # print the resultprint(result)", "e": 27057, "s": 26987, "text": null }, { "code": null, "e": 27066, "s": 27057, "text": "Output :" }, { "code": null, "e": 27353, "s": 27066, "text": "As we can see in the output, the Series.dt.date attribute has successfully accessed and returned the date property of the underlying data in the given series object. Example #2 : Use Series.dt.date attribute to return the date property of the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 27650, "s": 27353, "text": null }, { "code": null, "e": 27659, "s": 27650, "text": "Output :" }, { "code": null, "e": 27779, "s": 27659, "text": "Now we will use Series.dt.date attribute to return the date property of the underlying data of the given Series object." }, { "code": "# return the dateresult = sr.dt.date # print the resultprint(result)", "e": 27849, "s": 27779, "text": null }, { "code": null, "e": 28023, "s": 27849, "text": "Output :As we can see in the output, the Series.dt.date attribute has successfully accessed and returned the date property of the underlying data in the given series object." }, { "code": null, "e": 28053, "s": 28023, "text": "Python pandas-series-datetime" }, { "code": null, "e": 28067, "s": 28053, "text": "Python-pandas" }, { "code": null, "e": 28074, "s": 28067, "text": "Python" }, { "code": null, "e": 28172, "s": 28074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28190, "s": 28172, "text": "Python Dictionary" }, { "code": null, "e": 28222, "s": 28190, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28244, "s": 28222, "text": "Enumerate() in Python" }, { "code": null, "e": 28286, "s": 28244, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28315, "s": 28286, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28359, "s": 28315, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28395, "s": 28359, "text": "Convert integer to string in Python" }, { "code": null, "e": 28432, "s": 28395, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28474, "s": 28432, "text": "Check if element exists in list in Python" } ]
jQuery | ajaxError() Method - GeeksforGeeks
01 Mar, 2019 The ajaxError() method in jQuery is used to specify function to be run when an AJAX request fails. Syntax: $(document).ajaxError( function(event, xhr, options, exc) ) Parameter:: This method accepts single parameter function which is mandatory. This function accepts four parameters which are listed below: event: This parameter holds the event object. xhr: It holds the XMLHttpRequest object. options: It contains the used options in AJAX request. exc: It holds the JavaScript exception. The demo.txt file stored on server and it will load after clicking the change content button.demo.txt This is GFG. Example 1: This example changes the content of <p> element, by taking the data from server. When the AJAX request fails due to an error, the page says AJAX request fails.. <!DOCTYPE html> <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to use ajaxError() method --> <script> $(document).ready(function() { $(document).ajaxError(function() { alert("AJAX request fails."); }); $("button").click(function() { $("#paragraph").load("demo.txt"); }); }); </script> </head> <body style="text-align:center;"> <div id="div_content"> <h1 style = "color: green;"> GeeksforGeeks </h1> <p id = "paragraph" style= "font-size: 20px;"> A computer science portal for geeks </p> </div> <button> Change Content </button> </body> </html> Output: Before click on the button: After click on the button: Example 2: This example changes the content of <h1> element, by taking the data from server. When the AJAX request fails due to an error, the page says AJAX request fails.. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to use ajaxError() method --> <script> $(document).ready(function() { $(document).ajaxError(function() { alert("AJAX request fails."); }); $("button").click(function() { $("#heading").load("demo.txt"); }); }); </script> </head> <body style="text-align:center;"> <div id="div_content"> <h1 id = "heading" style = "color: green;"> GeeksforGeeks </h1> <p style= "font-size: 20px;"> A computer science portal for geeks </p> </div> <button> Change Content </button> </body> </html> Output: Before click on the button: After click on the button: jQuery-AJAX Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ? 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": 41968, "s": 41940, "text": "\n01 Mar, 2019" }, { "code": null, "e": 42067, "s": 41968, "text": "The ajaxError() method in jQuery is used to specify function to be run when an AJAX request fails." }, { "code": null, "e": 42075, "s": 42067, "text": "Syntax:" }, { "code": null, "e": 42135, "s": 42075, "text": "$(document).ajaxError( function(event, xhr, options, exc) )" }, { "code": null, "e": 42275, "s": 42135, "text": "Parameter:: This method accepts single parameter function which is mandatory. This function accepts four parameters which are listed below:" }, { "code": null, "e": 42321, "s": 42275, "text": "event: This parameter holds the event object." }, { "code": null, "e": 42362, "s": 42321, "text": "xhr: It holds the XMLHttpRequest object." }, { "code": null, "e": 42417, "s": 42362, "text": "options: It contains the used options in AJAX request." }, { "code": null, "e": 42457, "s": 42417, "text": "exc: It holds the JavaScript exception." }, { "code": null, "e": 42559, "s": 42457, "text": "The demo.txt file stored on server and it will load after clicking the change content button.demo.txt" }, { "code": null, "e": 42572, "s": 42559, "text": "This is GFG." }, { "code": null, "e": 42744, "s": 42572, "text": "Example 1: This example changes the content of <p> element, by taking the data from server. When the AJAX request fails due to an error, the page says AJAX request fails.." }, { "code": "<!DOCTYPE html> <html> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to use ajaxError() method --> <script> $(document).ready(function() { $(document).ajaxError(function() { alert(\"AJAX request fails.\"); }); $(\"button\").click(function() { $(\"#paragraph\").load(\"demo.txt\"); }); }); </script> </head> <body style=\"text-align:center;\"> <div id=\"div_content\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <p id = \"paragraph\" style= \"font-size: 20px;\"> A computer science portal for geeks </p> </div> <button> Change Content </button> </body> </html> ", "e": 43741, "s": 42744, "text": null }, { "code": null, "e": 43749, "s": 43741, "text": "Output:" }, { "code": null, "e": 43777, "s": 43749, "text": "Before click on the button:" }, { "code": null, "e": 43804, "s": 43777, "text": "After click on the button:" }, { "code": null, "e": 43977, "s": 43804, "text": "Example 2: This example changes the content of <h1> element, by taking the data from server. When the AJAX request fails due to an error, the page says AJAX request fails.." }, { "code": "<!DOCTYPE html> <html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to use ajaxError() method --> <script> $(document).ready(function() { $(document).ajaxError(function() { alert(\"AJAX request fails.\"); }); $(\"button\").click(function() { $(\"#heading\").load(\"demo.txt\"); }); }); </script> </head> <body style=\"text-align:center;\"> <div id=\"div_content\"> <h1 id = \"heading\" style = \"color: green;\"> GeeksforGeeks </h1> <p style= \"font-size: 20px;\"> A computer science portal for geeks </p> </div> <button> Change Content </button> </body> </html> ", "e": 44969, "s": 43977, "text": null }, { "code": null, "e": 44977, "s": 44969, "text": "Output:" }, { "code": null, "e": 45005, "s": 44977, "text": "Before click on the button:" }, { "code": null, "e": 45032, "s": 45005, "text": "After click on the button:" }, { "code": null, "e": 45044, "s": 45032, "text": "jQuery-AJAX" }, { "code": null, "e": 45051, "s": 45044, "text": "Picked" }, { "code": null, "e": 45058, "s": 45051, "text": "JQuery" }, { "code": null, "e": 45075, "s": 45058, "text": "Web Technologies" }, { "code": null, "e": 45173, "s": 45075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45219, "s": 45173, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 45248, "s": 45219, "text": "Form validation using jQuery" }, { "code": null, "e": 45311, "s": 45248, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 45388, "s": 45311, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 45462, "s": 45388, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" }, { "code": null, "e": 45502, "s": 45462, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 45535, "s": 45502, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 45580, "s": 45535, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45623, "s": 45580, "text": "How to fetch data from an API in ReactJS ?" } ]
Types of Threads in C# - GeeksforGeeks
15 Sep, 2021 Multi-threading is the most useful feature of C# which allows concurrent programming of two or more parts of the program for maximizing the utilization of the CPU. Each part of a program is called Thread. So, in other words, threads are lightweight processes within a process. C# supports two types of threads are as follows : A thread which keeps on running to complete its work even if the Main thread leaves its process, this type of thread is known as foreground thread. Foreground thread does not care whether the main thread is alive or not, it completes only when it finishes its assigned work. Or in other words, the life of the foreground thread does not depend upon the main thread.Example: CSharp // C# program to illustrate the// concept of foreground threadusing System;using System.Threading; class GFG { // Main method static void Main(string[] args) { // Creating and initializing thread Thread thr = new Thread(mythread); thr.Start(); Console.WriteLine("Main Thread Ends!!"); } // Static method static void mythread() { for (int c = 0; c <= 3; c++) { Console.WriteLine("mythread is in progress!!"); Thread.Sleep(1000); } Console.WriteLine("mythread ends!!"); }} Output: Main Thread Ends!! mythread is in progress!! mythread is in progress!! mythread is in progress!! mythread is in progress!! mythread ends!! Explanation: In the above example, thr thread runs after main thread ended. So, the life of thr thread doesn’t depend upon the life of the main thread. The thr thread only ends its process when it completes its assigned task. A thread which leaves its process when the Main method leaves its process, these types of the thread are known as the background threads. Or in other words, the life of the background thread depends upon the life of the main thread. If the main thread finishes its process, then background thread also ends its process. Note: If you want to use a background thread in your program, then set the value of IsBackground property of the thread to true.Example: CSharp // C# program to illustrate the// concept of Background threadusing System;using System.Threading; class GFG { // Main method static void Main(string[] args) { // Creating and initializing thread Thread thr = new Thread(mythread); // Name of the thread is Mythread thr.Name = "Mythread"; thr.Start(); // IsBackground is the property of Thread // which allows thread to run in the background thr.IsBackground = true; Console.WriteLine("Main Thread Ends!!"); } // Static method static void mythread() { // Display the name of the // current working thread Console.WriteLine("In progress thread is: {0}", Thread.CurrentThread.Name); Thread.Sleep(2000); Console.WriteLine("Completed thread is: {0}", Thread.CurrentThread.Name); }} Output: In progress thread is: Mythread Main Thread Ends!! Explanation: In the above example, IsBackground property of Thread class is used to set the thr thread as a background thread by making the value of IsBackground true. If you set the value of IsBackground false, then the given thread behaves as a foreground Thread. Now, the process of the thr thread ends when the process of the main thread ends. adnanirshad158 CSharp Multithreading C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25993, "s": 25965, "text": "\n15 Sep, 2021" }, { "code": null, "e": 26320, "s": 25993, "text": "Multi-threading is the most useful feature of C# which allows concurrent programming of two or more parts of the program for maximizing the utilization of the CPU. Each part of a program is called Thread. So, in other words, threads are lightweight processes within a process. C# supports two types of threads are as follows :" }, { "code": null, "e": 26697, "s": 26322, "text": "A thread which keeps on running to complete its work even if the Main thread leaves its process, this type of thread is known as foreground thread. Foreground thread does not care whether the main thread is alive or not, it completes only when it finishes its assigned work. Or in other words, the life of the foreground thread does not depend upon the main thread.Example: " }, { "code": null, "e": 26704, "s": 26697, "text": "CSharp" }, { "code": "// C# program to illustrate the// concept of foreground threadusing System;using System.Threading; class GFG { // Main method static void Main(string[] args) { // Creating and initializing thread Thread thr = new Thread(mythread); thr.Start(); Console.WriteLine(\"Main Thread Ends!!\"); } // Static method static void mythread() { for (int c = 0; c <= 3; c++) { Console.WriteLine(\"mythread is in progress!!\"); Thread.Sleep(1000); } Console.WriteLine(\"mythread ends!!\"); }}", "e": 27274, "s": 26704, "text": null }, { "code": null, "e": 27284, "s": 27274, "text": "Output: " }, { "code": null, "e": 27423, "s": 27284, "text": "Main Thread Ends!!\nmythread is in progress!!\nmythread is in progress!!\nmythread is in progress!!\nmythread is in progress!!\nmythread ends!!" }, { "code": null, "e": 27650, "s": 27423, "text": "Explanation: In the above example, thr thread runs after main thread ended. So, the life of thr thread doesn’t depend upon the life of the main thread. The thr thread only ends its process when it completes its assigned task. " }, { "code": null, "e": 28108, "s": 27650, "text": "A thread which leaves its process when the Main method leaves its process, these types of the thread are known as the background threads. Or in other words, the life of the background thread depends upon the life of the main thread. If the main thread finishes its process, then background thread also ends its process. Note: If you want to use a background thread in your program, then set the value of IsBackground property of the thread to true.Example: " }, { "code": null, "e": 28115, "s": 28108, "text": "CSharp" }, { "code": "// C# program to illustrate the// concept of Background threadusing System;using System.Threading; class GFG { // Main method static void Main(string[] args) { // Creating and initializing thread Thread thr = new Thread(mythread); // Name of the thread is Mythread thr.Name = \"Mythread\"; thr.Start(); // IsBackground is the property of Thread // which allows thread to run in the background thr.IsBackground = true; Console.WriteLine(\"Main Thread Ends!!\"); } // Static method static void mythread() { // Display the name of the // current working thread Console.WriteLine(\"In progress thread is: {0}\", Thread.CurrentThread.Name); Thread.Sleep(2000); Console.WriteLine(\"Completed thread is: {0}\", Thread.CurrentThread.Name); }}", "e": 29024, "s": 28115, "text": null }, { "code": null, "e": 29034, "s": 29024, "text": "Output: " }, { "code": null, "e": 29085, "s": 29034, "text": "In progress thread is: Mythread\nMain Thread Ends!!" }, { "code": null, "e": 29434, "s": 29085, "text": "Explanation: In the above example, IsBackground property of Thread class is used to set the thr thread as a background thread by making the value of IsBackground true. If you set the value of IsBackground false, then the given thread behaves as a foreground Thread. Now, the process of the thr thread ends when the process of the main thread ends. " }, { "code": null, "e": 29449, "s": 29434, "text": "adnanirshad158" }, { "code": null, "e": 29471, "s": 29449, "text": "CSharp Multithreading" }, { "code": null, "e": 29474, "s": 29471, "text": "C#" }, { "code": null, "e": 29572, "s": 29474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29600, "s": 29572, "text": "C# Dictionary with examples" }, { "code": null, "e": 29615, "s": 29600, "text": "C# | Delegates" }, { "code": null, "e": 29638, "s": 29615, "text": "C# | Method Overriding" }, { "code": null, "e": 29660, "s": 29638, "text": "C# | Abstract Classes" }, { "code": null, "e": 29706, "s": 29660, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29729, "s": 29706, "text": "Extension Method in C#" }, { "code": null, "e": 29751, "s": 29729, "text": "C# | Class and Object" }, { "code": null, "e": 29769, "s": 29751, "text": "C# | Constructors" }, { "code": null, "e": 29809, "s": 29769, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Search insert position of K in a sorted array - GeeksforGeeks
27 Apr, 2022 Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it’s present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted. Examples: Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is 2. Input: arr[] = {1, 3, 5, 6}, K = 2Output: 1Explanation: Since 2 is not present in the array but can be inserted at index 1 to make the array sorted. Naive Approach: Follow the steps below to solve the problem: Iterate over every element of the array arr[] and search for integer K. If any array element is found to be equal to K, then print index of K. Otherwise, if any array element is found to be greater than K, print that index as the insert position of K. If no element is found to be exceeding K, K must be inserted after the last array element. Below is the implementation of above approach : C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find insert position of Kint find_index(int arr[], int n, int K){ // Traverse the array for (int i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 2; cout << find_index(arr, n, K) << endl; return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Traverse the array for(int i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 3, 5, 6 }; int n = arr.length; int K = 2; System.out.println(find_index(arr, n, K));}} // This code is contributed by akhilsaini # Python program for the above approach # Function to find insert position of Kdef find_index(arr, n, K): # Traverse the array for i in range(n): # If K is found if arr[i] == K: return i # If arr[i] exceeds K elif arr[i] > K: return i # If all array elements are smaller return n # Driver Codearr = [1, 3, 5, 6]n = len(arr)K = 2print(find_index(arr, n, K)) // C# program for the above approachusing System; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Traverse the array for(int i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver Codepublic static void Main(){ int[] arr = { 1, 3, 5, 6 }; int n = arr.Length; int K = 2; Console.WriteLine(find_index(arr, n, K));}} // This code is contributed by akhilsaini <script> // Javascript program for the above approach // Function to find insert position of Kfunction find_index(arr, n, K){ // Traverse the array for(let i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver codelet arr = [ 1, 3, 5, 6 ];let n = arr.length;let K = 2; document.write(find_index(arr, n, K)); // This code is contributed by splevel62 </script> 1 Time Complexity: O(N)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to use Binary Search. Follow the steps below to solve the problem: Set start and end as 0 and N – 1, where the start and end variables denote the lower and upper bound of the search space respectively. Calculate mid = (start + end) / 2. If arr[mid] is found to be equal to K, print mid as the required answer. If arr[mid] exceeds K, set high = mid – 1 Otherwise, set low = mid + 1. Below is the implementation of above approach : C++ C Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find insert position of Kint find_index(int arr[], int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 2; cout << find_index(arr, n, K) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program for the above approach #include<stdio.h> // Function to find insert position of Kint find_index(int arr[], int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 2; printf("%d",find_index(arr, n, K)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program for the above approachimport java.io.*; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 3, 5, 6 }; int n = arr.length; int K = 2; System.out.println(find_index(arr, n, K));}} // This code is contributed by akhilsaini # Python program to implement# the above approach # Function to find insert position of Kdef find_index(arr, n, B): # Lower and upper bounds start = 0 end = n - 1 # Traverse the search space while start<= end: mid =(start + end)//2 if arr[mid] == K: return mid elif arr[mid] < K: start = mid + 1 else: end = mid-1 # Return the insert position return end + 1 # Driver Codearr = [1, 3, 5, 6]n = len(arr)K = 2print(find_index(arr, n, K)) // C# program for the above approachusing System; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codepublic static void Main(){ int[] arr = { 1, 3, 5, 6 }; int n = arr.Length; int K = 2; Console.WriteLine(find_index(arr, n, K));}} // This code is contributed by akhilsaini <script>// JavaScript program for the above approach // Function to find insert position of Kfunction find_index(arr, n, K){ // Lower and upper bounds let start = 0; let end = n - 1; // Traverse the search space while (start <= end) { let mid = Math.floor((start + end) / 2); // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Code let arr = [ 1, 3, 5, 6 ]; let n = arr.length; let K = 2; document.write(find_index(arr, n, K) + "<br>"); // This code is contributed by Surbhi Tyagi.</script> 1 Time Complexity: O(log N)Auxiliary Space: O(1) akhilsaini splevel62 surbhityagi15 adityakumar129 array-rearrange array-traversal-question Binary Search Arrays Searching Arrays Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26373, "s": 26345, "text": "\n27 Apr, 2022" }, { "code": null, "e": 26601, "s": 26373, "text": "Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it’s present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted." }, { "code": null, "e": 26612, "s": 26601, "text": "Examples: " }, { "code": null, "e": 26728, "s": 26612, "text": "Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is 2." }, { "code": null, "e": 26877, "s": 26728, "text": "Input: arr[] = {1, 3, 5, 6}, K = 2Output: 1Explanation: Since 2 is not present in the array but can be inserted at index 1 to make the array sorted." }, { "code": null, "e": 26938, "s": 26877, "text": "Naive Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 27010, "s": 26938, "text": "Iterate over every element of the array arr[] and search for integer K." }, { "code": null, "e": 27081, "s": 27010, "text": "If any array element is found to be equal to K, then print index of K." }, { "code": null, "e": 27281, "s": 27081, "text": "Otherwise, if any array element is found to be greater than K, print that index as the insert position of K. If no element is found to be exceeding K, K must be inserted after the last array element." }, { "code": null, "e": 27329, "s": 27281, "text": "Below is the implementation of above approach :" }, { "code": null, "e": 27333, "s": 27329, "text": "C++" }, { "code": null, "e": 27338, "s": 27333, "text": "Java" }, { "code": null, "e": 27346, "s": 27338, "text": "Python3" }, { "code": null, "e": 27349, "s": 27346, "text": "C#" }, { "code": null, "e": 27360, "s": 27349, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find insert position of Kint find_index(int arr[], int n, int K){ // Traverse the array for (int i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 2; cout << find_index(arr, n, K) << endl; return 0;}", "e": 27985, "s": 27360, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Traverse the array for(int i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 3, 5, 6 }; int n = arr.length; int K = 2; System.out.println(find_index(arr, n, K));}} // This code is contributed by akhilsaini", "e": 28658, "s": 27985, "text": null }, { "code": "# Python program for the above approach # Function to find insert position of Kdef find_index(arr, n, K): # Traverse the array for i in range(n): # If K is found if arr[i] == K: return i # If arr[i] exceeds K elif arr[i] > K: return i # If all array elements are smaller return n # Driver Codearr = [1, 3, 5, 6]n = len(arr)K = 2print(find_index(arr, n, K))", "e": 29117, "s": 28658, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Traverse the array for(int i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver Codepublic static void Main(){ int[] arr = { 1, 3, 5, 6 }; int n = arr.Length; int K = 2; Console.WriteLine(find_index(arr, n, K));}} // This code is contributed by akhilsaini", "e": 29770, "s": 29117, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find insert position of Kfunction find_index(arr, n, K){ // Traverse the array for(let i = 0; i < n; i++) // If K is found if (arr[i] == K) return i; // If current array element // exceeds K else if (arr[i] > K) return i; // If all elements are smaller // than K return n;} // Driver codelet arr = [ 1, 3, 5, 6 ];let n = arr.length;let K = 2; document.write(find_index(arr, n, K)); // This code is contributed by splevel62 </script>", "e": 30362, "s": 29770, "text": null }, { "code": null, "e": 30364, "s": 30362, "text": "1" }, { "code": null, "e": 30409, "s": 30366, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 30541, "s": 30409, "text": "Efficient Approach: To optimize the above approach, the idea is to use Binary Search. Follow the steps below to solve the problem: " }, { "code": null, "e": 30676, "s": 30541, "text": "Set start and end as 0 and N – 1, where the start and end variables denote the lower and upper bound of the search space respectively." }, { "code": null, "e": 30711, "s": 30676, "text": "Calculate mid = (start + end) / 2." }, { "code": null, "e": 30784, "s": 30711, "text": "If arr[mid] is found to be equal to K, print mid as the required answer." }, { "code": null, "e": 30858, "s": 30784, "text": "If arr[mid] exceeds K, set high = mid – 1 Otherwise, set low = mid + 1. " }, { "code": null, "e": 30906, "s": 30858, "text": "Below is the implementation of above approach :" }, { "code": null, "e": 30910, "s": 30906, "text": "C++" }, { "code": null, "e": 30912, "s": 30910, "text": "C" }, { "code": null, "e": 30917, "s": 30912, "text": "Java" }, { "code": null, "e": 30925, "s": 30917, "text": "Python3" }, { "code": null, "e": 30928, "s": 30925, "text": "C#" }, { "code": null, "e": 30939, "s": 30928, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find insert position of Kint find_index(int arr[], int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 2; cout << find_index(arr, n, K) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 31716, "s": 30939, "text": null }, { "code": "// C program for the above approach #include<stdio.h> // Function to find insert position of Kint find_index(int arr[], int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codeint main(){ int arr[] = { 1, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 2; printf(\"%d\",find_index(arr, n, K)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 32461, "s": 31716, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 3, 5, 6 }; int n = arr.length; int K = 2; System.out.println(find_index(arr, n, K));}} // This code is contributed by akhilsaini", "e": 33230, "s": 32461, "text": null }, { "code": "# Python program to implement# the above approach # Function to find insert position of Kdef find_index(arr, n, B): # Lower and upper bounds start = 0 end = n - 1 # Traverse the search space while start<= end: mid =(start + end)//2 if arr[mid] == K: return mid elif arr[mid] < K: start = mid + 1 else: end = mid-1 # Return the insert position return end + 1 # Driver Codearr = [1, 3, 5, 6]n = len(arr)K = 2print(find_index(arr, n, K))", "e": 33753, "s": 33230, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find insert position of Kstatic int find_index(int[] arr, int n, int K){ // Lower and upper bounds int start = 0; int end = n - 1; // Traverse the search space while (start <= end) { int mid = (start + end) / 2; // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Codepublic static void Main(){ int[] arr = { 1, 3, 5, 6 }; int n = arr.Length; int K = 2; Console.WriteLine(find_index(arr, n, K));}} // This code is contributed by akhilsaini", "e": 34502, "s": 33753, "text": null }, { "code": "<script>// JavaScript program for the above approach // Function to find insert position of Kfunction find_index(arr, n, K){ // Lower and upper bounds let start = 0; let end = n - 1; // Traverse the search space while (start <= end) { let mid = Math.floor((start + end) / 2); // If K is found if (arr[mid] == K) return mid; else if (arr[mid] < K) start = mid + 1; else end = mid - 1; } // Return insert position return end + 1;} // Driver Code let arr = [ 1, 3, 5, 6 ]; let n = arr.length; let K = 2; document.write(find_index(arr, n, K) + \"<br>\"); // This code is contributed by Surbhi Tyagi.</script>", "e": 35217, "s": 34502, "text": null }, { "code": null, "e": 35219, "s": 35217, "text": "1" }, { "code": null, "e": 35268, "s": 35221, "text": "Time Complexity: O(log N)Auxiliary Space: O(1)" }, { "code": null, "e": 35279, "s": 35268, "text": "akhilsaini" }, { "code": null, "e": 35289, "s": 35279, "text": "splevel62" }, { "code": null, "e": 35303, "s": 35289, "text": "surbhityagi15" }, { "code": null, "e": 35318, "s": 35303, "text": "adityakumar129" }, { "code": null, "e": 35334, "s": 35318, "text": "array-rearrange" }, { "code": null, "e": 35359, "s": 35334, "text": "array-traversal-question" }, { "code": null, "e": 35373, "s": 35359, "text": "Binary Search" }, { "code": null, "e": 35380, "s": 35373, "text": "Arrays" }, { "code": null, "e": 35390, "s": 35380, "text": "Searching" }, { "code": null, "e": 35397, "s": 35390, "text": "Arrays" }, { "code": null, "e": 35407, "s": 35397, "text": "Searching" }, { "code": null, "e": 35421, "s": 35407, "text": "Binary Search" }, { "code": null, "e": 35519, "s": 35421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35587, "s": 35519, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35631, "s": 35587, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35654, "s": 35631, "text": "Introduction to Arrays" }, { "code": null, "e": 35686, "s": 35654, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35700, "s": 35686, "text": "Linear Search" }, { "code": null, "e": 35714, "s": 35700, "text": "Binary Search" }, { "code": null, "e": 35782, "s": 35714, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35796, "s": 35782, "text": "Linear Search" }, { "code": null, "e": 35844, "s": 35796, "text": "Search an element in a sorted and rotated array" } ]
Minimum time required to fill a cistern using N pipes - GeeksforGeeks
13 Apr, 2021 Given the time required by a total of N+1 pipes where N pipes are used to fill the Cistern and a single pipe is used to empty the Cistern. The task is to Calculate the amount of time in which the Cistern will get filled if all the N+1 pipes are opened together. Examples: Input: n = 2, pipe1 = 12 hours, pipe2 = 14 hours, emptypipe = 30 hours Output: 8 hours Input: n = 1, pipe1 = 12 hours emptypipe = 18 hours Output: 36 hours Approach: If a pipe1 can fill a cistern in ‘n’ hours, then in 1 hour, the pipe1 will able to fill ‘1/n’ Cistern. Similarly If a pipe2 can fill a cistern in ‘m’ hours, then in one hour, the pipe2 will able to fill ‘1/m’ Cistern. So on.... for other pipes. So, total work done in filling a Cistern by N pipes in 1 hours is 1/n + 1/m + 1/p...... + 1/zWhere n, m, p ....., z are the number of hours taken by each pipes respectively. The result of the above expression will be the part of work done by all pipes together in 1 hours, let’s say a / b.To calculate the time taken to fill the cistern will be b / a. Consider an example of two pipes: Time taken by 1st pipe to fill the cistern = 12 hours Time taken by 2nd pipe to fill the cistern = 14 hours Time taken by 3rd pipe to empty the cistern = 30 hoursWork done by 1st pipe in 1 hour = 1/12 Work done by 2nd pipe in 1 hour = 1/14 Work done by 3nd pipe in 1 hour = – (1/30) as it empty the pipe. So, total work done by all the pipes in 1 hour is => ( 1 / 12 + 1/ 14 ) – (1 / 30) => ((7 + 6 ) / (84)) – (1 / 30) => ((13) / (84)) – (1 / 30) => 51 / 420So, to Fill the cistern time required will be 420 / 51 i.e 8 hours Approx. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the timefloat Time(float arr[], int n, int Emptypipe){ float fill = 0; for (int i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / (float)Emptypipe); return 1 / fill;} // Driver Codeint main(){ float arr[] = { 12, 14 }; float Emptypipe = 30; int n = sizeof(arr) / sizeof(arr[0]); cout << floor(Time(arr, n, Emptypipe)) << " Hours"; return 0;} // Java implementation of// above approachimport java.io.*; class GFG{ // Function to calculate the timestatic float Time(float arr[], int n, float Emptypipe){ float fill = 0; for (int i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / (float)Emptypipe); return 1 / fill;} // Driver Codepublic static void main (String[] args){ float arr[] = { 12, 14 }; float Emptypipe = 30; int n = arr.length; System.out.println((int)(Time(arr, n, Emptypipe)) + " Hours");}} // This code is contributed// by inder_verma. # Python3 implementation of# above approach # Function to calculate the timedef Time(arr, n, Emptypipe) : fill = 0 for i in range(0,n) : fill += (1 / arr[i]) fill = fill - (1 / float(Emptypipe)) return int(1 / fill) # Driver Codeif __name__=='__main__': arr = [ 12, 14 ] Emptypipe = 30 n = len(arr) print((Time(arr, n, Emptypipe)) , "Hours") # This code is contributed by# Smitha Dinesh Semwal // C# implementation of// above approachusing System; class GFG{ // Function to calculate the timestatic float Time(float []arr, int n, float Emptypipe){ float fill = 0; for (int i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / (float)Emptypipe); return 1 / fill;} // Driver Codepublic static void Main (){ float []arr = { 12, 14 }; float Emptypipe = 30; int n = arr.Length; Console.WriteLine((int)(Time(arr, n, Emptypipe)) + " Hours");}} // This code is contributed// by inder_verma. <?php// PHP implementation of above approach // Function to calculate the timefunction T_ime($arr, $n, $Emptypipe){ $fill = 0; for ($i = 0; $i < $n; $i++) $fill += 1 / $arr[$i]; $fill = $fill - (1 / $Emptypipe); return 1 / $fill;} // Driver Code$arr = array( 12, 14 );$Emptypipe = 30;$n = count($arr); echo (int)T_ime($arr, $n, $Emptypipe) . " Hours"; // This code is contributed// by inder_verma.?> <script> // Javascript implementation of above approach // Function to calculate the timefunction Time(arr, n, Emptypipe){ var fill = 0; for(var i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / Emptypipe); return 1 / fill;} // Driver Codevar arr = [ 12, 14 ];var Emptypipe = 30;var n = arr.length; document.write(Math.floor( Time(arr, n, Emptypipe)) + " Hours"); // This code is contributed by itsok </script> 8 Hours inderDuMCA Smitha Dinesh Semwal itsok Pipes and Cisterns Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Program to multiply two matrices Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25937, "s": 25909, "text": "\n13 Apr, 2021" }, { "code": null, "e": 26199, "s": 25937, "text": "Given the time required by a total of N+1 pipes where N pipes are used to fill the Cistern and a single pipe is used to empty the Cistern. The task is to Calculate the amount of time in which the Cistern will get filled if all the N+1 pipes are opened together." }, { "code": null, "e": 26210, "s": 26199, "text": "Examples: " }, { "code": null, "e": 26370, "s": 26210, "text": "Input: n = 2, \npipe1 = 12 hours, pipe2 = 14 hours,\nemptypipe = 30 hours\nOutput: 8 hours\n\nInput: n = 1, \npipe1 = 12 hours\nemptypipe = 18 hours\nOutput: 36 hours " }, { "code": null, "e": 26381, "s": 26370, "text": "Approach: " }, { "code": null, "e": 26484, "s": 26381, "text": "If a pipe1 can fill a cistern in ‘n’ hours, then in 1 hour, the pipe1 will able to fill ‘1/n’ Cistern." }, { "code": null, "e": 26599, "s": 26484, "text": "Similarly If a pipe2 can fill a cistern in ‘m’ hours, then in one hour, the pipe2 will able to fill ‘1/m’ Cistern." }, { "code": null, "e": 26626, "s": 26599, "text": "So on.... for other pipes." }, { "code": null, "e": 26693, "s": 26626, "text": "So, total work done in filling a Cistern by N pipes in 1 hours is " }, { "code": null, "e": 26801, "s": 26693, "text": "1/n + 1/m + 1/p...... + 1/zWhere n, m, p ....., z are the number of hours taken by each pipes respectively." }, { "code": null, "e": 26979, "s": 26801, "text": "The result of the above expression will be the part of work done by all pipes together in 1 hours, let’s say a / b.To calculate the time taken to fill the cistern will be b / a." }, { "code": null, "e": 27014, "s": 26979, "text": "Consider an example of two pipes: " }, { "code": null, "e": 27548, "s": 27014, "text": "Time taken by 1st pipe to fill the cistern = 12 hours Time taken by 2nd pipe to fill the cistern = 14 hours Time taken by 3rd pipe to empty the cistern = 30 hoursWork done by 1st pipe in 1 hour = 1/12 Work done by 2nd pipe in 1 hour = 1/14 Work done by 3nd pipe in 1 hour = – (1/30) as it empty the pipe. So, total work done by all the pipes in 1 hour is => ( 1 / 12 + 1/ 14 ) – (1 / 30) => ((7 + 6 ) / (84)) – (1 / 30) => ((13) / (84)) – (1 / 30) => 51 / 420So, to Fill the cistern time required will be 420 / 51 i.e 8 hours Approx." }, { "code": null, "e": 27597, "s": 27548, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27601, "s": 27597, "text": "C++" }, { "code": null, "e": 27606, "s": 27601, "text": "Java" }, { "code": null, "e": 27614, "s": 27606, "text": "Python3" }, { "code": null, "e": 27617, "s": 27614, "text": "C#" }, { "code": null, "e": 27621, "s": 27617, "text": "PHP" }, { "code": null, "e": 27632, "s": 27621, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the timefloat Time(float arr[], int n, int Emptypipe){ float fill = 0; for (int i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / (float)Emptypipe); return 1 / fill;} // Driver Codeint main(){ float arr[] = { 12, 14 }; float Emptypipe = 30; int n = sizeof(arr) / sizeof(arr[0]); cout << floor(Time(arr, n, Emptypipe)) << \" Hours\"; return 0;}", "e": 28130, "s": 27632, "text": null }, { "code": "// Java implementation of// above approachimport java.io.*; class GFG{ // Function to calculate the timestatic float Time(float arr[], int n, float Emptypipe){ float fill = 0; for (int i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / (float)Emptypipe); return 1 / fill;} // Driver Codepublic static void main (String[] args){ float arr[] = { 12, 14 }; float Emptypipe = 30; int n = arr.length; System.out.println((int)(Time(arr, n, Emptypipe)) + \" Hours\");}} // This code is contributed// by inder_verma.", "e": 28726, "s": 28130, "text": null }, { "code": "# Python3 implementation of# above approach # Function to calculate the timedef Time(arr, n, Emptypipe) : fill = 0 for i in range(0,n) : fill += (1 / arr[i]) fill = fill - (1 / float(Emptypipe)) return int(1 / fill) # Driver Codeif __name__=='__main__': arr = [ 12, 14 ] Emptypipe = 30 n = len(arr) print((Time(arr, n, Emptypipe)) , \"Hours\") # This code is contributed by# Smitha Dinesh Semwal", "e": 29164, "s": 28726, "text": null }, { "code": "// C# implementation of// above approachusing System; class GFG{ // Function to calculate the timestatic float Time(float []arr, int n, float Emptypipe){ float fill = 0; for (int i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / (float)Emptypipe); return 1 / fill;} // Driver Codepublic static void Main (){ float []arr = { 12, 14 }; float Emptypipe = 30; int n = arr.Length; Console.WriteLine((int)(Time(arr, n, Emptypipe)) + \" Hours\");}} // This code is contributed// by inder_verma.", "e": 29776, "s": 29164, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to calculate the timefunction T_ime($arr, $n, $Emptypipe){ $fill = 0; for ($i = 0; $i < $n; $i++) $fill += 1 / $arr[$i]; $fill = $fill - (1 / $Emptypipe); return 1 / $fill;} // Driver Code$arr = array( 12, 14 );$Emptypipe = 30;$n = count($arr); echo (int)T_ime($arr, $n, $Emptypipe) . \" Hours\"; // This code is contributed// by inder_verma.?>", "e": 30212, "s": 29776, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to calculate the timefunction Time(arr, n, Emptypipe){ var fill = 0; for(var i = 0; i < n; i++) fill += 1 / arr[i]; fill = fill - (1 / Emptypipe); return 1 / fill;} // Driver Codevar arr = [ 12, 14 ];var Emptypipe = 30;var n = arr.length; document.write(Math.floor( Time(arr, n, Emptypipe)) + \" Hours\"); // This code is contributed by itsok </script>", "e": 30659, "s": 30212, "text": null }, { "code": null, "e": 30667, "s": 30659, "text": "8 Hours" }, { "code": null, "e": 30680, "s": 30669, "text": "inderDuMCA" }, { "code": null, "e": 30701, "s": 30680, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 30707, "s": 30701, "text": "itsok" }, { "code": null, "e": 30726, "s": 30707, "text": "Pipes and Cisterns" }, { "code": null, "e": 30739, "s": 30726, "text": "Mathematical" }, { "code": null, "e": 30758, "s": 30739, "text": "School Programming" }, { "code": null, "e": 30771, "s": 30758, "text": "Mathematical" }, { "code": null, "e": 30869, "s": 30771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30913, "s": 30869, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30955, "s": 30913, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 31026, "s": 30955, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 31057, "s": 31026, "text": "Modular multiplicative inverse" }, { "code": null, "e": 31090, "s": 31057, "text": "Program to multiply two matrices" }, { "code": null, "e": 31108, "s": 31090, "text": "Python Dictionary" }, { "code": null, "e": 31124, "s": 31108, "text": "Arrays in C/C++" }, { "code": null, "e": 31143, "s": 31124, "text": "Inheritance in C++" }, { "code": null, "e": 31168, "s": 31143, "text": "Reverse a string in Java" } ]
Optimal partition of an array into four parts - GeeksforGeeks
21 Jun, 2021 Given an array of n non-negative integers. Choose three indices i.e. (0 <= index_1 <= index_ 2<= index_3 <= n) from the array to make four subsets such that the term sum(0, index_1) – sum(index_1, index_2) + sum(index_2, index_3) – sum(index_3, n) is maximum possible. Here, two indices say l and r means, the sum(l, r) will be the sum of all numbers of subset on positions from l to r non-inclusive (l-th element is not counted, r-th element is counted). For example, if arr = {-5, 3, 9, 4}, then sum(0, 1) = -5, sum(0, 2) = -2, sum(1, 4) = 16 and sum(i, i) = 0 for each i from 0 to 4. For indices l and r holds 0 <= l <= r <= n. Indices in array are numbered from 0.Examples: Input : arr = {-1, 2, 3} Output : 0 1 3 Here, sum(0, 0) = 0 sum(0, 1) = -1 sum(1, 3) = 2 + 3 = 5 sum(3, 3) = 0 Therefore , sum(0, 0) - sum(0, 1) + sum(1, 3) - sum(3, 3) = 4 which is maximum. Input : arr = {0, 0, -1, 0} Output : 0 0 0 Here, sum(0, 0) - sum(0, 0) + sum(0, 0) - sum(0, 0) = 0 which is maximum possible. Imagine the same task but without the first term in sum. As the sum of the array is fixed, the best second segment should be the one with the greatest sum. This can be solved in O(n) with prefix sum. When recalling the best segment to end at position i, take minimal prefix sum from 0 to i inclusive (from the whole sum you want to subtract the lowest number). Now let’s just iterate over all possible ends of the first segment and solve the task above on the array without this segment. C++ Java Python3 C# PHP Javascript // CPP program to find three indices#include <bits/stdc++.h>#define max 50009using namespace std; // Function to find required indices.void find_Indices(int arr[], int n){ int sum[max], k; int index_1, index_2, index_3, index; // calculating prefix sum from // 1 to i for each i. for (int i = 1, k = 0; i <= n; i++) sum[i] = sum[i-1] + arr[k++]; long long ans = -(1e15); index_1 = index_2 = index_3 = -1; // iterating the loop from 0 to n // for all possibilities. for (int l = 0; l <= n; l++) { int index = 0; long long vmin = (1e15); // Here, we recalling the best // segment to end at position i. for (int r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. printf("%d %d %d", index_1, index_2, index_3);} // Driver functionint main() { int arr[] = {-1, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); find_Indices(arr, n);} // Java program to find three indicesclass GFG { static final int max = 50009; // Function to find required indices. static void find_Indices(int arr[], int n) { int sum[] = new int[max]; int index_1, index_2, index_3, index; int k, i; // calculating prefix sum from // 1 to i for each i. for (i = 1, k = 0; i <= n; i++) sum[i] = sum[i - 1] + arr[k++]; double ans = -(1e15); index_1 = index_2 = index_3 = -1; // iterating the loop from 0 to n // for all possibilities. for (int l = 0; l <= n; l++) { index = 0; double vmin = (1e15); // Here, we recalling the best // segment to end at position i. for (int r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. System.out.print(index_1 + " " + index_2 + " " + index_3); } // Driver function. public static void main(String[] args) { int arr[] = { -1, 2, 3 }; int n = arr.length; find_Indices(arr, n); }} // This code is contributed by Anant Agarwal. # Python program to# find three indices max = 50009 # Function to find# required indices.def find_Indices(arr, n): sum=[0 for i in range(max)] # calculating prefix sum from # 1 to i for each i. k=0 for i in range(1,n+1): sum[i] = sum[i-1] + arr[k]; k+=1 ans = -(1e15) index_1 = index_2 = index_3 = -1 # iterating the loop from 0 to n # for all possibilities. for l in range(n+1): index = 0 vmin = (1e15) # Here, we recalling the best # segment to end at position i. for r in range(l,n+1): # taking the minimal prefix # sum from 0 to i inclusive. if (sum[r] < vmin): vmin = sum[r] index = r # calculating the indices. if (sum[l] + sum[r] - vmin > ans): ans = sum[l] + sum[r] - vmin index_1 = l index_2 = index index_3 = r # Required indices. print(index_1," ", index_2," ", index_3) # Driver function arr = [-1, 2, 3]n = len(arr)find_Indices(arr, n) # This code is contributed# by Anant Agarwal. // C# program to find three indicesusing System; class GFG { static int max = 50009; // Function to find required indices. static void find_Indices(int []arr, int n) { int []sum = new int[max]; int index_1, index_2, index_3, index; int k, i; // calculating prefix sum from // 1 to i for each i. for (i = 1, k = 0; i <= n; i++) sum[i] = sum[i - 1] + arr[k++]; double ans = -(1e15); index_1 = index_2 = index_3 = -1; // iterating the loop from 0 to n // for all possibilities. for (int l = 0; l <= n; l++) { index = 0; double vmin = (1e15); // Here, we recalling the best // segment to end at position i. for (int r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. Console.WriteLine(index_1 + " " + index_2 + " " + index_3); } // Driver function. public static void Main() { int []arr = { -1, 2, 3 }; int n = arr.Length; find_Indices(arr, n); }} // This code is contributed by vt_m. <?php// PHP program to// find three indices$max = 50009; // Function to find// required indices.function find_Indices($arr, $n){ global $max; $sum = array(); $k = 0; $sum[0] = 0; // calculating prefix sum // from 1 to i for each i. for ($i = 1, $k = 0; $i <= $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$k++]; $ans = -(1000000000000000); $index_1 = $index_2 = $index_3 = -1; // iterating the loop from // 0 to n for all possibilities. for ($l = 0; $l <= $n; $l++) { $index = 0; $vmin = (1000000000000000); // Here, we recalling the // best segment to end at // position i. for ($r = $l; $r <= $n; $r++) { // taking the minimal prefix // sum from 0 to i inclusive. if ($sum[$r] < $vmin) { $vmin = $sum[$r]; $index = $r; } // calculating the indices. if ($sum[$l] + $sum[$r] - $vmin > $ans) { $ans = $sum[$l] + $sum[$r] - $vmin; $index_1 = $l; $index_2 = $index; $index_3 = $r; } } } // Required indices. echo($index_1." ".$index_2. " ".$index_3." ");} // Driver Code$arr = array(-1, 2, 3);$n = count($arr);find_Indices($arr, $n); // This code is contributed by// Manish Shaw(manishshaw1)?> <script>// Javascript program to// find three indiceslet max = 50009; // Function to find// required indices.function find_Indices(arr, n){ let sum = new Array(); k = 0; sum[0] = 0; // calculating prefix sum // from 1 to i for each i. for (let i = 1, k = 0; i <= n; i++) sum[i] = sum[i - 1] + arr[k++]; let ans = -(1000000000000000); let index_1 = index_2 = index_3 = -1; // iterating the loop from // 0 to n for all possibilities. for (let l = 0; l <= n; l++) { let index = 0; let vmin = (1000000000000000); // Here, we recalling the // best segment to end at // position i. for (let r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. document.write(index_1 + " " + index_2 +" " + index_3 + " ");} // Driver Codelet arr = new Array(-1, 2, 3);let n = arr.length;find_Indices(arr, n); // This code is contributed by// _saurabh_jaiswal</script> Output: 0 1 3 Time complexity: manishshaw1 _saurabh_jaiswal prefix-sum Arrays prefix-sum Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Queue | Set 1 (Introduction and Array Implementation) Array of Strings in C++ (5 Different Ways to Create) Find the Missing Number Subset Sum Problem | DP-25
[ { "code": null, "e": 26273, "s": 26245, "text": "\n21 Jun, 2021" }, { "code": null, "e": 26953, "s": 26273, "text": "Given an array of n non-negative integers. Choose three indices i.e. (0 <= index_1 <= index_ 2<= index_3 <= n) from the array to make four subsets such that the term sum(0, index_1) – sum(index_1, index_2) + sum(index_2, index_3) – sum(index_3, n) is maximum possible. Here, two indices say l and r means, the sum(l, r) will be the sum of all numbers of subset on positions from l to r non-inclusive (l-th element is not counted, r-th element is counted). For example, if arr = {-5, 3, 9, 4}, then sum(0, 1) = -5, sum(0, 2) = -2, sum(1, 4) = 16 and sum(i, i) = 0 for each i from 0 to 4. For indices l and r holds 0 <= l <= r <= n. Indices in array are numbered from 0.Examples: " }, { "code": null, "e": 27292, "s": 26953, "text": "Input : arr = {-1, 2, 3}\nOutput : 0 1 3 \nHere, sum(0, 0) = 0\n sum(0, 1) = -1\n sum(1, 3) = 2 + 3 = 5\n sum(3, 3) = 0\nTherefore , sum(0, 0) - sum(0, 1) + sum(1, 3) - sum(3, 3) = 4\nwhich is maximum.\n\nInput : arr = {0, 0, -1, 0}\nOutput : 0 0 0\nHere, sum(0, 0) - sum(0, 0) + sum(0, 0) - sum(0, 0) = 0\nwhich is maximum possible." }, { "code": null, "e": 27784, "s": 27294, "text": "Imagine the same task but without the first term in sum. As the sum of the array is fixed, the best second segment should be the one with the greatest sum. This can be solved in O(n) with prefix sum. When recalling the best segment to end at position i, take minimal prefix sum from 0 to i inclusive (from the whole sum you want to subtract the lowest number). Now let’s just iterate over all possible ends of the first segment and solve the task above on the array without this segment. " }, { "code": null, "e": 27788, "s": 27784, "text": "C++" }, { "code": null, "e": 27793, "s": 27788, "text": "Java" }, { "code": null, "e": 27801, "s": 27793, "text": "Python3" }, { "code": null, "e": 27804, "s": 27801, "text": "C#" }, { "code": null, "e": 27808, "s": 27804, "text": "PHP" }, { "code": null, "e": 27819, "s": 27808, "text": "Javascript" }, { "code": "// CPP program to find three indices#include <bits/stdc++.h>#define max 50009using namespace std; // Function to find required indices.void find_Indices(int arr[], int n){ int sum[max], k; int index_1, index_2, index_3, index; // calculating prefix sum from // 1 to i for each i. for (int i = 1, k = 0; i <= n; i++) sum[i] = sum[i-1] + arr[k++]; long long ans = -(1e15); index_1 = index_2 = index_3 = -1; // iterating the loop from 0 to n // for all possibilities. for (int l = 0; l <= n; l++) { int index = 0; long long vmin = (1e15); // Here, we recalling the best // segment to end at position i. for (int r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. printf(\"%d %d %d\", index_1, index_2, index_3);} // Driver functionint main() { int arr[] = {-1, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); find_Indices(arr, n);}", "e": 29201, "s": 27819, "text": null }, { "code": "// Java program to find three indicesclass GFG { static final int max = 50009; // Function to find required indices. static void find_Indices(int arr[], int n) { int sum[] = new int[max]; int index_1, index_2, index_3, index; int k, i; // calculating prefix sum from // 1 to i for each i. for (i = 1, k = 0; i <= n; i++) sum[i] = sum[i - 1] + arr[k++]; double ans = -(1e15); index_1 = index_2 = index_3 = -1; // iterating the loop from 0 to n // for all possibilities. for (int l = 0; l <= n; l++) { index = 0; double vmin = (1e15); // Here, we recalling the best // segment to end at position i. for (int r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. System.out.print(index_1 + \" \" + index_2 + \" \" + index_3); } // Driver function. public static void main(String[] args) { int arr[] = { -1, 2, 3 }; int n = arr.length; find_Indices(arr, n); }} // This code is contributed by Anant Agarwal.", "e": 30879, "s": 29201, "text": null }, { "code": "# Python program to# find three indices max = 50009 # Function to find# required indices.def find_Indices(arr, n): sum=[0 for i in range(max)] # calculating prefix sum from # 1 to i for each i. k=0 for i in range(1,n+1): sum[i] = sum[i-1] + arr[k]; k+=1 ans = -(1e15) index_1 = index_2 = index_3 = -1 # iterating the loop from 0 to n # for all possibilities. for l in range(n+1): index = 0 vmin = (1e15) # Here, we recalling the best # segment to end at position i. for r in range(l,n+1): # taking the minimal prefix # sum from 0 to i inclusive. if (sum[r] < vmin): vmin = sum[r] index = r # calculating the indices. if (sum[l] + sum[r] - vmin > ans): ans = sum[l] + sum[r] - vmin index_1 = l index_2 = index index_3 = r # Required indices. print(index_1,\" \", index_2,\" \", index_3) # Driver function arr = [-1, 2, 3]n = len(arr)find_Indices(arr, n) # This code is contributed# by Anant Agarwal.", "e": 32098, "s": 30879, "text": null }, { "code": "// C# program to find three indicesusing System; class GFG { static int max = 50009; // Function to find required indices. static void find_Indices(int []arr, int n) { int []sum = new int[max]; int index_1, index_2, index_3, index; int k, i; // calculating prefix sum from // 1 to i for each i. for (i = 1, k = 0; i <= n; i++) sum[i] = sum[i - 1] + arr[k++]; double ans = -(1e15); index_1 = index_2 = index_3 = -1; // iterating the loop from 0 to n // for all possibilities. for (int l = 0; l <= n; l++) { index = 0; double vmin = (1e15); // Here, we recalling the best // segment to end at position i. for (int r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. Console.WriteLine(index_1 + \" \" + index_2 + \" \" + index_3); } // Driver function. public static void Main() { int []arr = { -1, 2, 3 }; int n = arr.Length; find_Indices(arr, n); }} // This code is contributed by vt_m.", "e": 33761, "s": 32098, "text": null }, { "code": "<?php// PHP program to// find three indices$max = 50009; // Function to find// required indices.function find_Indices($arr, $n){ global $max; $sum = array(); $k = 0; $sum[0] = 0; // calculating prefix sum // from 1 to i for each i. for ($i = 1, $k = 0; $i <= $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$k++]; $ans = -(1000000000000000); $index_1 = $index_2 = $index_3 = -1; // iterating the loop from // 0 to n for all possibilities. for ($l = 0; $l <= $n; $l++) { $index = 0; $vmin = (1000000000000000); // Here, we recalling the // best segment to end at // position i. for ($r = $l; $r <= $n; $r++) { // taking the minimal prefix // sum from 0 to i inclusive. if ($sum[$r] < $vmin) { $vmin = $sum[$r]; $index = $r; } // calculating the indices. if ($sum[$l] + $sum[$r] - $vmin > $ans) { $ans = $sum[$l] + $sum[$r] - $vmin; $index_1 = $l; $index_2 = $index; $index_3 = $r; } } } // Required indices. echo($index_1.\" \".$index_2. \" \".$index_3.\" \");} // Driver Code$arr = array(-1, 2, 3);$n = count($arr);find_Indices($arr, $n); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 35268, "s": 33761, "text": null }, { "code": "<script>// Javascript program to// find three indiceslet max = 50009; // Function to find// required indices.function find_Indices(arr, n){ let sum = new Array(); k = 0; sum[0] = 0; // calculating prefix sum // from 1 to i for each i. for (let i = 1, k = 0; i <= n; i++) sum[i] = sum[i - 1] + arr[k++]; let ans = -(1000000000000000); let index_1 = index_2 = index_3 = -1; // iterating the loop from // 0 to n for all possibilities. for (let l = 0; l <= n; l++) { let index = 0; let vmin = (1000000000000000); // Here, we recalling the // best segment to end at // position i. for (let r = l; r <= n; r++) { // taking the minimal prefix // sum from 0 to i inclusive. if (sum[r] < vmin) { vmin = sum[r]; index = r; } // calculating the indices. if (sum[l] + sum[r] - vmin > ans) { ans = sum[l] + sum[r] - vmin; index_1 = l; index_2 = index; index_3 = r; } } } // Required indices. document.write(index_1 + \" \" + index_2 +\" \" + index_3 + \" \");} // Driver Codelet arr = new Array(-1, 2, 3);let n = arr.length;find_Indices(arr, n); // This code is contributed by// _saurabh_jaiswal</script>", "e": 36748, "s": 35268, "text": null }, { "code": null, "e": 36758, "s": 36748, "text": "Output: " }, { "code": null, "e": 36764, "s": 36758, "text": "0 1 3" }, { "code": null, "e": 36783, "s": 36764, "text": "Time complexity: " }, { "code": null, "e": 36795, "s": 36783, "text": "manishshaw1" }, { "code": null, "e": 36812, "s": 36795, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36823, "s": 36812, "text": "prefix-sum" }, { "code": null, "e": 36830, "s": 36823, "text": "Arrays" }, { "code": null, "e": 36841, "s": 36830, "text": "prefix-sum" }, { "code": null, "e": 36848, "s": 36841, "text": "Arrays" }, { "code": null, "e": 36946, "s": 36848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36969, "s": 36946, "text": "Introduction to Arrays" }, { "code": null, "e": 37001, "s": 36969, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37022, "s": 37001, "text": "Linked List vs Array" }, { "code": null, "e": 37107, "s": 37022, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37152, "s": 37107, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 37200, "s": 37152, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 37254, "s": 37200, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 37307, "s": 37254, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 37331, "s": 37307, "text": "Find the Missing Number" } ]
Fermat's Factorization method for large numbers - GeeksforGeeks
17 Apr, 2020 Given a large number N, the task is to divide this number into a product of two factors, using Fermat’s Factorisation method. Examples Input: N = 105327569Output: 10223, 10303 Input: N = 249803Output: 23, 10861 Fermat Factorization: Fermat’s Factorization method is based on the representation of an odd integer as the difference of two squares.For an integer N, we want a and b such as: N = a2 - b2 = (a+b)(a-b) where (a+b) and (a-b) are the factors of the number N. Approach: Get the number as an object of BigInteger classFind the square root of N.It is guaranteed that the value of a is greater than sqrt(N) and value of b less than sqrt(N).Take the value of sqrt(n) as a and increment the number until and unless a number b is found such that N – a^2 is a perfect square. Get the number as an object of BigInteger class Find the square root of N. It is guaranteed that the value of a is greater than sqrt(N) and value of b less than sqrt(N). Take the value of sqrt(n) as a and increment the number until and unless a number b is found such that N – a^2 is a perfect square. Below is the implementation of the above approach: // Java program for Fermat's Factorization// method for large numbers import java.math.*;import java.util.*; class Solution { // Function to find the Floor // of square root of a number public static BigInteger sqrtF(BigInteger x) throws IllegalArgumentException { // if x is less than 0 if (x.compareTo(BigInteger.ZERO) < 0) { throw new IllegalArgumentException( "Negative argument."); } // if x==0 or x==1 if (x.equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)) { return x; } BigInteger two = BigInteger.valueOf(2L); BigInteger y; // run a loop y = x.divide(two); while (y.compareTo(x.divide(y)) > 0) y = ((x.divide(y)).add(y)) .divide(two); return y; } // function to find the Ceil // of square root of a number public static BigInteger sqrtC(BigInteger x) throws IllegalArgumentException { BigInteger y = sqrtF(x); if (x.compareTo(y.multiply(y)) == 0) { return y; } else { return y.add(BigInteger.ONE); } } // Fermat factorisation static String FermatFactors(BigInteger n) { // constants BigInteger ONE = new BigInteger("1"); BigInteger ZERO = new BigInteger("0"); BigInteger TWO = new BigInteger("2"); // if n%2 ==0 then return the factors if (n.mod(TWO).equals(ZERO)) { return n.divide(TWO) .toString() + ", 2"; } // find the square root BigInteger a = sqrtC(n); // if the number is a perfect square if (a.multiply(a).equals(n)) { return a.toString() + ", " + a.toString(); } // else perform factorisation BigInteger b; while (true) { BigInteger b1 = a.multiply(a) .subtract(n); b = sqrtF(b1); if (b.multiply(b).equals(b1)) break; else a = a.add(ONE); } return a.subtract(b).toString() + ", " + a.add(b).toString(); } // Driver code public static void main(String args[]) { String N = "105327569"; System.out.println( FermatFactors( new BigInteger(N))); }} 10223, 10303 Performance Analysis: Time Complexity: O(sqrt(N)) Space Complexity: O(1) factor Java-BigInteger large-numbers Java Programs Mathematical Write From Home Java-BigInteger Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Iterate HashMap in Java? Iterate through List in Java Factory method design pattern in Java Java program to count the occurrence of each character in a string using Hashmap Java Program to Remove Duplicate Elements From the Array 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": 25985, "s": 25957, "text": "\n17 Apr, 2020" }, { "code": null, "e": 26111, "s": 25985, "text": "Given a large number N, the task is to divide this number into a product of two factors, using Fermat’s Factorisation method." }, { "code": null, "e": 26120, "s": 26111, "text": "Examples" }, { "code": null, "e": 26161, "s": 26120, "text": "Input: N = 105327569Output: 10223, 10303" }, { "code": null, "e": 26196, "s": 26161, "text": "Input: N = 249803Output: 23, 10861" }, { "code": null, "e": 26373, "s": 26196, "text": "Fermat Factorization: Fermat’s Factorization method is based on the representation of an odd integer as the difference of two squares.For an integer N, we want a and b such as:" }, { "code": null, "e": 26457, "s": 26373, "text": "N = a2 - b2 = (a+b)(a-b) \n\nwhere (a+b) and (a-b) are \nthe factors of the number N.\n" }, { "code": null, "e": 26467, "s": 26457, "text": "Approach:" }, { "code": null, "e": 26766, "s": 26467, "text": "Get the number as an object of BigInteger classFind the square root of N.It is guaranteed that the value of a is greater than sqrt(N) and value of b less than sqrt(N).Take the value of sqrt(n) as a and increment the number until and unless a number b is found such that N – a^2 is a perfect square." }, { "code": null, "e": 26814, "s": 26766, "text": "Get the number as an object of BigInteger class" }, { "code": null, "e": 26841, "s": 26814, "text": "Find the square root of N." }, { "code": null, "e": 26936, "s": 26841, "text": "It is guaranteed that the value of a is greater than sqrt(N) and value of b less than sqrt(N)." }, { "code": null, "e": 27068, "s": 26936, "text": "Take the value of sqrt(n) as a and increment the number until and unless a number b is found such that N – a^2 is a perfect square." }, { "code": null, "e": 27119, "s": 27068, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program for Fermat's Factorization// method for large numbers import java.math.*;import java.util.*; class Solution { // Function to find the Floor // of square root of a number public static BigInteger sqrtF(BigInteger x) throws IllegalArgumentException { // if x is less than 0 if (x.compareTo(BigInteger.ZERO) < 0) { throw new IllegalArgumentException( \"Negative argument.\"); } // if x==0 or x==1 if (x.equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)) { return x; } BigInteger two = BigInteger.valueOf(2L); BigInteger y; // run a loop y = x.divide(two); while (y.compareTo(x.divide(y)) > 0) y = ((x.divide(y)).add(y)) .divide(two); return y; } // function to find the Ceil // of square root of a number public static BigInteger sqrtC(BigInteger x) throws IllegalArgumentException { BigInteger y = sqrtF(x); if (x.compareTo(y.multiply(y)) == 0) { return y; } else { return y.add(BigInteger.ONE); } } // Fermat factorisation static String FermatFactors(BigInteger n) { // constants BigInteger ONE = new BigInteger(\"1\"); BigInteger ZERO = new BigInteger(\"0\"); BigInteger TWO = new BigInteger(\"2\"); // if n%2 ==0 then return the factors if (n.mod(TWO).equals(ZERO)) { return n.divide(TWO) .toString() + \", 2\"; } // find the square root BigInteger a = sqrtC(n); // if the number is a perfect square if (a.multiply(a).equals(n)) { return a.toString() + \", \" + a.toString(); } // else perform factorisation BigInteger b; while (true) { BigInteger b1 = a.multiply(a) .subtract(n); b = sqrtF(b1); if (b.multiply(b).equals(b1)) break; else a = a.add(ONE); } return a.subtract(b).toString() + \", \" + a.add(b).toString(); } // Driver code public static void main(String args[]) { String N = \"105327569\"; System.out.println( FermatFactors( new BigInteger(N))); }}", "e": 29566, "s": 27119, "text": null }, { "code": null, "e": 29580, "s": 29566, "text": "10223, 10303\n" }, { "code": null, "e": 29602, "s": 29580, "text": "Performance Analysis:" }, { "code": null, "e": 29630, "s": 29602, "text": "Time Complexity: O(sqrt(N))" }, { "code": null, "e": 29653, "s": 29630, "text": "Space Complexity: O(1)" }, { "code": null, "e": 29660, "s": 29653, "text": "factor" }, { "code": null, "e": 29676, "s": 29660, "text": "Java-BigInteger" }, { "code": null, "e": 29690, "s": 29676, "text": "large-numbers" }, { "code": null, "e": 29704, "s": 29690, "text": "Java Programs" }, { "code": null, "e": 29717, "s": 29704, "text": "Mathematical" }, { "code": null, "e": 29733, "s": 29717, "text": "Write From Home" }, { "code": null, "e": 29749, "s": 29733, "text": "Java-BigInteger" }, { "code": null, "e": 29762, "s": 29749, "text": "Mathematical" }, { "code": null, "e": 29860, "s": 29762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29892, "s": 29860, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 29921, "s": 29892, "text": "Iterate through List in Java" }, { "code": null, "e": 29959, "s": 29921, "text": "Factory method design pattern in Java" }, { "code": null, "e": 30040, "s": 29959, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 30097, "s": 30040, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 30127, "s": 30097, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30187, "s": 30127, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30202, "s": 30187, "text": "C++ Data Types" }, { "code": null, "e": 30245, "s": 30202, "text": "Set in C++ Standard Template Library (STL)" } ]
Largest Even and Odd N-digit numbers - GeeksforGeeks
25 Mar, 2021 Given an integer N, the task is to find the largest even and odd N-digit numbers.Examples: Input: N = 4 Output: Even = 9998 Odd = 9999Input: N = 2 Output: Even = 98 Odd = 99 Approach: Largest N-digit even number will be (10n) – 2 because the series for different values of N will be 8, 98, 998, 9998, ..... Similarly, largest N-digit odd number will be (10n) – 1 for the series 9, 99, 999, 9999, ..... Below is the implementation of the above approach: C++ Java C# Python3 PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the largest n-digit// even and odd numbersvoid findNumbers(int n){ int odd = pow(10, n) - 1; int even = odd - 1; cout << "Even = " << even << endl; cout << "Odd = " << odd;} // Driver codeint main(){ int n = 4; findNumbers(n); return 0;} // Java implementation of the approachclass GFG { // Function to print the largest n-digit // even and odd numbers static void findNumbers(int n) { int odd = (int)Math.pow(10, n) - 1; int even = odd - 1; System.out.println("Even = " + even); System.out.print("Odd = " + odd); } // Driver code public static void main(String args[]) { int n = 4; findNumbers(n); }} // C# implementation of the approachusing System;class GFG { // Function to print the largest n-digit // even and odd numbers static void findNumbers(int n) { int odd = (int)Math.Pow(10, n) - 1; int even = odd - 1; Console.WriteLine("Even = " + even); Console.Write("Odd = " + odd); } // Driver code public static void Main() { int n = 4; findNumbers(n); }} # Python3 implementation of the approach # Function to print the largest n-digit# even and odd numbersdef findNumbers(n): odd = pow(10, n) - 1 even = odd - 1 print("Even = ", even) print("Odd = ", odd) # Driver coden = 4findNumbers(n) # This code is contributed by ihritik <?php// PHP implementation of the approach // Function to print the largest n-digit// even and odd numbersfunction findNumbers($n){ $odd = pow(10, $n) - 1; $even = $odd - 1; echo "Even = $even \n"; echo "Odd = $odd";} // Driver code$n = 4 ;findNumbers($n); // This code is contributed by ihritik?> <script> // Javascript implementation of the approach // Function to print the largest n-digit // even and odd numbers function findNumbers(n) { var odd = Math.pow(10, n) - 1; var even = odd - 1; document.write("Even = " + even+"<br>"); document.write("Odd = " + odd); } // Driver code var n = 4; findNumbers(n); // This code is contributed by rrrtnx. </script> Even = 9998 Odd = 9999 ihritik rrrtnx number-theory school-programming Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25961, "s": 25933, "text": "\n25 Mar, 2021" }, { "code": null, "e": 26054, "s": 25961, "text": "Given an integer N, the task is to find the largest even and odd N-digit numbers.Examples: " }, { "code": null, "e": 26139, "s": 26054, "text": "Input: N = 4 Output: Even = 9998 Odd = 9999Input: N = 2 Output: Even = 98 Odd = 99 " }, { "code": null, "e": 26153, "s": 26141, "text": "Approach: " }, { "code": null, "e": 26276, "s": 26153, "text": "Largest N-digit even number will be (10n) – 2 because the series for different values of N will be 8, 98, 998, 9998, ....." }, { "code": null, "e": 26371, "s": 26276, "text": "Similarly, largest N-digit odd number will be (10n) – 1 for the series 9, 99, 999, 9999, ....." }, { "code": null, "e": 26423, "s": 26371, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26427, "s": 26423, "text": "C++" }, { "code": null, "e": 26432, "s": 26427, "text": "Java" }, { "code": null, "e": 26435, "s": 26432, "text": "C#" }, { "code": null, "e": 26443, "s": 26435, "text": "Python3" }, { "code": null, "e": 26447, "s": 26443, "text": "PHP" }, { "code": null, "e": 26458, "s": 26447, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the largest n-digit// even and odd numbersvoid findNumbers(int n){ int odd = pow(10, n) - 1; int even = odd - 1; cout << \"Even = \" << even << endl; cout << \"Odd = \" << odd;} // Driver codeint main(){ int n = 4; findNumbers(n); return 0;}", "e": 26821, "s": 26458, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to print the largest n-digit // even and odd numbers static void findNumbers(int n) { int odd = (int)Math.pow(10, n) - 1; int even = odd - 1; System.out.println(\"Even = \" + even); System.out.print(\"Odd = \" + odd); } // Driver code public static void main(String args[]) { int n = 4; findNumbers(n); }}", "e": 27256, "s": 26821, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG { // Function to print the largest n-digit // even and odd numbers static void findNumbers(int n) { int odd = (int)Math.Pow(10, n) - 1; int even = odd - 1; Console.WriteLine(\"Even = \" + even); Console.Write(\"Odd = \" + odd); } // Driver code public static void Main() { int n = 4; findNumbers(n); }}", "e": 27685, "s": 27256, "text": null }, { "code": "# Python3 implementation of the approach # Function to print the largest n-digit# even and odd numbersdef findNumbers(n): odd = pow(10, n) - 1 even = odd - 1 print(\"Even = \", even) print(\"Odd = \", odd) # Driver coden = 4findNumbers(n) # This code is contributed by ihritik", "e": 27971, "s": 27685, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print the largest n-digit// even and odd numbersfunction findNumbers($n){ $odd = pow(10, $n) - 1; $even = $odd - 1; echo \"Even = $even \\n\"; echo \"Odd = $odd\";} // Driver code$n = 4 ;findNumbers($n); // This code is contributed by ihritik?>", "e": 28281, "s": 27971, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print the largest n-digit // even and odd numbers function findNumbers(n) { var odd = Math.pow(10, n) - 1; var even = odd - 1; document.write(\"Even = \" + even+\"<br>\"); document.write(\"Odd = \" + odd); } // Driver code var n = 4; findNumbers(n); // This code is contributed by rrrtnx. </script>", "e": 28704, "s": 28281, "text": null }, { "code": null, "e": 28727, "s": 28704, "text": "Even = 9998\nOdd = 9999" }, { "code": null, "e": 28737, "s": 28729, "text": "ihritik" }, { "code": null, "e": 28744, "s": 28737, "text": "rrrtnx" }, { "code": null, "e": 28758, "s": 28744, "text": "number-theory" }, { "code": null, "e": 28777, "s": 28758, "text": "school-programming" }, { "code": null, "e": 28790, "s": 28777, "text": "Mathematical" }, { "code": null, "e": 28804, "s": 28790, "text": "number-theory" }, { "code": null, "e": 28817, "s": 28804, "text": "Mathematical" }, { "code": null, "e": 28915, "s": 28817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28959, "s": 28915, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29001, "s": 28959, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 29032, "s": 29001, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29103, "s": 29032, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 29128, "s": 29103, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29160, "s": 29128, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29193, "s": 29160, "text": "Program to multiply two matrices" }, { "code": null, "e": 29239, "s": 29193, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 29283, "s": 29239, "text": "Generate all permutation of a set in Python" } ]
Page Faults in LFU | Implementation - GeeksforGeeks
02 Jun, 2021 Overview : In this, it is using the concept of paging for memory management, a page replacement algorithm is needed to decide which page needs to be replaced when the new page comes in. Whenever a new page is referred to and is not present in memory, the page fault occurs and the Operating System replaces one of the existing pages with a newly needed page. LFU is one such page replacement policy in which the least frequently used pages are replaced. If the frequency of pages is the same, then the page that has arrived first is replaced first. Example : Given a sequence of pages in an array of pages[] of length N and memory capacity C, find the number of page faults using the Least Frequently Used (LFU) Algorithm. Example-1 : Input : N = 7, C = 3 pages = { 1, 2, 3, 4, 2, 1, 5 } Output : Page Faults = 6 Page Hits = 1 Explanation : Capacity is 3, thus, we can store maximum 3 pages at a time. Page 1 is required, since it is not present, it is a page fault : page fault = 1 Page 2 is required, since it is not present, it is a page fault : page fault = 1 + 1 = 2 Page 3 is required, since it is not present, it is a page fault : page fault = 2 + 1 = 3 Page 4 is required, since it is not present, it replaces LFU page 1 : page fault = 3 + 1 = 4 Page 2 is required, since it is present, it is not a page fault : page fault = 4 + 0 = 4 Page 1 is required, since it is not present, it replaces LFU page 3 : page fault = 4 + 1 = 5 Page 5 is required, since it is not present, it replaces LFU page 4 : page fault = 5 + 1 = 6 Example-2 : Input : N = 9, C = 4 pages = { 5, 0, 1, 3, 2, 4, 1, 0, 5 } Output : Page Faults = 8 Page Hits = 1 Explanation : Capacity is 4, thus, we can store maximum 4 pages at a time. Page 5 is required, since it is not present, it is a page fault : page fault = 1 Page 0 is required, since it is not present, it is a page fault : page fault = 1 + 1 = 2 Page 1 is required, since it is not present, it is a page fault : page fault = 2 + 1 = 3 Page 3 is required, since it is not present, it is a page fault : page fault = 3 + 1 = 4 Page 2 is required, since it is not present, it replaces LFU page 5 : page fault = 4 + 1 = 5 Page 4 is required, since it is not present, it replaces LFU page 0 : page fault = 5 + 1 = 6 Page 1 is required, since it is present, it is not a page fault : page fault = 6 + 0 = 6 Page 0 is required, since it is not present, it replaces LRU page 3 : page fault = 6 + 1 = 7 Page 5 is required, since it is not present, it replaces LFU page 2 : page fault = 7 + 1 = 8 Algorithm : Step-1 : Initialize count as 0. Step-2 : Create a vector / array of size equal to memory capacity. Create a map to store frequency of pages Step-3 : Traverse elements of pages[] Step-4 : In each traversal: if(element is present in memory): remove the element and push the element at the end increase its frequency else: if(memory is full) remove the first element and decrease frequency of 1st element Increment count push the element at the end and increase its frequency Compare frequency with other pages starting from the 2nd last page Sort the pages based on their frequency and time at which they arrive if frequency is same, then, the page arriving first must be placed first Following is the implementation of the above algorithm. C++ // C++ program to illustrate// page faults in LFU #include <bits/stdc++.h>using namespace std; /* Counts no. of page faults */int pageFaults(int n, int c, int pages[]){ // Initialise count to 0 int count = 0; // To store elements in memory of size c vector<int> v; // To store frequency of pages unordered_map<int, int> mp; int i; for (i = 0; i <= n - 1; i++) { // Find if element is present in memory or not auto it = find(v.begin(), v.end(), pages[i]); // If element is not present if (it == v.end()) { // If memory is full if (v.size() == c) { // Decrease the frequency mp[v[0]]--; // Remove the first element as // It is least frequently used v.erase(v.begin()); } // Add the element at the end of memory v.push_back(pages[i]); // Increase its frequency mp[pages[i]]++; // Increment the count count++; } else { // If element is present // Remove the element // And add it at the end // Increase its frequency mp[pages[i]]++; v.erase(it); v.push_back(pages[i]); } // Compare frequency with other pages // starting from the 2nd last page int k = v.size() - 2; // Sort the pages based on their frequency // And time at which they arrive // if frequency is same // then, the page arriving first must be placed first while (mp[v[k]] > mp[v[k + 1]] && k > -1) { swap(v[k + 1], v[k]); k--; } } // Return total page faults return count;} /* Driver program to test pageFaults function*/int main(){ int pages[] = { 1, 2, 3, 4, 2, 1, 5 }; int n = 7, c = 3; cout << "Page Faults = " << pageFaults(n, c, pages) << endl; cout << "Page Hits = " << n - pageFaults(n, c, pages); return 0;} // This code is contributed by rajsanghavi9. Page Faults = 6 Page Hits = 1 GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Preemptive and Non-Preemptive Scheduling Difference between Clustered and Non-clustered index Phases of a Compiler Introduction of Process Synchronization Banker's Algorithm in Operating System Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Introduction of Deadlock in Operating System Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 25651, "s": 25623, "text": "\n02 Jun, 2021" }, { "code": null, "e": 25662, "s": 25651, "text": "Overview :" }, { "code": null, "e": 26200, "s": 25662, "text": "In this, it is using the concept of paging for memory management, a page replacement algorithm is needed to decide which page needs to be replaced when the new page comes in. Whenever a new page is referred to and is not present in memory, the page fault occurs and the Operating System replaces one of the existing pages with a newly needed page. LFU is one such page replacement policy in which the least frequently used pages are replaced. If the frequency of pages is the same, then the page that has arrived first is replaced first." }, { "code": null, "e": 26210, "s": 26200, "text": "Example :" }, { "code": null, "e": 26374, "s": 26210, "text": "Given a sequence of pages in an array of pages[] of length N and memory capacity C, find the number of page faults using the Least Frequently Used (LFU) Algorithm." }, { "code": null, "e": 26386, "s": 26374, "text": "Example-1 :" }, { "code": null, "e": 26478, "s": 26386, "text": "Input : N = 7, C = 3\npages = { 1, 2, 3, 4, 2, 1, 5 }\nOutput :\nPage Faults = 6\nPage Hits = 1" }, { "code": null, "e": 26492, "s": 26478, "text": "Explanation :" }, { "code": null, "e": 26553, "s": 26492, "text": "Capacity is 3, thus, we can store maximum 3 pages at a time." }, { "code": null, "e": 26600, "s": 26553, "text": "Page 1 is required, since it is not present, " }, { "code": null, "e": 26636, "s": 26600, "text": "it is a page fault : page fault = 1" }, { "code": null, "e": 26683, "s": 26636, "text": "Page 2 is required, since it is not present, " }, { "code": null, "e": 26727, "s": 26683, "text": "it is a page fault : page fault = 1 + 1 = 2" }, { "code": null, "e": 26774, "s": 26727, "text": "Page 3 is required, since it is not present, " }, { "code": null, "e": 26818, "s": 26774, "text": "it is a page fault : page fault = 2 + 1 = 3" }, { "code": null, "e": 26865, "s": 26818, "text": "Page 4 is required, since it is not present, " }, { "code": null, "e": 26913, "s": 26865, "text": "it replaces LFU page 1 : page fault = 3 + 1 = 4" }, { "code": null, "e": 26956, "s": 26913, "text": "Page 2 is required, since it is present, " }, { "code": null, "e": 27004, "s": 26956, "text": "it is not a page fault : page fault = 4 + 0 = 4" }, { "code": null, "e": 27051, "s": 27004, "text": "Page 1 is required, since it is not present, " }, { "code": null, "e": 27099, "s": 27051, "text": "it replaces LFU page 3 : page fault = 4 + 1 = 5" }, { "code": null, "e": 27146, "s": 27099, "text": "Page 5 is required, since it is not present, " }, { "code": null, "e": 27194, "s": 27146, "text": "it replaces LFU page 4 : page fault = 5 + 1 = 6" }, { "code": null, "e": 27206, "s": 27194, "text": "Example-2 :" }, { "code": null, "e": 27304, "s": 27206, "text": "Input : N = 9, C = 4\npages = { 5, 0, 1, 3, 2, 4, 1, 0, 5 }\nOutput :\nPage Faults = 8\nPage Hits = 1" }, { "code": null, "e": 27318, "s": 27304, "text": "Explanation :" }, { "code": null, "e": 27379, "s": 27318, "text": "Capacity is 4, thus, we can store maximum 4 pages at a time." }, { "code": null, "e": 27426, "s": 27379, "text": "Page 5 is required, since it is not present, " }, { "code": null, "e": 27462, "s": 27426, "text": "it is a page fault : page fault = 1" }, { "code": null, "e": 27509, "s": 27462, "text": "Page 0 is required, since it is not present, " }, { "code": null, "e": 27553, "s": 27509, "text": "it is a page fault : page fault = 1 + 1 = 2" }, { "code": null, "e": 27600, "s": 27553, "text": "Page 1 is required, since it is not present, " }, { "code": null, "e": 27644, "s": 27600, "text": "it is a page fault : page fault = 2 + 1 = 3" }, { "code": null, "e": 27691, "s": 27644, "text": "Page 3 is required, since it is not present, " }, { "code": null, "e": 27735, "s": 27691, "text": "it is a page fault : page fault = 3 + 1 = 4" }, { "code": null, "e": 27782, "s": 27735, "text": "Page 2 is required, since it is not present, " }, { "code": null, "e": 27830, "s": 27782, "text": "it replaces LFU page 5 : page fault = 4 + 1 = 5" }, { "code": null, "e": 27877, "s": 27830, "text": "Page 4 is required, since it is not present, " }, { "code": null, "e": 27925, "s": 27877, "text": "it replaces LFU page 0 : page fault = 5 + 1 = 6" }, { "code": null, "e": 27968, "s": 27925, "text": "Page 1 is required, since it is present, " }, { "code": null, "e": 28016, "s": 27968, "text": "it is not a page fault : page fault = 6 + 0 = 6" }, { "code": null, "e": 28063, "s": 28016, "text": "Page 0 is required, since it is not present, " }, { "code": null, "e": 28111, "s": 28063, "text": "it replaces LRU page 3 : page fault = 6 + 1 = 7" }, { "code": null, "e": 28158, "s": 28111, "text": "Page 5 is required, since it is not present, " }, { "code": null, "e": 28206, "s": 28158, "text": "it replaces LFU page 2 : page fault = 7 + 1 = 8" }, { "code": null, "e": 28218, "s": 28206, "text": "Algorithm :" }, { "code": null, "e": 29053, "s": 28218, "text": "Step-1 : Initialize count as 0.\nStep-2 : Create a vector / array of size equal to memory capacity.\n Create a map to store frequency of pages \nStep-3 : Traverse elements of pages[]\nStep-4 : In each traversal:\n if(element is present in memory):\n remove the element and push the element at the end \n increase its frequency\n else:\n if(memory is full) \n remove the first element and decrease frequency of 1st element\n Increment count \n push the element at the end and increase its frequency\n Compare frequency with other pages starting from the 2nd last page \n Sort the pages based on their frequency and time at which they arrive\n if frequency is same, then, the page arriving first must be placed first " }, { "code": null, "e": 29109, "s": 29053, "text": "Following is the implementation of the above algorithm." }, { "code": null, "e": 29113, "s": 29109, "text": "C++" }, { "code": "// C++ program to illustrate// page faults in LFU #include <bits/stdc++.h>using namespace std; /* Counts no. of page faults */int pageFaults(int n, int c, int pages[]){ // Initialise count to 0 int count = 0; // To store elements in memory of size c vector<int> v; // To store frequency of pages unordered_map<int, int> mp; int i; for (i = 0; i <= n - 1; i++) { // Find if element is present in memory or not auto it = find(v.begin(), v.end(), pages[i]); // If element is not present if (it == v.end()) { // If memory is full if (v.size() == c) { // Decrease the frequency mp[v[0]]--; // Remove the first element as // It is least frequently used v.erase(v.begin()); } // Add the element at the end of memory v.push_back(pages[i]); // Increase its frequency mp[pages[i]]++; // Increment the count count++; } else { // If element is present // Remove the element // And add it at the end // Increase its frequency mp[pages[i]]++; v.erase(it); v.push_back(pages[i]); } // Compare frequency with other pages // starting from the 2nd last page int k = v.size() - 2; // Sort the pages based on their frequency // And time at which they arrive // if frequency is same // then, the page arriving first must be placed first while (mp[v[k]] > mp[v[k + 1]] && k > -1) { swap(v[k + 1], v[k]); k--; } } // Return total page faults return count;} /* Driver program to test pageFaults function*/int main(){ int pages[] = { 1, 2, 3, 4, 2, 1, 5 }; int n = 7, c = 3; cout << \"Page Faults = \" << pageFaults(n, c, pages) << endl; cout << \"Page Hits = \" << n - pageFaults(n, c, pages); return 0;} // This code is contributed by rajsanghavi9.", "e": 31228, "s": 29113, "text": null }, { "code": null, "e": 31258, "s": 31228, "text": "Page Faults = 6\nPage Hits = 1" }, { "code": null, "e": 31266, "s": 31258, "text": "GATE CS" }, { "code": null, "e": 31284, "s": 31266, "text": "Operating Systems" }, { "code": null, "e": 31302, "s": 31284, "text": "Operating Systems" }, { "code": null, "e": 31400, "s": 31302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31434, "s": 31400, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 31475, "s": 31434, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 31528, "s": 31475, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 31549, "s": 31528, "text": "Phases of a Compiler" }, { "code": null, "e": 31589, "s": 31549, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 31628, "s": 31589, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 31668, "s": 31628, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 31695, "s": 31668, "text": "Paging in Operating System" }, { "code": null, "e": 31740, "s": 31695, "text": "Introduction of Deadlock in Operating System" } ]
MongoDB - $slice Modifier - GeeksforGeeks
10 May, 2020 MongoDB provides different types of array update operators to update the values of the array fields in the documents and $slice modifier is one of them. This modifier is used to limit the number of array items during a $push operation. Syntax: { $push: { <field>: { $each: [ <value1>, <value2>, ... ], $slice: <number> } } } If the value of number is zero, then this modifier will update the array field to an empty array. If the value of number is negative, then this modifier will update the array field to contain only the last number items. If the value of number is positive, then this modifier will update the array field to contain only the first number items. $slice modifier must appear with $each modifier in the $push operator. You are allowed to pass an empty array in the $each modifier which help $slice modifier to show its effect. If you use the $slice modifier without $each modifier, then you will get an error. The order in which the modifiers appear in $push operation is immaterial. In the following examples, we are working with: Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs. In this example, we are adding new items in the language field and then use $slice modifier to trim the array to the last four items. db.contributor.update({name: "Suman"}, {$push: {language: { $each: ["SQL", "JS++"], $slice: -4}}}) In this example, we are adding new items in the language field and then use $slice modifier to trim the array to the first five items. db.contributor.update({name: "Rohit"}, {$push: {language: { $each: ["R Language", "JS++"], $slice: 5}}}) In this example, we are updating the array of the language field by triming the array to the last three items. db.contributor.update({name: "Rohit"}, {$push: {language: { $each: [], $slice: -3}}}) In this example, we are using the $slice modifier with other modifiers like $each and $sort with $push operator. db.contributor.update({name: "Rohit"}, {$push: { language: { $each: ["C++", "Kotlin"], $sort: 1, $slice: 4}}}) Here, The $each modifier is used to add multiple documents to the language array. The $sort modifier is used to sort all the items of the modified language array in ascending. The $slice modifier is used to keep only the first four sorted items of the language array. MongoDB MongoDB-modifier MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB - sort() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB insertMany() Method - db.Collection.insertMany() MongoDB - Update() Method MongoDB Cursor MongoDB updateMany() Method - db.Collection.updateMany()
[ { "code": null, "e": 25517, "s": 25489, "text": "\n10 May, 2020" }, { "code": null, "e": 25753, "s": 25517, "text": "MongoDB provides different types of array update operators to update the values of the array fields in the documents and $slice modifier is one of them. This modifier is used to limit the number of array items during a $push operation." }, { "code": null, "e": 25761, "s": 25753, "text": "Syntax:" }, { "code": null, "e": 25870, "s": 25761, "text": "{\n $push: {\n <field>: {\n $each: [ <value1>, <value2>, ... ],\n $slice: <number>\n }\n }\n}" }, { "code": null, "e": 25968, "s": 25870, "text": "If the value of number is zero, then this modifier will update the array field to an empty array." }, { "code": null, "e": 26090, "s": 25968, "text": "If the value of number is negative, then this modifier will update the array field to contain only the last number items." }, { "code": null, "e": 26213, "s": 26090, "text": "If the value of number is positive, then this modifier will update the array field to contain only the first number items." }, { "code": null, "e": 26475, "s": 26213, "text": "$slice modifier must appear with $each modifier in the $push operator. You are allowed to pass an empty array in the $each modifier which help $slice modifier to show its effect. If you use the $slice modifier without $each modifier, then you will get an error." }, { "code": null, "e": 26549, "s": 26475, "text": "The order in which the modifiers appear in $push operation is immaterial." }, { "code": null, "e": 26597, "s": 26549, "text": "In the following examples, we are working with:" }, { "code": null, "e": 26745, "s": 26597, "text": "Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs." }, { "code": null, "e": 26879, "s": 26745, "text": "In this example, we are adding new items in the language field and then use $slice modifier to trim the array to the last four items." }, { "code": "db.contributor.update({name: \"Suman\"}, {$push: {language: { $each: [\"SQL\", \"JS++\"], $slice: -4}}})", "e": 27022, "s": 26879, "text": null }, { "code": null, "e": 27157, "s": 27022, "text": "In this example, we are adding new items in the language field and then use $slice modifier to trim the array to the first five items." }, { "code": "db.contributor.update({name: \"Rohit\"}, {$push: {language: { $each: [\"R Language\", \"JS++\"], $slice: 5}}})", "e": 27306, "s": 27157, "text": null }, { "code": null, "e": 27417, "s": 27306, "text": "In this example, we are updating the array of the language field by triming the array to the last three items." }, { "code": "db.contributor.update({name: \"Rohit\"}, {$push: {language: { $each: [], $slice: -3}}})", "e": 27548, "s": 27417, "text": null }, { "code": null, "e": 27661, "s": 27548, "text": "In this example, we are using the $slice modifier with other modifiers like $each and $sort with $push operator." }, { "code": "db.contributor.update({name: \"Rohit\"}, {$push: { language: { $each: [\"C++\", \"Kotlin\"], $sort: 1, $slice: 4}}})", "e": 27816, "s": 27661, "text": null }, { "code": null, "e": 27822, "s": 27816, "text": "Here," }, { "code": null, "e": 27898, "s": 27822, "text": "The $each modifier is used to add multiple documents to the language array." }, { "code": null, "e": 27992, "s": 27898, "text": "The $sort modifier is used to sort all the items of the modified language array in ascending." }, { "code": null, "e": 28084, "s": 27992, "text": "The $slice modifier is used to keep only the first four sorted items of the language array." }, { "code": null, "e": 28092, "s": 28084, "text": "MongoDB" }, { "code": null, "e": 28109, "s": 28092, "text": "MongoDB-modifier" }, { "code": null, "e": 28117, "s": 28109, "text": "MongoDB" }, { "code": null, "e": 28215, "s": 28117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28253, "s": 28215, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 28278, "s": 28253, "text": "MongoDB - limit() Method" }, { "code": null, "e": 28305, "s": 28278, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 28341, "s": 28305, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 28365, "s": 28341, "text": "MongoDB - sort() Method" }, { "code": null, "e": 28420, "s": 28365, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 28477, "s": 28420, "text": "MongoDB insertMany() Method - db.Collection.insertMany()" }, { "code": null, "e": 28503, "s": 28477, "text": "MongoDB - Update() Method" }, { "code": null, "e": 28518, "s": 28503, "text": "MongoDB Cursor" } ]
Python | Numpy matrix.std() - GeeksforGeeks
20 May, 2019 With the help of matrix.std() method, we are able to find the standard deviation a matrix by using the same method. Syntax : matrix.std()Return : Return standard deviation of a matrix Example #1 :In this example we are able to find the standard deviation of a matrix by using matrix.std() method. # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]') # applying matrix.std() methodgeek = gfg.std() print(geek) 4.18330013267 Example #2 : # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]') # applying matrix.std() methodgeek = gfg.std() print(geek) 3.3993463424 Python numpy-Matrix Function Python-numpy 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26139, "s": 26111, "text": "\n20 May, 2019" }, { "code": null, "e": 26255, "s": 26139, "text": "With the help of matrix.std() method, we are able to find the standard deviation a matrix by using the same method." }, { "code": null, "e": 26323, "s": 26255, "text": "Syntax : matrix.std()Return : Return standard deviation of a matrix" }, { "code": null, "e": 26436, "s": 26323, "text": "Example #1 :In this example we are able to find the standard deviation of a matrix by using matrix.std() method." }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]') # applying matrix.std() methodgeek = gfg.std() print(geek)", "e": 26636, "s": 26436, "text": null }, { "code": null, "e": 26651, "s": 26636, "text": "4.18330013267\n" }, { "code": null, "e": 26664, "s": 26651, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]') # applying matrix.std() methodgeek = gfg.std() print(geek)", "e": 26879, "s": 26664, "text": null }, { "code": null, "e": 26893, "s": 26879, "text": "3.3993463424\n" }, { "code": null, "e": 26922, "s": 26893, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 26935, "s": 26922, "text": "Python-numpy" }, { "code": null, "e": 26942, "s": 26935, "text": "Python" }, { "code": null, "e": 27040, "s": 26942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27058, "s": 27040, "text": "Python Dictionary" }, { "code": null, "e": 27093, "s": 27058, "text": "Read a file line by line in Python" }, { "code": null, "e": 27125, "s": 27093, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27147, "s": 27125, "text": "Enumerate() in Python" }, { "code": null, "e": 27189, "s": 27147, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27219, "s": 27189, "text": "Iterate over a list in Python" }, { "code": null, "e": 27245, "s": 27219, "text": "Python String | replace()" }, { "code": null, "e": 27274, "s": 27245, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27318, "s": 27274, "text": "Reading and Writing to text files in Python" } ]
HTML | <option> label Attribute - GeeksforGeeks
07 Aug, 2019 The HTML option label Attribute is used to specify the text value which represents the shorted label for option. The shortest version will be displayed in the drop-down list. Syntax: <option label="text"> Attribute Values: It contains single value text which specify the shorter version for an option. Below example illustrates the use of label attribute for an option element.Example: <!DOCTYPE html> <html> <head> <title> HTML option label attribute </title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML option label Attribute</h2> <select> <option>Choose an option</option> <option label="HTML">HTML Language</option> <option label="JAVA">JAVA Programming</option> <option label="C++">C++ Programming</option> <option label="PHP">PHP Programming</option> <option label="PERL">PERL Programming</option> </select> </body> </html> Output: Supported Browsers: The browsers supported by HTML <option> label attribute are listed below: Google Chrome Internet Explorer 8.0 Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes 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 ? REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 27179, "s": 27151, "text": "\n07 Aug, 2019" }, { "code": null, "e": 27354, "s": 27179, "text": "The HTML option label Attribute is used to specify the text value which represents the shorted label for option. The shortest version will be displayed in the drop-down list." }, { "code": null, "e": 27362, "s": 27354, "text": "Syntax:" }, { "code": null, "e": 27384, "s": 27362, "text": "<option label=\"text\">" }, { "code": null, "e": 27481, "s": 27384, "text": "Attribute Values: It contains single value text which specify the shorter version for an option." }, { "code": null, "e": 27565, "s": 27481, "text": "Below example illustrates the use of label attribute for an option element.Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML option label attribute </title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML option label Attribute</h2> <select> <option>Choose an option</option> <option label=\"HTML\">HTML Language</option> <option label=\"JAVA\">JAVA Programming</option> <option label=\"C++\">C++ Programming</option> <option label=\"PHP\">PHP Programming</option> <option label=\"PERL\">PERL Programming</option> </select> </body> </html> ", "e": 28256, "s": 27565, "text": null }, { "code": null, "e": 28264, "s": 28256, "text": "Output:" }, { "code": null, "e": 28358, "s": 28264, "text": "Supported Browsers: The browsers supported by HTML <option> label attribute are listed below:" }, { "code": null, "e": 28372, "s": 28358, "text": "Google Chrome" }, { "code": null, "e": 28394, "s": 28372, "text": "Internet Explorer 8.0" }, { "code": null, "e": 28401, "s": 28394, "text": "Safari" }, { "code": null, "e": 28407, "s": 28401, "text": "Opera" }, { "code": null, "e": 28544, "s": 28407, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28560, "s": 28544, "text": "HTML-Attributes" }, { "code": null, "e": 28565, "s": 28560, "text": "HTML" }, { "code": null, "e": 28582, "s": 28565, "text": "Web Technologies" }, { "code": null, "e": 28587, "s": 28582, "text": "HTML" }, { "code": null, "e": 28685, "s": 28587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28733, "s": 28685, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28757, "s": 28733, "text": "REST API (Introduction)" }, { "code": null, "e": 28807, "s": 28757, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28844, "s": 28807, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28908, "s": 28844, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28948, "s": 28908, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28981, "s": 28948, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29026, "s": 28981, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29069, "s": 29026, "text": "How to fetch data from an API in ReactJS ?" } ]
Pandas.set_option() function in Python - GeeksforGeeks
28 Jul, 2020 Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to set the value of a specified option. Syntax : pandas.set_option(pat, value) Parameters : pat : Regexp which should match a single option. value : New value of option. Returns : NoneRaises : OptionError if no such option exists Example 1 : Changing the number of rows to be displayed using display.max_rows. # importing the moduleimport pandas as pd # creating the DataFramedata = {"Number" : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "Alphabet" : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']}df = pd.DataFrame(data) print("Initial max_rows value : " + str(pd.options.display.max_rows)) # displaying the DataFramedisplay(df) # changing the max_rows valuepd.set_option("display.max_rows", 5) print("max_rows value after the change : " + str(pd.options.display.max_rows)) # displaying the DataFramedisplay(df) Output : Example 2 : Changing the number of columns to be displayed using display.max_columns. # importing the moduleimport pandas as pd # creating the DataFramedata = {"Number" : 1, "Name" : ["ABC"], "Subject" : ["Computer"], "Field" : ["BDA"], "Marks" : 70}df = pd.DataFrame(data) print("Initial max_columns value : " + str(pd.options.display.max_columns)) # displaying the DataFramedisplay(df) # changing the max_columns valuepd.set_option("display.max_columns", 3) print("max_columns value after the change : " + str(pd.options.display.max_columns)) # displaying the DataFramedisplay(df) Output : Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 25389, "s": 25361, "text": "\n28 Jul, 2020" }, { "code": null, "e": 25599, "s": 25389, "text": "Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to set the value of a specified option." }, { "code": null, "e": 25638, "s": 25599, "text": "Syntax : pandas.set_option(pat, value)" }, { "code": null, "e": 25651, "s": 25638, "text": "Parameters :" }, { "code": null, "e": 25700, "s": 25651, "text": "pat : Regexp which should match a single option." }, { "code": null, "e": 25729, "s": 25700, "text": "value : New value of option." }, { "code": null, "e": 25789, "s": 25729, "text": "Returns : NoneRaises : OptionError if no such option exists" }, { "code": null, "e": 25869, "s": 25789, "text": "Example 1 : Changing the number of rows to be displayed using display.max_rows." }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramedata = {\"Number\" : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], \"Alphabet\" : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']}df = pd.DataFrame(data) print(\"Initial max_rows value : \" + str(pd.options.display.max_rows)) # displaying the DataFramedisplay(df) # changing the max_rows valuepd.set_option(\"display.max_rows\", 5) print(\"max_rows value after the change : \" + str(pd.options.display.max_rows)) # displaying the DataFramedisplay(df)", "e": 26432, "s": 25869, "text": null }, { "code": null, "e": 26441, "s": 26432, "text": "Output :" }, { "code": null, "e": 26527, "s": 26441, "text": "Example 2 : Changing the number of columns to be displayed using display.max_columns." }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramedata = {\"Number\" : 1, \"Name\" : [\"ABC\"], \"Subject\" : [\"Computer\"], \"Field\" : [\"BDA\"], \"Marks\" : 70}df = pd.DataFrame(data) print(\"Initial max_columns value : \" + str(pd.options.display.max_columns)) # displaying the DataFramedisplay(df) # changing the max_columns valuepd.set_option(\"display.max_columns\", 3) print(\"max_columns value after the change : \" + str(pd.options.display.max_columns)) # displaying the DataFramedisplay(df)", "e": 27070, "s": 26527, "text": null }, { "code": null, "e": 27079, "s": 27070, "text": "Output :" }, { "code": null, "e": 27093, "s": 27079, "text": "Python-pandas" }, { "code": null, "e": 27100, "s": 27093, "text": "Python" }, { "code": null, "e": 27198, "s": 27100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27233, "s": 27198, "text": "Read a file line by line in Python" }, { "code": null, "e": 27265, "s": 27233, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27287, "s": 27265, "text": "Enumerate() in Python" }, { "code": null, "e": 27329, "s": 27287, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27359, "s": 27329, "text": "Iterate over a list in Python" }, { "code": null, "e": 27385, "s": 27359, "text": "Python String | replace()" }, { "code": null, "e": 27414, "s": 27385, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27458, "s": 27414, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27495, "s": 27458, "text": "Create a Pandas DataFrame from Lists" } ]
Implementing Non-contiguous Memory Management Techniques - GeeksforGeeks
14 Apr, 2020 Memory Management Techniques are basic techniques that are used in managing the memory in operating system. Memory Management Techniques are basically classified into two categories: (i) Contiguous (ii) Non-contiguous We have already discussed the implementation of contiguous in the article Implementation of Contiguous Memory Management Techniques. Here we will discuss the implementation of non-contiguous memory management techniques. Non-contiguous Memory Management Techniques:In this technique, memory is allotted in a non-continuous way to the processes. It has five types: Paging:Paging is a non-contiguous memory management technique that permits the physical address space of a process to be non–contiguous. Whenever the process is created paging will be applied on the process and page table will be created. Paging is related with respect to every process and every process will have its own page table. There is no external fragmentation in the paging. The internal fragmentation exists in the last page and internal fragmentation in paging is considered as P/2 where P is the page size. Multilevel Paging:Multilevel Paging is a non-contiguous memory management technique which contains two or more levels of page tables in a hierarchical manner.In the multilevel paging when the paging is applied on the page tables, the last page is called the first level page table. In multilevel paging, when the paging is applied on the page tables then all the page table will be stored in main memory. Inverted Paging:To avoid the overhead of maintaining page table process, the concept of Inverted Paging is implemented. In the inverted paging only one page table will be maintained for all the processes. The memory required to maintain the page tables of the processes will be less but searching time for corresponding page of a process will be more. Segmentation:Segmentation is a non-contiguous memory management technique in which the memory is divided into segments. Each process is allotted a segment. There are two types of segmentation: (i) Simple (ii) Virtual Segmented Paging:To avoid the overhead of bringing large size segment into memory the concept of segmented paging is implemented. IN the segmented paging, paging will be applied on the segment and instead of bringing the entire segment into memory, the pages of segment will be brought into memory. The number of entries in the page table of segment is same as the number of pages on the segment. Page size of segment is same as frame size of physical address space. GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Preemptive and Non-Preemptive Scheduling Difference between Clustered and Non-clustered index Phases of a Compiler Introduction of Process Synchronization Banker's Algorithm in Operating System Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Introduction of Deadlock in Operating System Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 25627, "s": 25599, "text": "\n14 Apr, 2020" }, { "code": null, "e": 25810, "s": 25627, "text": "Memory Management Techniques are basic techniques that are used in managing the memory in operating system. Memory Management Techniques are basically classified into two categories:" }, { "code": null, "e": 25846, "s": 25810, "text": "(i) Contiguous\n(ii) Non-contiguous " }, { "code": null, "e": 26067, "s": 25846, "text": "We have already discussed the implementation of contiguous in the article Implementation of Contiguous Memory Management Techniques. Here we will discuss the implementation of non-contiguous memory management techniques." }, { "code": null, "e": 26210, "s": 26067, "text": "Non-contiguous Memory Management Techniques:In this technique, memory is allotted in a non-continuous way to the processes. It has five types:" }, { "code": null, "e": 26545, "s": 26210, "text": "Paging:Paging is a non-contiguous memory management technique that permits the physical address space of a process to be non–contiguous. Whenever the process is created paging will be applied on the process and page table will be created. Paging is related with respect to every process and every process will have its own page table." }, { "code": null, "e": 26730, "s": 26545, "text": "There is no external fragmentation in the paging. The internal fragmentation exists in the last page and internal fragmentation in paging is considered as P/2 where P is the page size." }, { "code": null, "e": 27135, "s": 26730, "text": "Multilevel Paging:Multilevel Paging is a non-contiguous memory management technique which contains two or more levels of page tables in a hierarchical manner.In the multilevel paging when the paging is applied on the page tables, the last page is called the first level page table. In multilevel paging, when the paging is applied on the page tables then all the page table will be stored in main memory." }, { "code": null, "e": 27487, "s": 27135, "text": "Inverted Paging:To avoid the overhead of maintaining page table process, the concept of Inverted Paging is implemented. In the inverted paging only one page table will be maintained for all the processes. The memory required to maintain the page tables of the processes will be less but searching time for corresponding page of a process will be more." }, { "code": null, "e": 27680, "s": 27487, "text": "Segmentation:Segmentation is a non-contiguous memory management technique in which the memory is divided into segments. Each process is allotted a segment. There are two types of segmentation:" }, { "code": null, "e": 27705, "s": 27680, "text": "(i) Simple\n(ii) Virtual " }, { "code": null, "e": 28102, "s": 27705, "text": "Segmented Paging:To avoid the overhead of bringing large size segment into memory the concept of segmented paging is implemented. IN the segmented paging, paging will be applied on the segment and instead of bringing the entire segment into memory, the pages of segment will be brought into memory. The number of entries in the page table of segment is same as the number of pages on the segment." }, { "code": null, "e": 28172, "s": 28102, "text": "Page size of segment is same as frame size of physical address space." }, { "code": null, "e": 28180, "s": 28172, "text": "GATE CS" }, { "code": null, "e": 28198, "s": 28180, "text": "Operating Systems" }, { "code": null, "e": 28216, "s": 28198, "text": "Operating Systems" }, { "code": null, "e": 28314, "s": 28216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28348, "s": 28314, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 28389, "s": 28348, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 28442, "s": 28389, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 28463, "s": 28442, "text": "Phases of a Compiler" }, { "code": null, "e": 28503, "s": 28463, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 28542, "s": 28503, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 28582, "s": 28542, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 28609, "s": 28582, "text": "Paging in Operating System" }, { "code": null, "e": 28654, "s": 28609, "text": "Introduction of Deadlock in Operating System" } ]
Python Program to Compute Life Path Number - GeeksforGeeks
24 Jan, 2021 Given a String of date of format YYYYMMDD, our task is to compute the life path number. Life Path Number is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions. Examples: Input : test_str = “19970314” Output : 7 Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 3 = 3 [ month ] ; 1 + 4 = 5 [ day ]. 5 + 3 + 8 = 16 ; 1 + 6 = 7. Input : test_str = “19970104” Output : 4 Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 1 = 1 [ month ] ; 0 + 4 = 4 [ day ]. 4 + 1 + 8 = 13 ; 1 + 3 = 4. Method 1: Using loop The logic behind computing this is getting a summation of each digit and perform %10 at each step. This way result curlers to single digit if it goes to double-digit. Python3 # Python3 code to demonstrate working of# Life Path Number# Using loop # initializing stringtest_str = "19970314" # printing original stringprint("The original string is : " + str(test_str)) res = 0for num in test_str: res += int(num) # modulation in case of 2 digit number if res > 9: res = res % 10 + res // 10 # printing resultprint("Life Path Number : " + str(res)) Output: The original string is : 19970314 Life Path Number : 7 Method 2: Using recursion Similar way as above, the difference being the recursive function is used for repeated modulation in case of digit count greater than 1. Python3 # Python3 code to demonstrate working of# Life Path Number# Using recursion # initializing stringtest_str = "19970314" # printing original stringprint("The original string is : " + str(test_str)) # recursion function definitiondef lpn(num): return num if num < 10 else lpn(num // 10 + num % 10) # recursive function initial callres = lpn(int(test_str)) # printing resultprint("Life Path Number : " + str(res)) Output: The original string is : 19970314 Life Path Number : 7 Python string-programs Python Python Programs 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26077, "s": 26049, "text": "\n24 Jan, 2021" }, { "code": null, "e": 26333, "s": 26077, "text": "Given a String of date of format YYYYMMDD, our task is to compute the life path number. Life Path Number is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions." }, { "code": null, "e": 26343, "s": 26333, "text": "Examples:" }, { "code": null, "e": 26373, "s": 26343, "text": "Input : test_str = “19970314”" }, { "code": null, "e": 26384, "s": 26373, "text": "Output : 7" }, { "code": null, "e": 26509, "s": 26384, "text": "Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 3 = 3 [ month ] ; 1 + 4 = 5 [ day ]. 5 + 3 + 8 = 16 ; 1 + 6 = 7." }, { "code": null, "e": 26539, "s": 26509, "text": "Input : test_str = “19970104”" }, { "code": null, "e": 26550, "s": 26539, "text": "Output : 4" }, { "code": null, "e": 26675, "s": 26550, "text": "Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 1 = 1 [ month ] ; 0 + 4 = 4 [ day ]. 4 + 1 + 8 = 13 ; 1 + 3 = 4." }, { "code": null, "e": 26696, "s": 26675, "text": "Method 1: Using loop" }, { "code": null, "e": 26864, "s": 26696, "text": "The logic behind computing this is getting a summation of each digit and perform %10 at each step. This way result curlers to single digit if it goes to double-digit. " }, { "code": null, "e": 26872, "s": 26864, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Life Path Number# Using loop # initializing stringtest_str = \"19970314\" # printing original stringprint(\"The original string is : \" + str(test_str)) res = 0for num in test_str: res += int(num) # modulation in case of 2 digit number if res > 9: res = res % 10 + res // 10 # printing resultprint(\"Life Path Number : \" + str(res))", "e": 27269, "s": 26872, "text": null }, { "code": null, "e": 27277, "s": 27269, "text": "Output:" }, { "code": null, "e": 27333, "s": 27277, "text": "The original string is : 19970314\nLife Path Number : 7" }, { "code": null, "e": 27359, "s": 27333, "text": "Method 2: Using recursion" }, { "code": null, "e": 27496, "s": 27359, "text": "Similar way as above, the difference being the recursive function is used for repeated modulation in case of digit count greater than 1." }, { "code": null, "e": 27504, "s": 27496, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Life Path Number# Using recursion # initializing stringtest_str = \"19970314\" # printing original stringprint(\"The original string is : \" + str(test_str)) # recursion function definitiondef lpn(num): return num if num < 10 else lpn(num // 10 + num % 10) # recursive function initial callres = lpn(int(test_str)) # printing resultprint(\"Life Path Number : \" + str(res))", "e": 27920, "s": 27504, "text": null }, { "code": null, "e": 27928, "s": 27920, "text": "Output:" }, { "code": null, "e": 27984, "s": 27928, "text": "The original string is : 19970314\nLife Path Number : 7" }, { "code": null, "e": 28007, "s": 27984, "text": "Python string-programs" }, { "code": null, "e": 28014, "s": 28007, "text": "Python" }, { "code": null, "e": 28030, "s": 28014, "text": "Python Programs" }, { "code": null, "e": 28128, "s": 28030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28146, "s": 28128, "text": "Python Dictionary" }, { "code": null, "e": 28181, "s": 28146, "text": "Read a file line by line in Python" }, { "code": null, "e": 28213, "s": 28181, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28235, "s": 28213, "text": "Enumerate() in Python" }, { "code": null, "e": 28277, "s": 28235, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28320, "s": 28277, "text": "Python program to convert a list to string" }, { "code": null, "e": 28342, "s": 28320, "text": "Defaultdict in Python" }, { "code": null, "e": 28381, "s": 28342, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28427, "s": 28381, "text": "Python | Split string into list of characters" } ]
wxPython - Change Button Label Font - GeeksforGeeks
06 Jan, 2022 In this article we are going to learn that how can we change the font of the label text present on the button present in the frame. We need to follow some steps as follows: Step 1: Create a wx.Font object. Step 2: Add different attributes of font in parameters like: family, style etc. Step 3: Set font by using SetFont() function. Syntax: wx.Button.SetFont(self, font)Parameters: Code Example: Python3 import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) # wx.Font object initialization font = wx.Font(12, wx.FONTFAMILY_MODERN, 0, 90, underline = False, faceName ="") # CREATE BUTTON AT POINT (20, 20) self.st = wx.Button(self.pnl, id = 1, label ="Button", pos =(20, 20), size = wx.DefaultSize, name ="button") # SET FONT FOR LABEL self.st.SetFont(font) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Window: gulshankumarar231 Python wxPython-Button Python-gui Python-wxPython 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25903, "s": 25875, "text": "\n06 Jan, 2022" }, { "code": null, "e": 26077, "s": 25903, "text": "In this article we are going to learn that how can we change the font of the label text present on the button present in the frame. We need to follow some steps as follows: " }, { "code": null, "e": 26237, "s": 26077, "text": "Step 1: Create a wx.Font object. Step 2: Add different attributes of font in parameters like: family, style etc. Step 3: Set font by using SetFont() function. " }, { "code": null, "e": 26290, "s": 26239, "text": "Syntax: wx.Button.SetFont(self, font)Parameters: " }, { "code": null, "e": 26308, "s": 26292, "text": "Code Example: " }, { "code": null, "e": 26316, "s": 26308, "text": "Python3" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) # wx.Font object initialization font = wx.Font(12, wx.FONTFAMILY_MODERN, 0, 90, underline = False, faceName =\"\") # CREATE BUTTON AT POINT (20, 20) self.st = wx.Button(self.pnl, id = 1, label =\"Button\", pos =(20, 20), size = wx.DefaultSize, name =\"button\") # SET FONT FOR LABEL self.st.SetFont(font) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 27169, "s": 26316, "text": null }, { "code": null, "e": 27186, "s": 27169, "text": "Output Window: " }, { "code": null, "e": 27206, "s": 27188, "text": "gulshankumarar231" }, { "code": null, "e": 27229, "s": 27206, "text": "Python wxPython-Button" }, { "code": null, "e": 27240, "s": 27229, "text": "Python-gui" }, { "code": null, "e": 27256, "s": 27240, "text": "Python-wxPython" }, { "code": null, "e": 27263, "s": 27256, "text": "Python" }, { "code": null, "e": 27361, "s": 27263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27379, "s": 27361, "text": "Python Dictionary" }, { "code": null, "e": 27414, "s": 27379, "text": "Read a file line by line in Python" }, { "code": null, "e": 27446, "s": 27414, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27468, "s": 27446, "text": "Enumerate() in Python" }, { "code": null, "e": 27510, "s": 27468, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27540, "s": 27510, "text": "Iterate over a list in Python" }, { "code": null, "e": 27566, "s": 27540, "text": "Python String | replace()" }, { "code": null, "e": 27595, "s": 27566, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27639, "s": 27595, "text": "Reading and Writing to text files in Python" } ]
Java IO : Input-output in Java with Examples - GeeksforGeeks
01 Sep, 2021 Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide which are also most common in use: System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device.System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen.Here is a list of the various print functions that we use to output statements:print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.Syntax:System.out.print(parameter);Example:// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print("GfG! "); System.out.print("GfG! "); System.out.print("GfG! "); }}Output:GfG! GfG! GfG! println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.Syntax:System.out.println(parameter);Example:// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println("GfG! "); System.out.println("GfG! "); System.out.println("GfG! "); }}Output:GfG! GfG! GfG! printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java.Example:// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( "Printing simple" + " integer: x = %d\n", x); // this will print it upto // 2 decimal places System.out.printf( "Formatted with" + " precision: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( "Formatted to " + "specific width: n = %.4f\n", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( "Formatted to " + "right margin: n = %20.4f\n", n); }}Output:Printing simple integer: x = 100 Formatted with precision: PI = 3.14 Formatted to specific width: n = 5.2000 Formatted to right margin: n = 2324435.2500System.err: This is the standard error stream that is used to output all the error data that a program might throw, on a computer screen or any standard output device.This stream also uses all the 3 above-mentioned functions to output the error data:print()println()printf()Example:// Java code to illustrate standard// input output streams import java.io.*;public class SimpleIO { public static void main(String args[]) throws IOException { // InputStreamReader class to read input InputStreamReader inp = null; // Storing the input in inp inp = new InputStreamReader(System.in); System.out.println("Enter characters, " + " and '0' to quit."); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); }}Input:GeeksforGeeks0Output:Enter characters, and '0' to quit. G e e k s f o r G e e k s 0 System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device. System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen.Here is a list of the various print functions that we use to output statements:print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.Syntax:System.out.print(parameter);Example:// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print("GfG! "); System.out.print("GfG! "); System.out.print("GfG! "); }}Output:GfG! GfG! GfG! println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.Syntax:System.out.println(parameter);Example:// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println("GfG! "); System.out.println("GfG! "); System.out.println("GfG! "); }}Output:GfG! GfG! GfG! printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java.Example:// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( "Printing simple" + " integer: x = %d\n", x); // this will print it upto // 2 decimal places System.out.printf( "Formatted with" + " precision: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( "Formatted to " + "specific width: n = %.4f\n", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( "Formatted to " + "right margin: n = %20.4f\n", n); }}Output:Printing simple integer: x = 100 Formatted with precision: PI = 3.14 Formatted to specific width: n = 5.2000 Formatted to right margin: n = 2324435.2500 Here is a list of the various print functions that we use to output statements: print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.Syntax:System.out.print(parameter);Example:// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print("GfG! "); System.out.print("GfG! "); System.out.print("GfG! "); }}Output:GfG! GfG! GfG! System.out.print(parameter); Example: // Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print("GfG! "); System.out.print("GfG! "); System.out.print("GfG! "); }} Output: GfG! GfG! GfG! println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.Syntax:System.out.println(parameter);Example:// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println("GfG! "); System.out.println("GfG! "); System.out.println("GfG! "); }}Output:GfG! GfG! GfG! System.out.println(parameter); Example: // Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println("GfG! "); System.out.println("GfG! "); System.out.println("GfG! "); }} Output: GfG! GfG! GfG! printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java.Example:// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( "Printing simple" + " integer: x = %d\n", x); // this will print it upto // 2 decimal places System.out.printf( "Formatted with" + " precision: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( "Formatted to " + "specific width: n = %.4f\n", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( "Formatted to " + "right margin: n = %20.4f\n", n); }}Output:Printing simple integer: x = 100 Formatted with precision: PI = 3.14 Formatted to specific width: n = 5.2000 Formatted to right margin: n = 2324435.2500 // A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( "Printing simple" + " integer: x = %d\n", x); // this will print it upto // 2 decimal places System.out.printf( "Formatted with" + " precision: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( "Formatted to " + "specific width: n = %.4f\n", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( "Formatted to " + "right margin: n = %20.4f\n", n); }} Output: Printing simple integer: x = 100 Formatted with precision: PI = 3.14 Formatted to specific width: n = 5.2000 Formatted to right margin: n = 2324435.2500 System.err: This is the standard error stream that is used to output all the error data that a program might throw, on a computer screen or any standard output device.This stream also uses all the 3 above-mentioned functions to output the error data:print()println()printf()Example:// Java code to illustrate standard// input output streams import java.io.*;public class SimpleIO { public static void main(String args[]) throws IOException { // InputStreamReader class to read input InputStreamReader inp = null; // Storing the input in inp inp = new InputStreamReader(System.in); System.out.println("Enter characters, " + " and '0' to quit."); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); }}Input:GeeksforGeeks0Output:Enter characters, and '0' to quit. G e e k s f o r G e e k s 0 This stream also uses all the 3 above-mentioned functions to output the error data: print() println() printf() Example: // Java code to illustrate standard// input output streams import java.io.*;public class SimpleIO { public static void main(String args[]) throws IOException { // InputStreamReader class to read input InputStreamReader inp = null; // Storing the input in inp inp = new InputStreamReader(System.in); System.out.println("Enter characters, " + " and '0' to quit."); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); }} Input: GeeksforGeeks0 Output: Enter characters, and '0' to quit. G e e k s f o r G e e k s 0 Types of Streams: Depending on the type of operations, streams can be divided into two primary classes:Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc. Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc. Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc. Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc. Depending on the types of file, Streams can be divided into two primary classes which can be further divided into other classes as can be seen through the diagram below followed by the explanations.ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:Stream classDescriptionBufferedInputStreamIt is used for Buffered Input Stream.DataInputStreamIt contains method for reading java standard datatypes.FileInputStreamThis is used to reads from a fileInputStreamThis is an abstract class that describes stream input.PrintStreamThis contains the most used print() and println() methodBufferedOutputStreamThis is used for Buffered Output Stream.DataOutputStreamThis contains method for writing java standard data types.FileOutputStreamThis is used to write to a file.OutputStreamThis is an abstract class that describe stream output.Example:// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream("sorcefile.txt"); targetStream = new FileOutputStream("targetfile.txt"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}Output:Shows contents of file test.txt CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:Stream classDescriptionBufferedReaderIt is used to handle buffered input stream.FileReaderThis is an input stream that reads from file.InputStreamReaderThis input stream is used to translate byte to character.OutputStreamReaderThis output stream is used to translate character to byte.ReaderThis is an abstract class that define character stream input.PrintWriterThis contains the most used print() and println() methodWriterThis is an abstract class that define character stream output.BufferedWriterThis is used to handle buffered output stream.FileWriterThis is used to output stream that writes to file.Example:// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader("test.txt"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}Refer here for the complete difference between Byte and Character Stream Class in Java. ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:Stream classDescriptionBufferedInputStreamIt is used for Buffered Input Stream.DataInputStreamIt contains method for reading java standard datatypes.FileInputStreamThis is used to reads from a fileInputStreamThis is an abstract class that describes stream input.PrintStreamThis contains the most used print() and println() methodBufferedOutputStreamThis is used for Buffered Output Stream.DataOutputStreamThis contains method for writing java standard data types.FileOutputStreamThis is used to write to a file.OutputStreamThis is an abstract class that describe stream output.Example:// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream("sorcefile.txt"); targetStream = new FileOutputStream("targetfile.txt"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}Output:Shows contents of file test.txt CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:Stream classDescriptionBufferedReaderIt is used to handle buffered input stream.FileReaderThis is an input stream that reads from file.InputStreamReaderThis input stream is used to translate byte to character.OutputStreamReaderThis output stream is used to translate character to byte.ReaderThis is an abstract class that define character stream input.PrintWriterThis contains the most used print() and println() methodWriterThis is an abstract class that define character stream output.BufferedWriterThis is used to handle buffered output stream.FileWriterThis is used to output stream that writes to file.Example:// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader("test.txt"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}Refer here for the complete difference between Byte and Character Stream Class in Java. ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:Stream classDescriptionBufferedInputStreamIt is used for Buffered Input Stream.DataInputStreamIt contains method for reading java standard datatypes.FileInputStreamThis is used to reads from a fileInputStreamThis is an abstract class that describes stream input.PrintStreamThis contains the most used print() and println() methodBufferedOutputStreamThis is used for Buffered Output Stream.DataOutputStreamThis contains method for writing java standard data types.FileOutputStreamThis is used to write to a file.OutputStreamThis is an abstract class that describe stream output.Example:// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream("sorcefile.txt"); targetStream = new FileOutputStream("targetfile.txt"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}Output:Shows contents of file test.txt Example: // Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream("sorcefile.txt"); targetStream = new FileOutputStream("targetfile.txt"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }} Output: Shows contents of file test.txt CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:Stream classDescriptionBufferedReaderIt is used to handle buffered input stream.FileReaderThis is an input stream that reads from file.InputStreamReaderThis input stream is used to translate byte to character.OutputStreamReaderThis output stream is used to translate character to byte.ReaderThis is an abstract class that define character stream input.PrintWriterThis contains the most used print() and println() methodWriterThis is an abstract class that define character stream output.BufferedWriterThis is used to handle buffered output stream.FileWriterThis is used to output stream that writes to file.Example:// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader("test.txt"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}Refer here for the complete difference between Byte and Character Stream Class in Java. Example: // Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader("test.txt"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }} Refer here for the complete difference between Byte and Character Stream Class in Java. anikaseth98 java-basics Java-BufferedInputStream Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25607, "s": 25579, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25839, "s": 25607, "text": "Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations." }, { "code": null, "e": 25992, "s": 25839, "text": "Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide which are also most common in use:" }, { "code": null, "e": 29908, "s": 25992, "text": "System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device.System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen.Here is a list of the various print functions that we use to output statements:print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.Syntax:System.out.print(parameter);Example:// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); }}Output:GfG! GfG! GfG! println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.Syntax:System.out.println(parameter);Example:// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); }}Output:GfG! \nGfG! \nGfG! printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java.Example:// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( \"Printing simple\" + \" integer: x = %d\\n\", x); // this will print it upto // 2 decimal places System.out.printf( \"Formatted with\" + \" precision: PI = %.2f\\n\", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( \"Formatted to \" + \"specific width: n = %.4f\\n\", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( \"Formatted to \" + \"right margin: n = %20.4f\\n\", n); }}Output:Printing simple integer: x = 100\nFormatted with precision: PI = 3.14\nFormatted to specific width: n = 5.2000\nFormatted to right margin: n = 2324435.2500System.err: This is the standard error stream that is used to output all the error data that a program might throw, on a computer screen or any standard output device.This stream also uses all the 3 above-mentioned functions to output the error data:print()println()printf()Example:// Java code to illustrate standard// input output streams import java.io.*;public class SimpleIO { public static void main(String args[]) throws IOException { // InputStreamReader class to read input InputStreamReader inp = null; // Storing the input in inp inp = new InputStreamReader(System.in); System.out.println(\"Enter characters, \" + \" and '0' to quit.\"); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); }}Input:GeeksforGeeks0Output:Enter characters, and '0' to quit.\nG\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns\n0" }, { "code": null, "e": 30039, "s": 29908, "text": "System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device." }, { "code": null, "e": 32882, "s": 30039, "text": "System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen.Here is a list of the various print functions that we use to output statements:print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.Syntax:System.out.print(parameter);Example:// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); }}Output:GfG! GfG! GfG! println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.Syntax:System.out.println(parameter);Example:// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); }}Output:GfG! \nGfG! \nGfG! printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java.Example:// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( \"Printing simple\" + \" integer: x = %d\\n\", x); // this will print it upto // 2 decimal places System.out.printf( \"Formatted with\" + \" precision: PI = %.2f\\n\", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( \"Formatted to \" + \"specific width: n = %.4f\\n\", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( \"Formatted to \" + \"right margin: n = %20.4f\\n\", n); }}Output:Printing simple integer: x = 100\nFormatted with precision: PI = 3.14\nFormatted to specific width: n = 5.2000\nFormatted to right margin: n = 2324435.2500" }, { "code": null, "e": 32962, "s": 32882, "text": "Here is a list of the various print functions that we use to output statements:" }, { "code": null, "e": 33629, "s": 32962, "text": "print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.Syntax:System.out.print(parameter);Example:// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); }}Output:GfG! GfG! GfG! " }, { "code": null, "e": 33658, "s": 33629, "text": "System.out.print(parameter);" }, { "code": null, "e": 33667, "s": 33658, "text": "Example:" }, { "code": "// Java code to illustrate print()import java.io.*; class Demo_print { public static void main(String[] args) { // using print() // all are printed in the // same line System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); System.out.print(\"GfG! \"); }}", "e": 33973, "s": 33667, "text": null }, { "code": null, "e": 33981, "s": 33973, "text": "Output:" }, { "code": null, "e": 33997, "s": 33981, "text": "GfG! GfG! GfG! " }, { "code": null, "e": 34617, "s": 33997, "text": "println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.Syntax:System.out.println(parameter);Example:// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); }}Output:GfG! \nGfG! \nGfG! " }, { "code": null, "e": 34648, "s": 34617, "text": "System.out.println(parameter);" }, { "code": null, "e": 34657, "s": 34648, "text": "Example:" }, { "code": "// Java code to illustrate println() import java.io.*; class Demo_print { public static void main(String[] args) { // using println() // all are printed in the // different line System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); System.out.println(\"GfG! \"); }}", "e": 34980, "s": 34657, "text": null }, { "code": null, "e": 34988, "s": 34980, "text": "Output:" }, { "code": null, "e": 35006, "s": 34988, "text": "GfG! \nGfG! \nGfG! " }, { "code": null, "e": 36345, "s": 35006, "text": "printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments. This is used to format the output in Java.Example:// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( \"Printing simple\" + \" integer: x = %d\\n\", x); // this will print it upto // 2 decimal places System.out.printf( \"Formatted with\" + \" precision: PI = %.2f\\n\", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( \"Formatted to \" + \"specific width: n = %.4f\\n\", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( \"Formatted to \" + \"right margin: n = %20.4f\\n\", n); }}Output:Printing simple integer: x = 100\nFormatted with precision: PI = 3.14\nFormatted to specific width: n = 5.2000\nFormatted to right margin: n = 2324435.2500" }, { "code": "// A Java program to demonstrate working of printf() in Javaclass JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( \"Printing simple\" + \" integer: x = %d\\n\", x); // this will print it upto // 2 decimal places System.out.printf( \"Formatted with\" + \" precision: PI = %.2f\\n\", Math.PI); float n = 5.2f; // automatically appends zero // to the rightmost part of decimal System.out.printf( \"Formatted to \" + \"specific width: n = %.4f\\n\", n); n = 2324435.3f; // here number is formatted from // right margin and occupies a // width of 20 characters System.out.printf( \"Formatted to \" + \"right margin: n = %20.4f\\n\", n); }}", "e": 37267, "s": 36345, "text": null }, { "code": null, "e": 37275, "s": 37267, "text": "Output:" }, { "code": null, "e": 37436, "s": 37275, "text": "Printing simple integer: x = 100\nFormatted with precision: PI = 3.14\nFormatted to specific width: n = 5.2000\nFormatted to right margin: n = 2324435.2500" }, { "code": null, "e": 38380, "s": 37436, "text": "System.err: This is the standard error stream that is used to output all the error data that a program might throw, on a computer screen or any standard output device.This stream also uses all the 3 above-mentioned functions to output the error data:print()println()printf()Example:// Java code to illustrate standard// input output streams import java.io.*;public class SimpleIO { public static void main(String args[]) throws IOException { // InputStreamReader class to read input InputStreamReader inp = null; // Storing the input in inp inp = new InputStreamReader(System.in); System.out.println(\"Enter characters, \" + \" and '0' to quit.\"); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); }}Input:GeeksforGeeks0Output:Enter characters, and '0' to quit.\nG\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns\n0" }, { "code": null, "e": 38464, "s": 38380, "text": "This stream also uses all the 3 above-mentioned functions to output the error data:" }, { "code": null, "e": 38472, "s": 38464, "text": "print()" }, { "code": null, "e": 38482, "s": 38472, "text": "println()" }, { "code": null, "e": 38491, "s": 38482, "text": "printf()" }, { "code": null, "e": 38500, "s": 38491, "text": "Example:" }, { "code": "// Java code to illustrate standard// input output streams import java.io.*;public class SimpleIO { public static void main(String args[]) throws IOException { // InputStreamReader class to read input InputStreamReader inp = null; // Storing the input in inp inp = new InputStreamReader(System.in); System.out.println(\"Enter characters, \" + \" and '0' to quit.\"); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); }}", "e": 39073, "s": 38500, "text": null }, { "code": null, "e": 39080, "s": 39073, "text": "Input:" }, { "code": null, "e": 39095, "s": 39080, "text": "GeeksforGeeks0" }, { "code": null, "e": 39103, "s": 39095, "text": "Output:" }, { "code": null, "e": 39166, "s": 39103, "text": "Enter characters, and '0' to quit.\nG\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns\n0" }, { "code": null, "e": 39184, "s": 39166, "text": "Types of Streams:" }, { "code": null, "e": 39670, "s": 39184, "text": "Depending on the type of operations, streams can be divided into two primary classes:Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc." }, { "code": null, "e": 40071, "s": 39670, "text": "Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc." }, { "code": null, "e": 40279, "s": 40071, "text": "Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc." }, { "code": null, "e": 40473, "s": 40279, "text": "Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc." }, { "code": null, "e": 44522, "s": 40473, "text": "Depending on the types of file, Streams can be divided into two primary classes which can be further divided into other classes as can be seen through the diagram below followed by the explanations.ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:Stream classDescriptionBufferedInputStreamIt is used for Buffered Input Stream.DataInputStreamIt contains method for reading java standard datatypes.FileInputStreamThis is used to reads from a fileInputStreamThis is an abstract class that describes stream input.PrintStreamThis contains the most used print() and println() methodBufferedOutputStreamThis is used for Buffered Output Stream.DataOutputStreamThis contains method for writing java standard data types.FileOutputStreamThis is used to write to a file.OutputStreamThis is an abstract class that describe stream output.Example:// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream(\"sorcefile.txt\"); targetStream = new FileOutputStream(\"targetfile.txt\"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}Output:Shows contents of file test.txt CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:Stream classDescriptionBufferedReaderIt is used to handle buffered input stream.FileReaderThis is an input stream that reads from file.InputStreamReaderThis input stream is used to translate byte to character.OutputStreamReaderThis output stream is used to translate character to byte.ReaderThis is an abstract class that define character stream input.PrintWriterThis contains the most used print() and println() methodWriterThis is an abstract class that define character stream output.BufferedWriterThis is used to handle buffered output stream.FileWriterThis is used to output stream that writes to file.Example:// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader(\"test.txt\"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}Refer here for the complete difference between Byte and Character Stream Class in Java." }, { "code": null, "e": 48373, "s": 44522, "text": "ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:Stream classDescriptionBufferedInputStreamIt is used for Buffered Input Stream.DataInputStreamIt contains method for reading java standard datatypes.FileInputStreamThis is used to reads from a fileInputStreamThis is an abstract class that describes stream input.PrintStreamThis contains the most used print() and println() methodBufferedOutputStreamThis is used for Buffered Output Stream.DataOutputStreamThis contains method for writing java standard data types.FileOutputStreamThis is used to write to a file.OutputStreamThis is an abstract class that describe stream output.Example:// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream(\"sorcefile.txt\"); targetStream = new FileOutputStream(\"targetfile.txt\"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}Output:Shows contents of file test.txt CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:Stream classDescriptionBufferedReaderIt is used to handle buffered input stream.FileReaderThis is an input stream that reads from file.InputStreamReaderThis input stream is used to translate byte to character.OutputStreamReaderThis output stream is used to translate character to byte.ReaderThis is an abstract class that define character stream input.PrintWriterThis contains the most used print() and println() methodWriterThis is an abstract class that define character stream output.BufferedWriterThis is used to handle buffered output stream.FileWriterThis is used to output stream that writes to file.Example:// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader(\"test.txt\"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}Refer here for the complete difference between Byte and Character Stream Class in Java." }, { "code": null, "e": 50242, "s": 48373, "text": "ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:Stream classDescriptionBufferedInputStreamIt is used for Buffered Input Stream.DataInputStreamIt contains method for reading java standard datatypes.FileInputStreamThis is used to reads from a fileInputStreamThis is an abstract class that describes stream input.PrintStreamThis contains the most used print() and println() methodBufferedOutputStreamThis is used for Buffered Output Stream.DataOutputStreamThis contains method for writing java standard data types.FileOutputStreamThis is used to write to a file.OutputStreamThis is an abstract class that describe stream output.Example:// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream(\"sorcefile.txt\"); targetStream = new FileOutputStream(\"targetfile.txt\"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}Output:Shows contents of file test.txt " }, { "code": null, "e": 50251, "s": 50242, "text": "Example:" }, { "code": "// Java Program illustrating the// Byte Stream to copy// contents of one file to another file.import java.io.*;public class BStream { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream(\"sorcefile.txt\"); targetStream = new FileOutputStream(\"targetfile.txt\"); // Reading source file and writing // content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } }}", "e": 51175, "s": 50251, "text": null }, { "code": null, "e": 51183, "s": 51175, "text": "Output:" }, { "code": null, "e": 51216, "s": 51183, "text": "Shows contents of file test.txt " }, { "code": null, "e": 53199, "s": 51216, "text": "CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. Here is the list of various CharacterStream Classes:Stream classDescriptionBufferedReaderIt is used to handle buffered input stream.FileReaderThis is an input stream that reads from file.InputStreamReaderThis input stream is used to translate byte to character.OutputStreamReaderThis output stream is used to translate character to byte.ReaderThis is an abstract class that define character stream input.PrintWriterThis contains the most used print() and println() methodWriterThis is an abstract class that define character stream output.BufferedWriterThis is used to handle buffered output stream.FileWriterThis is used to output stream that writes to file.Example:// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader(\"test.txt\"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}Refer here for the complete difference between Byte and Character Stream Class in Java." }, { "code": null, "e": 53208, "s": 53199, "text": "Example:" }, { "code": "// Java Program illustrating that// we can read a file in a human-readable// format using FileReader // Accessing FileReader, FileWriter,// and IOExceptionimport java.io.*;public class GfG { public static void main( String[] args) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader(\"test.txt\"); // Reading sourcefile and // writing content to target file // character by character. int temp; while (( temp = sourceStream.read()) != -1) System.out.println((char)temp); } finally { // Closing stream as no longer in use if (sourceStream != null) sourceStream.close(); } }}", "e": 54044, "s": 53208, "text": null }, { "code": null, "e": 54132, "s": 54044, "text": "Refer here for the complete difference between Byte and Character Stream Class in Java." }, { "code": null, "e": 54144, "s": 54132, "text": "anikaseth98" }, { "code": null, "e": 54156, "s": 54144, "text": "java-basics" }, { "code": null, "e": 54181, "s": 54156, "text": "Java-BufferedInputStream" }, { "code": null, "e": 54197, "s": 54181, "text": "Java-IO package" }, { "code": null, "e": 54202, "s": 54197, "text": "Java" }, { "code": null, "e": 54207, "s": 54202, "text": "Java" }, { "code": null, "e": 54305, "s": 54207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54356, "s": 54305, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 54386, "s": 54356, "text": "HashMap in Java with Examples" }, { "code": null, "e": 54401, "s": 54386, "text": "Stream In Java" }, { "code": null, "e": 54420, "s": 54401, "text": "Interfaces in Java" }, { "code": null, "e": 54451, "s": 54420, "text": "How to iterate any Map in Java" }, { "code": null, "e": 54469, "s": 54451, "text": "ArrayList in Java" }, { "code": null, "e": 54501, "s": 54469, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 54521, "s": 54501, "text": "Stack Class in Java" }, { "code": null, "e": 54553, "s": 54521, "text": "Multidimensional Arrays in Java" } ]
Overview of WorkManager in Android Architecture Components - GeeksforGeeks
30 Dec, 2021 Android WorkManager could be thought of as a backgrounding library that is employed to execute background tasks that should run in a guaranteed way but not necessarily immediately. With WorkManager we’ll enqueue our backgrounding even when the app isn’t running and even when the device is rebooted for a couple of reasons. WorkManager also lets us define constraints necessary to run the task e.g. Wi-Fi. or battery availability before starting the background task. Android WorkManager is one of the parts of Android Jetpack (a suite of libraries to guide developers to write down great quality apps) and is one among the Android Architecture Components (collection of components that help developers design robust, testable, and simply maintainable apps). As the Android OS evolved greatly over the years, there are certain restrictions placed on backgrounding the processes, it all is been done so as to optimize battery consumption and make use of device resources in an optimal and judicious way. Each new Android release, ranging from android marshmallow (API 23), has added some restrictions and they continue to come till way. You can examine the precise details on an equivalent within the Android developer guide. Thus, it’s important to settle on the simplest backgrounding approach for your app per your needs. Let’s quickly mention cases once you would prefer to use WorkManager. Android WorkManager is often an ideal backgrounding library to use when your task: Doesn’t get to run at a selected timeCan be deferred to be executedIs bound to run even after the app is killed or the device is restarted or permanently shut downHas got to meet constraints like network coverage or network availability before execution Doesn’t get to run at a selected time Can be deferred to be executed Is bound to run even after the app is killed or the device is restarted or permanently shut down Has got to meet constraints like network coverage or network availability before execution The simplest example for this can be when your app needs to upload a large chunk of user data onto the server. This requires the developers to reside and use the WorkManager as it’s the perfect thing that is required! But Why? Results needn’t be reflected immediately in your Android app (slight delay is allowed)Data must be uploaded even when the upload begins and therefore the user kills the app to figure on another app or decides to keep the phone to rest, andThe network and battery must be available so as to upload data on the server. Results needn’t be reflected immediately in your Android app (slight delay is allowed) Data must be uploaded even when the upload begins and therefore the user kills the app to figure on another app or decides to keep the phone to rest, and The network and battery must be available so as to upload data on the server. Adding work manager is simple, just include the following lines in your project level and you’re good to roll! Java dependencies{ def work_version = "2.5.0" // (Java only) implementation "androidx.work:work-runtime:$work_version" // Kotlin + coroutines implementation "androidx.work:work-runtime-ktx:$work_version" // optional - RxJava2 support implementation "androidx.work:work-rxjava2:$work_version" // optional - GCMNetworkManager support implementation "androidx.work:work-gcm:$work_version" // optional - Test helpers androidTestImplementation "androidx.work:work-testing:$work_version" // optional - Multiprocess support implementation "androidx.work:work-multiprocess:$work_version"} We need to create some work like mentioned in the example above, and then we will need to extend the Worker class by overriding the doSomeWork() method. The below given example shows how to add a Worker to the Android App that uploads data (primarily Images) to a server. Java public class WorkManagerOverviewGfg extends Worker { public WorkManagerOverviewGfg(@NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @Override public Result doSomeWork() { // Do the work here--in this case, upload the data. uploadData(); return Result.success(); }} The Result method mentioned above (returned from the Code) tells the system service whether the specified job/work went alright or not. If it returns fail, then it also gives the method to retry the work or not Once that you have defined your work, you must now schedule it using the WorkManager service, so as to make the service run. You can also schedule it to run programmatically over an interval or multiple times, or make it run only once! The below code snippet guides you on how to build a service that runs your job only once! Java WorkRequest uploadRequestGfg = new OneTimeWorkRequest.Builder(WorkManagerOverviewGfg.class).build(); After you have successfully crafted a WorkRequest the final step which is needed to be done is to submit the created WorkRequest to WorkManager using the enqueue method(), and then just see your job is performed using the WorkManager. The below code snippet guides you through the required steps to get this final step done Java WorkManager.getInstance(getContext).enqueue(uploadRequestGfg); Now sit back and hold tight, the exact time the worker will take will include all the steps and constraints you’ve put in your WorkRequest and the system state at the moment. simmytarika5 Android-Jetpack Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Android Listview in Java with Example How to Save Data to the Firebase Realtime Database in Android? Flexbox-Layout in Android How to Change the Background Color After Clicking the Button in Android?
[ { "code": null, "e": 26381, "s": 26353, "text": "\n30 Dec, 2021" }, { "code": null, "e": 26850, "s": 26381, "text": "Android WorkManager could be thought of as a backgrounding library that is employed to execute background tasks that should run in a guaranteed way but not necessarily immediately. With WorkManager we’ll enqueue our backgrounding even when the app isn’t running and even when the device is rebooted for a couple of reasons. WorkManager also lets us define constraints necessary to run the task e.g. Wi-Fi. or battery availability before starting the background task. " }, { "code": null, "e": 27141, "s": 26850, "text": "Android WorkManager is one of the parts of Android Jetpack (a suite of libraries to guide developers to write down great quality apps) and is one among the Android Architecture Components (collection of components that help developers design robust, testable, and simply maintainable apps)." }, { "code": null, "e": 27859, "s": 27141, "text": "As the Android OS evolved greatly over the years, there are certain restrictions placed on backgrounding the processes, it all is been done so as to optimize battery consumption and make use of device resources in an optimal and judicious way. Each new Android release, ranging from android marshmallow (API 23), has added some restrictions and they continue to come till way. You can examine the precise details on an equivalent within the Android developer guide. Thus, it’s important to settle on the simplest backgrounding approach for your app per your needs. Let’s quickly mention cases once you would prefer to use WorkManager. Android WorkManager is often an ideal backgrounding library to use when your task:" }, { "code": null, "e": 28113, "s": 27859, "text": "Doesn’t get to run at a selected timeCan be deferred to be executedIs bound to run even after the app is killed or the device is restarted or permanently shut downHas got to meet constraints like network coverage or network availability before execution" }, { "code": null, "e": 28151, "s": 28113, "text": "Doesn’t get to run at a selected time" }, { "code": null, "e": 28182, "s": 28151, "text": "Can be deferred to be executed" }, { "code": null, "e": 28279, "s": 28182, "text": "Is bound to run even after the app is killed or the device is restarted or permanently shut down" }, { "code": null, "e": 28370, "s": 28279, "text": "Has got to meet constraints like network coverage or network availability before execution" }, { "code": null, "e": 28588, "s": 28370, "text": "The simplest example for this can be when your app needs to upload a large chunk of user data onto the server. This requires the developers to reside and use the WorkManager as it’s the perfect thing that is required!" }, { "code": null, "e": 28597, "s": 28588, "text": "But Why?" }, { "code": null, "e": 28914, "s": 28597, "text": "Results needn’t be reflected immediately in your Android app (slight delay is allowed)Data must be uploaded even when the upload begins and therefore the user kills the app to figure on another app or decides to keep the phone to rest, andThe network and battery must be available so as to upload data on the server." }, { "code": null, "e": 29001, "s": 28914, "text": "Results needn’t be reflected immediately in your Android app (slight delay is allowed)" }, { "code": null, "e": 29155, "s": 29001, "text": "Data must be uploaded even when the upload begins and therefore the user kills the app to figure on another app or decides to keep the phone to rest, and" }, { "code": null, "e": 29233, "s": 29155, "text": "The network and battery must be available so as to upload data on the server." }, { "code": null, "e": 29344, "s": 29233, "text": "Adding work manager is simple, just include the following lines in your project level and you’re good to roll!" }, { "code": null, "e": 29349, "s": 29344, "text": "Java" }, { "code": "dependencies{ def work_version = \"2.5.0\" // (Java only) implementation \"androidx.work:work-runtime:$work_version\" // Kotlin + coroutines implementation \"androidx.work:work-runtime-ktx:$work_version\" // optional - RxJava2 support implementation \"androidx.work:work-rxjava2:$work_version\" // optional - GCMNetworkManager support implementation \"androidx.work:work-gcm:$work_version\" // optional - Test helpers androidTestImplementation \"androidx.work:work-testing:$work_version\" // optional - Multiprocess support implementation \"androidx.work:work-multiprocess:$work_version\"}", "e": 30018, "s": 29349, "text": null }, { "code": null, "e": 30290, "s": 30018, "text": "We need to create some work like mentioned in the example above, and then we will need to extend the Worker class by overriding the doSomeWork() method. The below given example shows how to add a Worker to the Android App that uploads data (primarily Images) to a server." }, { "code": null, "e": 30295, "s": 30290, "text": "Java" }, { "code": "public class WorkManagerOverviewGfg extends Worker { public WorkManagerOverviewGfg(@NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @Override public Result doSomeWork() { // Do the work here--in this case, upload the data. uploadData(); return Result.success(); }}", "e": 30679, "s": 30295, "text": null }, { "code": null, "e": 30891, "s": 30679, "text": " The Result method mentioned above (returned from the Code) tells the system service whether the specified job/work went alright or not. If it returns fail, then it also gives the method to retry the work or not" }, { "code": null, "e": 31217, "s": 30891, "text": "Once that you have defined your work, you must now schedule it using the WorkManager service, so as to make the service run. You can also schedule it to run programmatically over an interval or multiple times, or make it run only once! The below code snippet guides you on how to build a service that runs your job only once!" }, { "code": null, "e": 31222, "s": 31217, "text": "Java" }, { "code": "WorkRequest uploadRequestGfg = new OneTimeWorkRequest.Builder(WorkManagerOverviewGfg.class).build();", "e": 31323, "s": 31222, "text": null }, { "code": null, "e": 31647, "s": 31323, "text": "After you have successfully crafted a WorkRequest the final step which is needed to be done is to submit the created WorkRequest to WorkManager using the enqueue method(), and then just see your job is performed using the WorkManager. The below code snippet guides you through the required steps to get this final step done" }, { "code": null, "e": 31652, "s": 31647, "text": "Java" }, { "code": "WorkManager.getInstance(getContext).enqueue(uploadRequestGfg);", "e": 31715, "s": 31652, "text": null }, { "code": null, "e": 31890, "s": 31715, "text": "Now sit back and hold tight, the exact time the worker will take will include all the steps and constraints you’ve put in your WorkRequest and the system state at the moment." }, { "code": null, "e": 31905, "s": 31892, "text": "simmytarika5" }, { "code": null, "e": 31921, "s": 31905, "text": "Android-Jetpack" }, { "code": null, "e": 31928, "s": 31921, "text": "Picked" }, { "code": null, "e": 31936, "s": 31928, "text": "Android" }, { "code": null, "e": 31944, "s": 31936, "text": "Android" }, { "code": null, "e": 32042, "s": 31944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32080, "s": 32042, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 32119, "s": 32080, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32169, "s": 32119, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32220, "s": 32169, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32262, "s": 32220, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32302, "s": 32262, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 32340, "s": 32302, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32403, "s": 32340, "text": "How to Save Data to the Firebase Realtime Database in Android?" }, { "code": null, "e": 32429, "s": 32403, "text": "Flexbox-Layout in Android" } ]
How to apply multiple CSS properties using jQuery?
Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here is the syntax for the method − selector.css( {key1:val1, key2:val2....keyN:valN}) Here you can pass key as property and val as its value as described above. You can try to run the following code to learn how to apply multiple CSS properties using jQuery: Live Demo <html> <head> <title>jQuery CSS</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("li").eq(2).css({"color":"red", "background-color":"green"}); }); </script> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html>
[ { "code": null, "e": 1217, "s": 1062, "text": "Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call." }, { "code": null, "e": 1253, "s": 1217, "text": "Here is the syntax for the method −" }, { "code": null, "e": 1304, "s": 1253, "text": "selector.css( {key1:val1, key2:val2....keyN:valN})" }, { "code": null, "e": 1379, "s": 1304, "text": "Here you can pass key as property and val as its value as described above." }, { "code": null, "e": 1477, "s": 1379, "text": "You can try to run the following code to learn how to apply multiple CSS properties using jQuery:" }, { "code": null, "e": 1487, "s": 1477, "text": "Live Demo" }, { "code": null, "e": 2089, "s": 1487, "text": "<html>\n <head>\n <title>jQuery CSS</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function() {\n $(\"li\").eq(2).css({\"color\":\"red\", \"background-color\":\"green\"});\n });\n </script>\n </head>\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div> \n </body>\n</html>" } ]
Sort a stack | Practice | GeeksforGeeks
Given a stack, the task is to sort it such that the top of the stack has the greatest element. Example 1: Input: Stack: 3 2 1 Output: 3 2 1 Example 2: Input: Stack: 11 2 32 3 41 Output: 41 32 11 3 2 Your Task: You don't have to read input or print anything. Your task is to complete the function sort() which sorts the elements present in the given stack. (The sorted stack is printed by the driver's code by popping the elements of the stack.) Expected Time Complexity: O(N*N) Expected Auxilliary Space: O(N) recursive. Constraints: 1<=N<=100 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 rajanithinbatchu5 hours ago class Solution: def sorted(self, s): s.sort() return s[::-1] 0 imabhishek0219 hours ago Most easy way using Min Heap and push and pop. void SortedStack :: sort() { priority_queue<int,vector<int>,greater<int>>pq; while(!s.empty()) { pq.push(s.top()); s.pop(); } while(!pq.empty()) { s.push(pq.top()); pq.pop(); } } +1 dipanshusharma93131 week ago // java solution class GfG{public Stack<Integer> sort(Stack<Integer> s){ //add code here. if(s.isEmpty()){ return s; } int temp = s.pop(); sort(s); return insertstack(s,temp);} public Stack<Integer> insertstack(Stack<Integer> s , int item){ if(s.isEmpty()){ s.push(item); return s; } if(item < s.peek()){ int temp = s.pop(); insertstack(s, item); s.push(temp); } else{ s.push(item); return s; } return s;}} 0 shilsoumyadip2 weeks ago void solve(stack<int>& st){ vector<int>v; while(!st.empty()){ v.push_back(st.top()); st.pop(); } sort(v.begin(),v.end()); for(int i:v){ st.push(i); }}void SortedStack :: sort(){ //Your code here solve(s); } +1 oyesaurabh2 weeks ago void insert(stack<int> &s,int e){ if(s.empty() || s.top()<e){ s.push(e); return; } int t=s.top(); s.pop(); insert(s,e); s.push(t); } void SortedStack :: sort() { //Your code here if(s.empty())return; int t=s.top(); s.pop(); sort(); insert(s,t); } 0 hharshit81182 weeks ago using two stacks :: void SortedStack :: sort(){ stack<int> s2; while(!s.empty()){ int t = s.top(); s.pop(); while(s2.empty() == false && s2.top() > t){ s.push(s2.top()); s2.pop(); } s2.push(t); } s = s2;} 0 harshscode2 weeks ago vector<int> v; while(!s.empty()) { v.push_back(s.top()); s.pop(); } sort(v.begin(),v.end()); for(auto i:v) s.push(i); 0 kaushalkumardbg622 weeks ago void go(stack<int>& s){ vector<int>v; while(!s.empty()){ v.push_back(s.top()); s.pop(); } sort(v.begin(),v.end()); for(int i:v){ s.push(i); }} void SortedStack :: sort(){ //Your code here go(s); } +1 iamnobodyji2 weeks ago Simple java solution: class GfG{ public Stack<Integer> sort(Stack<Integer> s) { //add code here. Stack<Integer> t = new Stack<>(); t.push(s.pop()); while(!s.empty()){ if(s.peek()<t.peek()){ int t1 = s.pop(); int t2=t.peek(); while(t2>t1 && !t.empty()){ s.push(t2); t.pop(); if(!t.empty()){ t2=t.peek(); } } t.push(t1); }else{ t.push(s.pop()); } } return t; } } 0 abhitiwari9876at This comment was deleted. 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": 333, "s": 238, "text": "Given a stack, the task is to sort it such that the top of the stack has the greatest element." }, { "code": null, "e": 344, "s": 333, "text": "Example 1:" }, { "code": null, "e": 379, "s": 344, "text": "Input:\nStack: 3 2 1\nOutput: 3 2 1\n" }, { "code": null, "e": 390, "s": 379, "text": "Example 2:" }, { "code": null, "e": 438, "s": 390, "text": "Input:\nStack: 11 2 32 3 41\nOutput: 41 32 11 3 2" }, { "code": null, "e": 685, "s": 438, "text": "Your Task: \nYou don't have to read input or print anything. Your task is to complete the function sort() which sorts the elements present in the given stack. (The sorted stack is printed by the driver's code by popping the elements of the stack.)" }, { "code": null, "e": 761, "s": 685, "text": "Expected Time Complexity: O(N*N)\nExpected Auxilliary Space: O(N) recursive." }, { "code": null, "e": 1094, "s": 761, "text": "Constraints:\n1<=N<=100\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1096, "s": 1094, "text": "0" }, { "code": null, "e": 1124, "s": 1096, "text": "rajanithinbatchu5 hours ago" }, { "code": null, "e": 1205, "s": 1124, "text": "class Solution:\n def sorted(self, s):\n s.sort()\n return s[::-1]" }, { "code": null, "e": 1207, "s": 1205, "text": "0" }, { "code": null, "e": 1232, "s": 1207, "text": "imabhishek0219 hours ago" }, { "code": null, "e": 1279, "s": 1232, "text": "Most easy way using Min Heap and push and pop." }, { "code": null, "e": 1486, "s": 1279, "text": "void SortedStack :: sort()\n{\npriority_queue<int,vector<int>,greater<int>>pq;\n \n while(!s.empty())\n {\n pq.push(s.top());\n s.pop();\n }\n while(!pq.empty())\n {\n s.push(pq.top());\n pq.pop();\n }\n}" }, { "code": null, "e": 1489, "s": 1486, "text": "+1" }, { "code": null, "e": 1518, "s": 1489, "text": "dipanshusharma93131 week ago" }, { "code": null, "e": 1535, "s": 1518, "text": "// java solution" }, { "code": null, "e": 1990, "s": 1535, "text": "class GfG{public Stack<Integer> sort(Stack<Integer> s){ //add code here. if(s.isEmpty()){ return s; } int temp = s.pop(); sort(s); return insertstack(s,temp);} public Stack<Integer> insertstack(Stack<Integer> s , int item){ if(s.isEmpty()){ s.push(item); return s; } if(item < s.peek()){ int temp = s.pop(); insertstack(s, item); s.push(temp); } else{ s.push(item); return s; } return s;}}" }, { "code": null, "e": 1992, "s": 1990, "text": "0" }, { "code": null, "e": 2017, "s": 1992, "text": "shilsoumyadip2 weeks ago" }, { "code": null, "e": 2248, "s": 2017, "text": "void solve(stack<int>& st){ vector<int>v; while(!st.empty()){ v.push_back(st.top()); st.pop(); } sort(v.begin(),v.end()); for(int i:v){ st.push(i); }}void SortedStack :: sort(){ //Your code here solve(s); }" }, { "code": null, "e": 2251, "s": 2248, "text": "+1" }, { "code": null, "e": 2273, "s": 2251, "text": "oyesaurabh2 weeks ago" }, { "code": null, "e": 2583, "s": 2273, "text": "void insert(stack<int> &s,int e){\n if(s.empty() || s.top()<e){\n s.push(e);\n return;\n }\n int t=s.top();\n s.pop();\n insert(s,e);\n s.push(t);\n}\nvoid SortedStack :: sort()\n{\n //Your code here\n if(s.empty())return;\n int t=s.top();\n s.pop();\n sort();\n insert(s,t);\n}\n" }, { "code": null, "e": 2585, "s": 2583, "text": "0" }, { "code": null, "e": 2609, "s": 2585, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 2630, "s": 2609, "text": "using two stacks :: " }, { "code": null, "e": 2873, "s": 2630, "text": "void SortedStack :: sort(){ stack<int> s2; while(!s.empty()){ int t = s.top(); s.pop(); while(s2.empty() == false && s2.top() > t){ s.push(s2.top()); s2.pop(); } s2.push(t); } s = s2;}" }, { "code": null, "e": 2875, "s": 2873, "text": "0" }, { "code": null, "e": 2897, "s": 2875, "text": "harshscode2 weeks ago" }, { "code": null, "e": 3032, "s": 2897, "text": " vector<int> v; while(!s.empty()) { v.push_back(s.top()); s.pop(); } sort(v.begin(),v.end()); for(auto i:v) s.push(i);" }, { "code": null, "e": 3034, "s": 3032, "text": "0" }, { "code": null, "e": 3063, "s": 3034, "text": "kaushalkumardbg622 weeks ago" }, { "code": null, "e": 3236, "s": 3063, "text": "void go(stack<int>& s){ vector<int>v; while(!s.empty()){ v.push_back(s.top()); s.pop(); } sort(v.begin(),v.end()); for(int i:v){ s.push(i); }}" }, { "code": null, "e": 3294, "s": 3236, "text": "void SortedStack :: sort(){ //Your code here go(s); }" }, { "code": null, "e": 3297, "s": 3294, "text": "+1" }, { "code": null, "e": 3320, "s": 3297, "text": "iamnobodyji2 weeks ago" }, { "code": null, "e": 3343, "s": 3320, "text": "Simple java solution: " }, { "code": null, "e": 3912, "s": 3343, "text": "class GfG{\n\tpublic Stack<Integer> sort(Stack<Integer> s)\n\t{\n\t\t//add code here.\n\t\tStack<Integer> t = new Stack<>();\n\t\tt.push(s.pop());\n\t\twhile(!s.empty()){\n\t\t if(s.peek()<t.peek()){\n int t1 = s.pop();\n int t2=t.peek();\n while(t2>t1 && !t.empty()){\n s.push(t2);\n t.pop();\n if(!t.empty()){\n t2=t.peek();\n }\n }\n t.push(t1);\n\t\t }else{\n\t\t t.push(s.pop());\n\t\t }\n\t\t}\n\t\t\n\t\treturn t;\n\t}\n}" }, { "code": null, "e": 3914, "s": 3912, "text": "0" }, { "code": null, "e": 3931, "s": 3914, "text": "abhitiwari9876at" }, { "code": null, "e": 3957, "s": 3931, "text": "This comment was deleted." }, { "code": null, "e": 4103, "s": 3957, "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": 4139, "s": 4103, "text": " Login to access your submissions. " }, { "code": null, "e": 4149, "s": 4139, "text": "\nProblem\n" }, { "code": null, "e": 4159, "s": 4149, "text": "\nContest\n" }, { "code": null, "e": 4222, "s": 4159, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4370, "s": 4222, "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": 4578, "s": 4370, "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": 4684, "s": 4578, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]