title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
GATE | GATE-CS-2017 (Set 2) | Question 49
28 Jun, 2021 Consider the following C function. int fun(int n) { int i, j; for (i = 1; i <= n ; i++) { for (j = 1; j < n; j += i) { printf("%d %d", i, j); } } } Time complexity of fun in terms of θ notation is:(A) θ(n √n)(B) θ(n2)(C) θ(n log n)(D) θ(n 2 log n) Answer: (C)Explanation: Let us see how many times the innermost statement “printf(“%d %d”, i, j);” is executed. For i = 1, the statement runs n timesThe i’th iteration, statement runs Θ(n/i) times. Summing all iterations for i = 1 to n, we getThus T(n) = Θ(n(1 + 1/2 +1/3 + ....)) = Θ(n log n). Note that the value of 1/1 + 1/2 + 1/3 + .... 1/n is approximately same as Log n for large values of n.Quiz of this Question GATE-CS-2017 (Set 2) GATE-GATE-CS-2017 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 89, "s": 54, "text": "Consider the following C function." }, { "code": null, "e": 256, "s": 89, "text": "int fun(int n)\n{\n int i, j;\n for (i = 1; i <= n ; i++)\n {\n for (j = 1; j < n; j += i)\n {\n printf(\"%d %d\", i, j);\n }\n }\n}\n" }, { "code": null, "e": 356, "s": 256, "text": "Time complexity of fun in terms of θ notation is:(A) θ(n √n)(B) θ(n2)(C) θ(n log n)(D) θ(n 2 log n)" }, { "code": null, "e": 468, "s": 356, "text": "Answer: (C)Explanation: Let us see how many times the innermost statement “printf(“%d %d”, i, j);” is executed." }, { "code": null, "e": 554, "s": 468, "text": "For i = 1, the statement runs n timesThe i’th iteration, statement runs Θ(n/i) times." }, { "code": null, "e": 651, "s": 554, "text": "Summing all iterations for i = 1 to n, we getThus T(n) = Θ(n(1 + 1/2 +1/3 + ....)) = Θ(n log n)." }, { "code": null, "e": 776, "s": 651, "text": "Note that the value of 1/1 + 1/2 + 1/3 + .... 1/n is approximately same as Log n for large values of n.Quiz of this Question" }, { "code": null, "e": 797, "s": 776, "text": "GATE-CS-2017 (Set 2)" }, { "code": null, "e": 823, "s": 797, "text": "GATE-GATE-CS-2017 (Set 2)" }, { "code": null, "e": 828, "s": 823, "text": "GATE" } ]
p5.js Introduction
24 Dec, 2021 p5.js is a JavaScript library used for creative coding. It is based on Processing which is a creative coding environment. The main focus of processing is to make it easy as possible for beginners to learn how to program interactive, graphical applications, to make a programming language more user-friendly by visualizing it.The advantage of using the JavaScript programming language is its broad availability and ubiquitous support: every web browser has a JavaScript interpreter built-in, which means that p5.js programs can be run on any web browser.Also, Processing is that language which emphasizes on feasibility for programmers to create software prototypes very quickly, to try out a new idea or see if something works. For this reason, Processing (and p5.js) programs are generally referred to as “sketches.” Preferred Editors The official documentation of p5.js suggests to use Bracket or Sublime and then include the JavaScript files, finally lead us to work like any other programming language. But the online p5.js Web Editor is the best alternative. It is based on a web-based programming environment. Difference between P5.js and JavaScript?JavaScript is a core language that provides all the features to build any functionalities into browsers. It can use Loop, Function, Conditional, DOM Manipulation, events, canvas, etc. Hence, by using it to develop and design any framework.p5.js is a library of JavaScript. P5.js is running on Pure JavaScript provides some functions that make JavaScript user life easy to draw in the web. Example: function setup() { createCanvas(400, 400); //Canvas size 400*400} function draw() { background('blue'); //background color blue} Output: setup(): It is the statements in the setup() function. It executes once when the program begins. createCanvas must be the first statement.draw(): The statements in the draw() are executed until the program is stopped. Each statement is executed in sequence and after the last line is read, the first line is executed again. Reference: https://p5js.org/ Lauren McCarthy (creator of p5.js) Cassie Tarakajian (creator of p5.js web editor) sarthak_ishu11 JavaScript-p5.js Technical Scripter 2018 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Dec, 2021" }, { "code": null, "e": 870, "s": 52, "text": "p5.js is a JavaScript library used for creative coding. It is based on Processing which is a creative coding environment. The main focus of processing is to make it easy as possible for beginners to learn how to program interactive, graphical applications, to make a programming language more user-friendly by visualizing it.The advantage of using the JavaScript programming language is its broad availability and ubiquitous support: every web browser has a JavaScript interpreter built-in, which means that p5.js programs can be run on any web browser.Also, Processing is that language which emphasizes on feasibility for programmers to create software prototypes very quickly, to try out a new idea or see if something works. For this reason, Processing (and p5.js) programs are generally referred to as “sketches.”" }, { "code": null, "e": 1168, "s": 870, "text": "Preferred Editors The official documentation of p5.js suggests to use Bracket or Sublime and then include the JavaScript files, finally lead us to work like any other programming language. But the online p5.js Web Editor is the best alternative. It is based on a web-based programming environment." }, { "code": null, "e": 1606, "s": 1168, "text": "Difference between P5.js and JavaScript?JavaScript is a core language that provides all the features to build any functionalities into browsers. It can use Loop, Function, Conditional, DOM Manipulation, events, canvas, etc. Hence, by using it to develop and design any framework.p5.js is a library of JavaScript. P5.js is running on Pure JavaScript provides some functions that make JavaScript user life easy to draw in the web. Example:" }, { "code": "function setup() { createCanvas(400, 400); //Canvas size 400*400} function draw() { background('blue'); //background color blue}", "e": 1738, "s": 1606, "text": null }, { "code": null, "e": 1746, "s": 1738, "text": "Output:" }, { "code": null, "e": 2070, "s": 1746, "text": "setup(): It is the statements in the setup() function. It executes once when the program begins. createCanvas must be the first statement.draw(): The statements in the draw() are executed until the program is stopped. Each statement is executed in sequence and after the last line is read, the first line is executed again." }, { "code": null, "e": 2099, "s": 2070, "text": "Reference: https://p5js.org/" }, { "code": null, "e": 2134, "s": 2099, "text": "Lauren McCarthy (creator of p5.js)" }, { "code": null, "e": 2182, "s": 2134, "text": "Cassie Tarakajian (creator of p5.js web editor)" }, { "code": null, "e": 2197, "s": 2182, "text": "sarthak_ishu11" }, { "code": null, "e": 2214, "s": 2197, "text": "JavaScript-p5.js" }, { "code": null, "e": 2238, "s": 2214, "text": "Technical Scripter 2018" }, { "code": null, "e": 2249, "s": 2238, "text": "JavaScript" }, { "code": null, "e": 2268, "s": 2249, "text": "Technical Scripter" }, { "code": null, "e": 2285, "s": 2268, "text": "Web Technologies" } ]
Python theHarvester – How to use it?
13 Jan, 2022 theHarvester is another tool like sublist3r which is developed using Python. This tool can be used by penetration testers for gathering information of emails, sub-domains, hosts, employee names, open ports, and banners from different public sources like search engines, PGP key servers, and SHODAN computer database. This tool can be used in passive reconnaissance and by anyone who needs to know what an attacker can see about the organization. If you are using a Kali Linux machine then this tool is already installed in it, just type the command theharvester or theHarvester It will generate a help menu and list all available options which look like this: root@kali:~# theharvester ******************************************************************* * * * | |_| |__ ___ /\ /\__ _ _ ____ _____ ___| |_ ___ _ __ * * | __| '_ \ / _ \ / /_/ / _` | '__\ \ / / _ \/ __| __/ _ \ '__| * * | |_| | | | __/ / __ / (_| | | \ V / __/\__ \ || __/ | * * \__|_| |_|\___| \/ /_/ \__, _|_| \_/ \___||___/\__\___|_| * * * * TheHarvester Ver. 3.0.0 * * Coded by Christian Martorella * * Edge-Security Research * * cmartorella@edge-security.com * ******************************************************************* Usage: theharvester options -d: Domain to search or company name -b: data source: baidu, bing, bingapi, dogpile, google, googleCSE, googleplus, google-profiles, linkedin, pgp, twitter, vhost, virustotal, threatcrowd, crtsh, netcraft, yahoo, all -s: start in result number X (default: 0) -v: verify host name via dns resolution and search for virtual hosts -f: save the results into an HTML and XML file (both) -n: perform a DNS reverse query on all ranges discovered -c: perform a DNS brute force for the domain name -t: perform a DNS TLD expansion discovery -e: use this DNS server -p: port scan the detected hosts and check for Takeovers (80, 443, 22, 21, 8080) -l: limit the number of results to work with(bing goes from 50 to 50 results, google 100 to 100, and pgp doesn't use this option) -h: use SHODAN database to query discovered hosts Examples: theharvester -d microsoft.com -l 500 -b google -h myresults.html theharvester -d microsoft.com -b pgp theharvester -d microsoft -l 200 -b linkedin theharvester -d apple.com -b googleCSE -l 500 -s 300 To install it in other Linux os you can use the command sudo apt-get theharvester If this do not work you can clone the Git hub repository and use it using commands git clone https://github.com/laramies/theHarvester.git cd theHarvester sudo python ./theHarvester.py Example Search email addresses from domain kali.org with results of 200 and using Bing as data source. theharvester -d kali.org -l 200 -b bing surinderdawra388 Kali-Linux python-modules Linux-Unix Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 474, "s": 28, "text": "theHarvester is another tool like sublist3r which is developed using Python. This tool can be used by penetration testers for gathering information of emails, sub-domains, hosts, employee names, open ports, and banners from different public sources like search engines, PGP key servers, and SHODAN computer database. This tool can be used in passive reconnaissance and by anyone who needs to know what an attacker can see about the organization." }, { "code": null, "e": 578, "s": 474, "text": "If you are using a Kali Linux machine then this tool is already installed in it, just type the command " }, { "code": null, "e": 591, "s": 578, "text": "theharvester" }, { "code": null, "e": 594, "s": 591, "text": "or" }, { "code": null, "e": 607, "s": 594, "text": "theHarvester" }, { "code": null, "e": 690, "s": 607, "text": "It will generate a help menu and list all available options which look like this:" }, { "code": null, "e": 2771, "s": 690, "text": "root@kali:~# theharvester\n\n*******************************************************************\n* *\n* | |_| |__ ___ /\\ /\\__ _ _ ____ _____ ___| |_ ___ _ __ *\n* | __| '_ \\ / _ \\ / /_/ / _` | '__\\ \\ / / _ \\/ __| __/ _ \\ '__| *\n* | |_| | | | __/ / __ / (_| | | \\ V / __/\\__ \\ || __/ | *\n* \\__|_| |_|\\___| \\/ /_/ \\__, _|_| \\_/ \\___||___/\\__\\___|_| *\n* *\n* TheHarvester Ver. 3.0.0 *\n* Coded by Christian Martorella *\n* Edge-Security Research *\n* cmartorella@edge-security.com *\n*******************************************************************\n\n\nUsage: theharvester options \n\n -d: Domain to search or company name\n -b: data source: baidu, bing, bingapi, dogpile, google, googleCSE,\n googleplus, google-profiles, linkedin, pgp, twitter, vhost, \n virustotal, threatcrowd, crtsh, netcraft, yahoo, all\n\n -s: start in result number X (default: 0)\n -v: verify host name via dns resolution and search for virtual hosts\n -f: save the results into an HTML and XML file (both)\n -n: perform a DNS reverse query on all ranges discovered\n -c: perform a DNS brute force for the domain name\n -t: perform a DNS TLD expansion discovery\n -e: use this DNS server\n -p: port scan the detected hosts and check for Takeovers (80, 443, 22, 21, 8080)\n -l: limit the number of results to work with(bing goes from 50 to 50 results,\n google 100 to 100, and pgp doesn't use this option)\n -h: use SHODAN database to query discovered hosts\n\nExamples:\n theharvester -d microsoft.com -l 500 -b google -h myresults.html\n theharvester -d microsoft.com -b pgp\n theharvester -d microsoft -l 200 -b linkedin\n theharvester -d apple.com -b googleCSE -l 500 -s 300" }, { "code": null, "e": 2827, "s": 2771, "text": "To install it in other Linux os you can use the command" }, { "code": null, "e": 2854, "s": 2827, "text": " sudo apt-get theharvester" }, { "code": null, "e": 2937, "s": 2854, "text": "If this do not work you can clone the Git hub repository and use it using commands" }, { "code": null, "e": 3038, "s": 2937, "text": "git clone https://github.com/laramies/theHarvester.git\ncd theHarvester\nsudo python ./theHarvester.py" }, { "code": null, "e": 3047, "s": 3038, "text": "Example " }, { "code": null, "e": 3142, "s": 3047, "text": "Search email addresses from domain kali.org with results of 200 and using Bing as data source." }, { "code": null, "e": 3182, "s": 3142, "text": "theharvester -d kali.org -l 200 -b bing" }, { "code": null, "e": 3199, "s": 3182, "text": "surinderdawra388" }, { "code": null, "e": 3210, "s": 3199, "text": "Kali-Linux" }, { "code": null, "e": 3225, "s": 3210, "text": "python-modules" }, { "code": null, "e": 3236, "s": 3225, "text": "Linux-Unix" }, { "code": null, "e": 3243, "s": 3236, "text": "Python" } ]
Generalized Lambda Expressions in C++14
20 Dec, 2017 Lambda expressions were introduced in C++11. They are basically snippets of code that can be nested inside other functions and even function call statements. By combining a lambda expression with the auto keyword these expressions can then be later used in the program. We have discussed lambda expressions in detail in this article Lambda Expressions in C++. Before proceeding in this article make sure you have either read the linked article, or know about lambda expression semantics like scope capture, return value. C++ 14 buffed up lambda expressions further by introducing whats called a generalized lambda. To understand this feature lets take a general example. Suppose we create a lambda function to return the sum of two integers. So our lambda function would look like [](int a, int b) -> int { return a + b; } But what if we needed to obtain the sum of two floating point values later on. So we would need to declare another lambda expression that would work for only double values. Similarly each time our input parameters changed in type, the lambda function needed to be rewritten. [](double a, double b) -> double { return a + b; } Before C++ 14 there was a way to circumvent this problem by using template parameters, template<typename T> [](T a, T b) -> T { return a + b }; C++ 14 does away with this and allows us to use the keyword auto in the input parameters of the lambda expression. Thus the compilers can now deduce the type of parameters during compile time. So, in our previous example, a lambda expression that would work for both integer and floating point values would be [](auto a, auto b) { return a + b; } A very important application of this feature is that enhances existing algorithms greatly. Take for instance the sort() function. The following snippet will sort all data types ( provided they have overloaded < operators) in descending order. sort(container.begin(), container.end(), [](auto i, auto j) -> bool { return i > j; } Here are a few example programs using generalized lambdas : Example 1 // Cpp program to demonstrate// generalized lambda expressions#include <iostream>#include <string> using namespace std;int main(){ // Declare a generalized lambda and store it in sum auto sum = [](auto a, auto b) { return a + b; }; // Find sum of two integers cout << sum(1, 6) << endl; // Find sum of two floating numbers cout << sum(1.0, 5.6) << endl; // Find sum of two strings cout << sum(string("Geeks"), string("ForGeeks")) << endl; return 0;} Output: 7 6.6 GeeksForGeeks Example 2 : // Cpp program to demonstrate// how to sort integers, floats, strings// floating data types using a // generalized lambda and sort function #include <algorithm>#include <iostream>#include <string>#include <vector> using namespace std; // Utility Function to print the elements of a collectionvoid printElements(auto& C){ for (auto e : C) cout << e << " "; cout << endl;} int main(){ // Declare a generalized lambda and store it in greater auto greater = [](auto a, auto b) -> bool { return a > b; }; // Initialize a vector of integers vector<int> vi = { 1, 4, 2, 1, 6, 62, 636 }; // Initialize a vector of doubles vector<double> vd = { 4.62, 161.3, 62.26, 13.4, 235.5 }; // Initialize a vector of strings vector<string> vs = { "Tom", "Harry", "Ram", "Shyam" }; // Sort integers sort(vi.begin(), vi.end(), greater); // Sort doubles sort(vd.begin(), vd.end(), greater); // Sort strings sort(vs.begin(), vs.end(), greater); printElements(vi); printElements(vd); printElements(vs); return 0;} Output: 636 62 6 4 2 1 1 235.5 161.3 62.26 13.4 4.62 Tom Shyam Ram Harry Note : Generalized Lambda expressions only work for C++ standards 14 and later. The list of compilers that support C++ 14 is given in the references section References: https://isocpp.org/wiki/faq/cpp14-language http://en.cppreference.com/w/cpp/compiler_support cpp-advanced C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Dec, 2017" }, { "code": null, "e": 324, "s": 54, "text": "Lambda expressions were introduced in C++11. They are basically snippets of code that can be nested inside other functions and even function call statements. By combining a lambda expression with the auto keyword these expressions can then be later used in the program." }, { "code": null, "e": 575, "s": 324, "text": "We have discussed lambda expressions in detail in this article Lambda Expressions in C++. Before proceeding in this article make sure you have either read the linked article, or know about lambda expression semantics like scope capture, return value." }, { "code": null, "e": 835, "s": 575, "text": "C++ 14 buffed up lambda expressions further by introducing whats called a generalized lambda. To understand this feature lets take a general example. Suppose we create a lambda function to return the sum of two integers. So our lambda function would look like" }, { "code": null, "e": 878, "s": 835, "text": "[](int a, int b) -> int { return a + b; }\n" }, { "code": null, "e": 1153, "s": 878, "text": "But what if we needed to obtain the sum of two floating point values later on. So we would need to declare another lambda expression that would work for only double values. Similarly each time our input parameters changed in type, the lambda function needed to be rewritten." }, { "code": null, "e": 1205, "s": 1153, "text": "[](double a, double b) -> double { return a + b; }\n" }, { "code": null, "e": 1292, "s": 1205, "text": "Before C++ 14 there was a way to circumvent this problem by using template parameters," }, { "code": null, "e": 1350, "s": 1292, "text": "template<typename T>\n[](T a, T b) -> T { return a + b };\n" }, { "code": null, "e": 1660, "s": 1350, "text": "C++ 14 does away with this and allows us to use the keyword auto in the input parameters of the lambda expression. Thus the compilers can now deduce the type of parameters during compile time. So, in our previous example, a lambda expression that would work for both integer and floating point values would be" }, { "code": null, "e": 1698, "s": 1660, "text": "[](auto a, auto b) { return a + b; }\n" }, { "code": null, "e": 1941, "s": 1698, "text": "A very important application of this feature is that enhances existing algorithms greatly. Take for instance the sort() function. The following snippet will sort all data types ( provided they have overloaded < operators) in descending order." }, { "code": null, "e": 2029, "s": 1941, "text": "sort(container.begin(), container.end(), \n[](auto i, auto j) -> bool { return i > j; }\n" }, { "code": null, "e": 2089, "s": 2029, "text": "Here are a few example programs using generalized lambdas :" }, { "code": null, "e": 2099, "s": 2089, "text": "Example 1" }, { "code": "// Cpp program to demonstrate// generalized lambda expressions#include <iostream>#include <string> using namespace std;int main(){ // Declare a generalized lambda and store it in sum auto sum = [](auto a, auto b) { return a + b; }; // Find sum of two integers cout << sum(1, 6) << endl; // Find sum of two floating numbers cout << sum(1.0, 5.6) << endl; // Find sum of two strings cout << sum(string(\"Geeks\"), string(\"ForGeeks\")) << endl; return 0;}", "e": 2597, "s": 2099, "text": null }, { "code": null, "e": 2605, "s": 2597, "text": "Output:" }, { "code": null, "e": 2626, "s": 2605, "text": "7\n6.6\nGeeksForGeeks\n" }, { "code": null, "e": 2638, "s": 2626, "text": "Example 2 :" }, { "code": "// Cpp program to demonstrate// how to sort integers, floats, strings// floating data types using a // generalized lambda and sort function #include <algorithm>#include <iostream>#include <string>#include <vector> using namespace std; // Utility Function to print the elements of a collectionvoid printElements(auto& C){ for (auto e : C) cout << e << \" \"; cout << endl;} int main(){ // Declare a generalized lambda and store it in greater auto greater = [](auto a, auto b) -> bool { return a > b; }; // Initialize a vector of integers vector<int> vi = { 1, 4, 2, 1, 6, 62, 636 }; // Initialize a vector of doubles vector<double> vd = { 4.62, 161.3, 62.26, 13.4, 235.5 }; // Initialize a vector of strings vector<string> vs = { \"Tom\", \"Harry\", \"Ram\", \"Shyam\" }; // Sort integers sort(vi.begin(), vi.end(), greater); // Sort doubles sort(vd.begin(), vd.end(), greater); // Sort strings sort(vs.begin(), vs.end(), greater); printElements(vi); printElements(vd); printElements(vs); return 0;}", "e": 3730, "s": 2638, "text": null }, { "code": null, "e": 3738, "s": 3730, "text": "Output:" }, { "code": null, "e": 3879, "s": 3738, "text": "636 62 6 4 2 1 1\n235.5 161.3 62.26 13.4 4.62 \nTom Shyam Ram Harry \n" }, { "code": null, "e": 4036, "s": 3879, "text": "Note : Generalized Lambda expressions only work for C++ standards 14 and later. The list of compilers that support C++ 14 is given in the references section" }, { "code": null, "e": 4048, "s": 4036, "text": "References:" }, { "code": null, "e": 4091, "s": 4048, "text": "https://isocpp.org/wiki/faq/cpp14-language" }, { "code": null, "e": 4141, "s": 4091, "text": "http://en.cppreference.com/w/cpp/compiler_support" }, { "code": null, "e": 4154, "s": 4141, "text": "cpp-advanced" }, { "code": null, "e": 4165, "s": 4154, "text": "C Language" }, { "code": null, "e": 4169, "s": 4165, "text": "C++" }, { "code": null, "e": 4173, "s": 4169, "text": "CPP" } ]
Gerrit - Download Examples Using Git
You can download the example using Git along with the source code of any project organized at gerrit.wikimedia.org using the following Git Bash command. $ git clone ssh://<user_name>@gerrit.wikimedia.org:29418/sandbox The git clone command clones a directory into a new directory; in other words gets a copy of an existing repository. When you run the above command,it will clone the 'examples' repository and receives the objects, files, etc. from that repository and stores it in your local branch. Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2238, "text": "You can download the example using Git along with the source code of any project organized at gerrit.wikimedia.org using the following Git Bash command." }, { "code": null, "e": 2458, "s": 2391, "text": "$ git clone \nssh://<user_name>@gerrit.wikimedia.org:29418/sandbox\n" }, { "code": null, "e": 2741, "s": 2458, "text": "The git clone command clones a directory into a new directory; in other words gets a copy of an existing repository. When you run the above command,it will clone the 'examples' repository and receives the objects, files, etc. from that repository and stores it in your local branch." }, { "code": null, "e": 2748, "s": 2741, "text": " Print" }, { "code": null, "e": 2759, "s": 2748, "text": " Add Notes" } ]
Top Data Science Misconceptions I Learned in 2021 | Towards Data Science
IntroductionAB Testing is Only About SignificanceOnly Looking at Model Error & AccuracyYou Won’t Use SQLSummaryReferences Introduction AB Testing is Only About Significance Only Looking at Model Error & Accuracy You Won’t Use SQL Summary References Data scientists have a lot of expectations from companies as well as expectations for the role itself. There are things we expect that turn into misconceptions of the position itself, which can cause stress and confusion down the road. In this article, we will look at five misconceptions that I have personally experienced that you may also experience, and what you should expect instead; intended for any data scientist, from beginner to advanced. With that being said, let’s dive deeper into five misconceptions of 2021 that you can learn from for your data science career in 2022. Data scientists can get wrapped up in statistics and lose sight of the company goal. AB testing is one of those areas that data scientists may employ. While understanding and executing proper statistics are usually a part of the job and are expected, focusing too much on p-values itself, for example, might lead you away from the overall goal. What not to do: When comparing a test group against a control, only look at signifiance/p-value What to do: When comparing a test group against a control, look at the p-value, the sample size, and the duration of the test. It may be the case where you reach significance (or not), but it is not held steady over time. When you assess more than just the p-value, you can make sure that your test is fully processed and will stand the test of time. In addition to the test characteristics, you will want to focus on if the metrics make sense to test in general. For example, if you are incorporating a new product, you will want to look at metrics that can show an increase in business success, like: Revenue Retention Engagement You will also want to make sure that you do not harm the business, or cause negative effects to the business with a product change from a data science model. In a similar way to the above point, this misconception summarizes that just because you have an accurate model, it does not mean that you have a useful model. What not to do: A. The model has 94% accuracy for classifying good users from bad users (identifying users as good or bad is most not likely as useful because you cannot perform actionable processes from it, and it is not well defined) B. The model has an MAE of 4 min for bus arrival time (the MAE might be low, but if it tends to sway in one direction, then it could not be as useful for customers who do not want to stand at the bus stop for longer and would prefer to be there earlier) What to do: A. The model has 94% accuracy for classifying customers who buy products more versus who buy no products at all, or very few (this way, you can identify characteristics for people who spend more money, and can see if those features can be applied to the users who do not spend as much money, for example, if people tend to click on an iPhone notification versus an Android notification, perhaps the UI experiences are different, and that needs to be addressed) B. The model has an MAE of 4 min but now the metric is optimized for more values to be on the earlier side rather than the later side (this way, the model is just about as accurate overall, but it helps the use case more in the real world) As you can see, in addition to accuracy or error, you will need to identify the direction of the metric, as well as if what you are predicting is usable to make improvements or not. Because education programs in data science focus more on data science itself as well as machine learning, SQL can often be neglected or not taught at all. In order to be a more well-rounded data scientist, you will want to learn SQL so you do not have to learn it on the spot in your career. What not to do: Expect that all the SQL will be done for you or the data you use for your model is already created (you will most likely need to query your company database using SQL for obtaining your training data) What to do: Understand SQL while learning data science, and take more than just one course on it (you will also want to learn SQL to query your results from your models, as usually, it is the case that your predictions are stored in a table that is queryable) There are some jobs where you will not need to perform SQL for data science, but usually, you do, and it is not as much of a focus when you are trying to learn about machine learning algorithms. Learn it over time so that you do not have to rush into it, especially in your first data science position. As you can see, there are a few misconceptions about a career in data science. I have learned about these in the role itself this year, rather than from studying about it before entering a role. Of course, there are plenty more, but I hope this article has given some the opportunity to fix or improve upon your data science misconceptions moving forward. To summarize, here are some of the common data science misconceptions that you can learn from as well: * AB Testing is Only About Significance* Only Looking at Model Error & Accuracy* You Won’t Use SQL I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these misconceptions included. Why or why not? What other misconceptions do you think we could include that are just or more important? These can certainly be clarified even further, but I hope I was able to shed some light on some more unique misconceptions that I have personally experienced. Thank you for reading! I am not affiliated with any of these companies. Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments. Subscribe link: https://datascience2.medium.com/subscribe Referral link: https://datascience2.medium.com/membership (I will receive a commission if you sign up for a membership on Medium) [1] Photo by Isabela Kronemberger on Unsplash, (2021) [2] Photo by Markus Winkler on Unsplash, (2020) [3] Photo by Nicolas Horn on Unsplash, (2021) [4] Photo by Caspar Camille Rubin on Unsplash, (2017)
[ { "code": null, "e": 294, "s": 172, "text": "IntroductionAB Testing is Only About SignificanceOnly Looking at Model Error & AccuracyYou Won’t Use SQLSummaryReferences" }, { "code": null, "e": 307, "s": 294, "text": "Introduction" }, { "code": null, "e": 345, "s": 307, "text": "AB Testing is Only About Significance" }, { "code": null, "e": 384, "s": 345, "text": "Only Looking at Model Error & Accuracy" }, { "code": null, "e": 402, "s": 384, "text": "You Won’t Use SQL" }, { "code": null, "e": 410, "s": 402, "text": "Summary" }, { "code": null, "e": 421, "s": 410, "text": "References" }, { "code": null, "e": 1006, "s": 421, "text": "Data scientists have a lot of expectations from companies as well as expectations for the role itself. There are things we expect that turn into misconceptions of the position itself, which can cause stress and confusion down the road. In this article, we will look at five misconceptions that I have personally experienced that you may also experience, and what you should expect instead; intended for any data scientist, from beginner to advanced. With that being said, let’s dive deeper into five misconceptions of 2021 that you can learn from for your data science career in 2022." }, { "code": null, "e": 1351, "s": 1006, "text": "Data scientists can get wrapped up in statistics and lose sight of the company goal. AB testing is one of those areas that data scientists may employ. While understanding and executing proper statistics are usually a part of the job and are expected, focusing too much on p-values itself, for example, might lead you away from the overall goal." }, { "code": null, "e": 1367, "s": 1351, "text": "What not to do:" }, { "code": null, "e": 1447, "s": 1367, "text": "When comparing a test group against a control, only look at signifiance/p-value" }, { "code": null, "e": 1459, "s": 1447, "text": "What to do:" }, { "code": null, "e": 1669, "s": 1459, "text": "When comparing a test group against a control, look at the p-value, the sample size, and the duration of the test. It may be the case where you reach significance (or not), but it is not held steady over time." }, { "code": null, "e": 2050, "s": 1669, "text": "When you assess more than just the p-value, you can make sure that your test is fully processed and will stand the test of time. In addition to the test characteristics, you will want to focus on if the metrics make sense to test in general. For example, if you are incorporating a new product, you will want to look at metrics that can show an increase in business success, like:" }, { "code": null, "e": 2058, "s": 2050, "text": "Revenue" }, { "code": null, "e": 2068, "s": 2058, "text": "Retention" }, { "code": null, "e": 2079, "s": 2068, "text": "Engagement" }, { "code": null, "e": 2237, "s": 2079, "text": "You will also want to make sure that you do not harm the business, or cause negative effects to the business with a product change from a data science model." }, { "code": null, "e": 2397, "s": 2237, "text": "In a similar way to the above point, this misconception summarizes that just because you have an accurate model, it does not mean that you have a useful model." }, { "code": null, "e": 2413, "s": 2397, "text": "What not to do:" }, { "code": null, "e": 2485, "s": 2413, "text": "A. The model has 94% accuracy for classifying good users from bad users" }, { "code": null, "e": 2633, "s": 2485, "text": "(identifying users as good or bad is most not likely as useful because you cannot perform actionable processes from it, and it is not well defined)" }, { "code": null, "e": 2687, "s": 2633, "text": "B. The model has an MAE of 4 min for bus arrival time" }, { "code": null, "e": 2887, "s": 2687, "text": "(the MAE might be low, but if it tends to sway in one direction, then it could not be as useful for customers who do not want to stand at the bus stop for longer and would prefer to be there earlier)" }, { "code": null, "e": 2899, "s": 2887, "text": "What to do:" }, { "code": null, "e": 3024, "s": 2899, "text": "A. The model has 94% accuracy for classifying customers who buy products more versus who buy no products at all, or very few" }, { "code": null, "e": 3360, "s": 3024, "text": "(this way, you can identify characteristics for people who spend more money, and can see if those features can be applied to the users who do not spend as much money, for example, if people tend to click on an iPhone notification versus an Android notification, perhaps the UI experiences are different, and that needs to be addressed)" }, { "code": null, "e": 3494, "s": 3360, "text": "B. The model has an MAE of 4 min but now the metric is optimized for more values to be on the earlier side rather than the later side" }, { "code": null, "e": 3600, "s": 3494, "text": "(this way, the model is just about as accurate overall, but it helps the use case more in the real world)" }, { "code": null, "e": 3782, "s": 3600, "text": "As you can see, in addition to accuracy or error, you will need to identify the direction of the metric, as well as if what you are predicting is usable to make improvements or not." }, { "code": null, "e": 4074, "s": 3782, "text": "Because education programs in data science focus more on data science itself as well as machine learning, SQL can often be neglected or not taught at all. In order to be a more well-rounded data scientist, you will want to learn SQL so you do not have to learn it on the spot in your career." }, { "code": null, "e": 4090, "s": 4074, "text": "What not to do:" }, { "code": null, "e": 4189, "s": 4090, "text": "Expect that all the SQL will be done for you or the data you use for your model is already created" }, { "code": null, "e": 4291, "s": 4189, "text": "(you will most likely need to query your company database using SQL for obtaining your training data)" }, { "code": null, "e": 4303, "s": 4291, "text": "What to do:" }, { "code": null, "e": 4388, "s": 4303, "text": "Understand SQL while learning data science, and take more than just one course on it" }, { "code": null, "e": 4551, "s": 4388, "text": "(you will also want to learn SQL to query your results from your models, as usually, it is the case that your predictions are stored in a table that is queryable)" }, { "code": null, "e": 4854, "s": 4551, "text": "There are some jobs where you will not need to perform SQL for data science, but usually, you do, and it is not as much of a focus when you are trying to learn about machine learning algorithms. Learn it over time so that you do not have to rush into it, especially in your first data science position." }, { "code": null, "e": 5210, "s": 4854, "text": "As you can see, there are a few misconceptions about a career in data science. I have learned about these in the role itself this year, rather than from studying about it before entering a role. Of course, there are plenty more, but I hope this article has given some the opportunity to fix or improve upon your data science misconceptions moving forward." }, { "code": null, "e": 5313, "s": 5210, "text": "To summarize, here are some of the common data science misconceptions that you can learn from as well:" }, { "code": null, "e": 5412, "s": 5313, "text": "* AB Testing is Only About Significance* Only Looking at Model Error & Accuracy* You Won’t Use SQL" }, { "code": null, "e": 5856, "s": 5412, "text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these misconceptions included. Why or why not? What other misconceptions do you think we could include that are just or more important? These can certainly be clarified even further, but I hope I was able to shed some light on some more unique misconceptions that I have personally experienced. Thank you for reading!" }, { "code": null, "e": 5905, "s": 5856, "text": "I am not affiliated with any of these companies." }, { "code": null, "e": 6229, "s": 5905, "text": "Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments." }, { "code": null, "e": 6287, "s": 6229, "text": "Subscribe link: https://datascience2.medium.com/subscribe" }, { "code": null, "e": 6345, "s": 6287, "text": "Referral link: https://datascience2.medium.com/membership" }, { "code": null, "e": 6417, "s": 6345, "text": "(I will receive a commission if you sign up for a membership on Medium)" }, { "code": null, "e": 6471, "s": 6417, "text": "[1] Photo by Isabela Kronemberger on Unsplash, (2021)" }, { "code": null, "e": 6519, "s": 6471, "text": "[2] Photo by Markus Winkler on Unsplash, (2020)" }, { "code": null, "e": 6565, "s": 6519, "text": "[3] Photo by Nicolas Horn on Unsplash, (2021)" } ]
Construct a tree from Inorder and Level order traversals | Set 1 - GeeksforGeeks
21 Feb, 2022 Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the two arrays. For the above two arrays, the constructed tree is shown in the diagram on right side The following post can be considered as a prerequisite for this. Construct Tree from given Inorder and Preorder traversals Let us consider the above example.in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14};In a Levelorder sequence, the first element is the root of the tree. So we know ’20’ is root for given sequences. By searching ’20’ in Inorder sequence, we can find out all elements on left side of ‘20’ are in left subtree and elements on right are in right subtree. So we know below structure now. 20 / \ / \ {4,8,10,12,14} {22} Let us call {4,8,10,12,14} as left subarray in Inorder traversal and {22} as right subarray in Inorder traversal. In level order traversal, keys of left and right subtrees are not consecutive. So we extract all nodes from level order traversal which are in left subarray of Inorder traversal. To construct the left subtree of root, we recur for the extracted elements from level order traversal and left subarray of inorder traversal. In the above example, we recur for following two arrays. // Recur for following arrays to construct the left subtree In[] = {4, 8, 10, 12, 14} level[] = {8, 4, 12, 10, 14} Similarly, we recur for following two arrays and construct the right subtree. // Recur for following arrays to construct the right subtree In[] = {22} level[] = {22} Following is the implementation of the above approach: C++ Java Python3 C# Javascript /* program to construct tree using inorder and levelorder * traversals */#include <bits/stdc++.h>using namespace std; /* A binary tree node */struct Node { int key; struct Node *left, *right;}; /* Function to find index of value in arr[start...end] */int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // n is size of level[], m is size of in[] and m < n. This// function extracts keys from level[] which are present in// in[]. The order of extracted keys must be maintainedint* extrackKeys(int in[], int level[], int m, int n){ int *newlevel = new int[m], j = 0; for (int i = 0; i < n; i++) if (search(in, 0, m - 1, level[i]) != -1) newlevel[j] = level[i], j++; return newlevel;} /* function that allocates a new node with the given key */Node* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node);} /* Recursive function to construct binary tree of size n from Inorder traversal in[] and Level Order traversal level[]. inStrt and inEnd are start and end indexes of array in[] Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and levelorder do not form a tree */Node* buildTree(int in[], int level[], int inStrt, int inEnd, int n){ // If start index is more than the end index if (inStrt > inEnd) return NULL; /* The first node in level order traversal is root */ Node* root = newNode(level[0]); /* If this node has no children then return */ if (inStrt == inEnd) return root; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, root->key); // Extract left subtree keys from level order traversal int* llevel = extrackKeys(in, level, inIndex, n); // Extract right subtree keys from level order traversal int* rlevel = extrackKeys(in + inIndex + 1, level, n - 1, n); /* construct left and right subtrees */ root->left = buildTree(in, llevel, inStrt, inIndex - 1, inIndex - inStrt); root->right = buildTree(in, rlevel, inIndex + 1, inEnd, inEnd - inIndex); // Free memory to avoid memory leak delete[] llevel; delete[] rlevel; return root;} /* utility function to print inorder traversal of binary * tree */void printInorder(Node* node){ if (node == NULL) return; printInorder(node->left); cout << node->key << " "; printInorder(node->right);} /* Driver program to test above functions */int main(){ int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, level, 0, n - 1, n); /* Let us test the built tree by printing Inorder * traversal */ cout << "Inorder traversal of the constructed tree is " "\n"; printInorder(root); return 0;} // Java program to construct a tree from level order and// and inorder traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } public void setLeft(Node left) { this.left = left; } public void setRight(Node right) { this.right = right; }} class Tree { Node root; Node buildTree(int in[], int level[]) { Node startnode = null; return constructTree(startnode, level, in, 0, in.length - 1); } Node constructTree(Node startNode, int[] levelOrder, int[] inOrder, int inStart, int inEnd) { // if start index is more than end index if (inStart > inEnd) return null; if (inStart == inEnd) return new Node(inOrder[inStart]); boolean found = false; int index = 0; // it represents the index in inOrder array of // element that appear first in levelOrder array. for (int i = 0; i < levelOrder.length - 1; i++) { int data = levelOrder[i]; for (int j = inStart; j < inEnd; j++) { if (data == inOrder[j]) { startNode = new Node(data); index = j; found = true; break; } } if (found == true) break; } // elements present before index are part of left // child of startNode. elements present after index // are part of right child of startNode. startNode.setLeft( constructTree(startNode, levelOrder, inOrder, inStart, index - 1)); startNode.setRight( constructTree(startNode, levelOrder, inOrder, index + 1, inEnd)); return startNode; } /* Utility function to print inorder traversal of binary * tree */ void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } // Driver program to test the above functions public static void main(String args[]) { Tree tree = new Tree(); int in[] = new int[] { 4, 8, 10, 12, 14, 20, 22 }; int level[] = new int[] { 20, 8, 22, 4, 12, 10, 14 }; int n = in.length; Node node = tree.buildTree(in, level); /* Let us test the built tree by printing Inorder * traversal */ System.out.print( "Inorder traversal of the constructed tree is "); tree.printInorder(node); }} // This code has been contributed by Mayank Jaiswal # Python program to construct tree using# inorder and level order traversals # A binary tree node class Node: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None """Recursive function to construct binary tree of size n fromInorder traversal ino[] and Level Order traversal level[].The function doesn't do any error checking for caseswhere inorder and levelorder do not form a tree """ def buildTree(level, ino): # If ino array is not empty if ino: # Check if that element exist in level order for i in range(0, len(level)): if level[i] in ino: # Create a new node with # the matched element node = Node(level[i]) # Get the index of the matched element # in level order array io_index = ino.index(level[i]) break # Construct left and right subtree node.left = buildTree(level, ino[0:io_index]) node.right = buildTree(level, ino[io_index + 1:len(ino)]) return node else: return None def printInorder(node): if node is None: return # first recur on left child printInorder(node.left) # then print the data of node print(node.data, end=" ") # now recur on right child printInorder(node.right) # Driver code levelorder = [20, 8, 22, 4, 12, 10, 14]inorder = [4, 8, 10, 12, 14, 20, 22] ino_len = len(inorder)root = buildTree(levelorder, inorder) # Let us test the build tree by# printing Inorder traversalprint("Inorder traversal of the constructed tree is")printInorder(root) # This code is contributed by 'Vaibhav Kumar' // C# program to construct a tree from// level order and and inorder traversalusing System; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; } public virtual Node Left { set { this.left = value; } } public virtual Node Right { set { this.right = value; } }} class GFG { public Node root; public virtual Node buildTree(int[] arr, int[] level) { Node startnode = null; return constructTree(startnode, level, arr, 0, arr.Length - 1); } public virtual Node constructTree(Node startNode, int[] levelOrder, int[] inOrder, int inStart, int inEnd) { // if start index is more than end index if (inStart > inEnd) { return null; } if (inStart == inEnd) { return new Node(inOrder[inStart]); } bool found = false; int index = 0; // it represents the index in inOrder // array of element that appear first // in levelOrder array. for (int i = 0; i < levelOrder.Length - 1; i++) { int data = levelOrder[i]; for (int j = inStart; j < inEnd; j++) { if (data == inOrder[j]) { startNode = new Node(data); index = j; found = true; break; } } if (found == true) { break; } } // elements present before index are // part of left child of startNode. // elements present after index are // part of right child of startNode. startNode.Left = constructTree(startNode, levelOrder, inOrder, inStart, index - 1); startNode.Right = constructTree(startNode, levelOrder, inOrder, index + 1, inEnd); return startNode; } /* Utility function to print inorder traversal of binary tree */ public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver Code public static void Main(string[] args) { GFG tree = new GFG(); int[] arr = new int[] { 4, 8, 10, 12, 14, 20, 22 }; int[] level = new int[] { 20, 8, 22, 4, 12, 10, 14 }; int n = arr.Length; Node node = tree.buildTree(arr, level); /* Let us test the built tree by printing Inorder traversal */ Console.Write("Inorder traversal of the " + "constructed tree is " + "\n"); tree.printInorder(node); }} // This code is contributed by Shrikant13 <script> // inorder and level order traversals// A binary tree nodeclass Node{ // Constructor to create a new node constructor(key){ this.data = key this.left = null this.right = null } } // Recursive function to construct binary tree of size n from// Inorder traversal ino[] and Level Order traversal level[].// The function doesn't do any error checking for cases// where inorder and levelorder do not form a treefunction buildTree(level, ino){ // If ino array is not empty if(ino.length > 0) { // Check if that element exist in level order let io_index; let node; for (let i = 0; i < level.length; i++) { if(ino.indexOf(level[i]) !== -1) { // Create a new node with // the matched element node = new Node(level[i]) // Get the index of the matched element // in level order array io_index = ino.indexOf(level[i]); break } } // Construct left and right subtree node.left = buildTree(level, ino.slice(0,io_index)) node.right = buildTree(level, ino.slice(io_index+1,ino.length)) return node } else return null; } function printInorder(node){ if(node === null) return // first recur on left child printInorder(node.left) // then print the data of node document.write(node.data," ") // now recur on right child printInorder(node.right)} // Driver codelet levelorder = [20, 8, 22, 4, 12, 10, 14];let inorder = [4, 8, 10, 12, 14, 20, 22]; root = buildTree(levelorder, inorder); // Let us test the build tree by// printing Inorder traversaldocument.write("Inorder traversal of the constructed tree is","</br>");printInorder(root); // This code is contributed by shinjanpatra </script> Output: Inorder traversal of the constructed tree is 4 8 10 12 14 20 22 An upper bound on time complexity of above method is O(n3). In the main recursive function, extractNodes() is called which takes O(n2) time.The code can be optimized in many ways and there may be better solutions. Construct a tree from Inorder and Level order traversals | Set 2This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 gjaiswal108 leviosa317 arunsathyanpkd aneeketmangal ruhelaa48 simranarora5sos shinjanpatra tree-level-order Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Write a Program to Find the Maximum Depth or Height of a Tree A program to check if a binary tree is BST or not Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree
[ { "code": null, "e": 37758, "s": 37730, "text": "\n21 Feb, 2022" }, { "code": null, "e": 37895, "s": 37758, "text": "Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem." }, { "code": null, "e": 38250, "s": 37895, "text": "Input: Two arrays that represent Inorder\n and level order traversals of a \n Binary Tree\nin[] = {4, 8, 10, 12, 14, 20, 22};\nlevel[] = {20, 8, 22, 4, 12, 10, 14};\n\nOutput: Construct the tree represented \n by the two arrays.\n For the above two arrays, the \n constructed tree is shown in \n the diagram on right side" }, { "code": null, "e": 38374, "s": 38250, "text": "The following post can be considered as a prerequisite for this. Construct Tree from given Inorder and Preorder traversals " }, { "code": null, "e": 38780, "s": 38374, "text": "Let us consider the above example.in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14};In a Levelorder sequence, the first element is the root of the tree. So we know ’20’ is root for given sequences. By searching ’20’ in Inorder sequence, we can find out all elements on left side of ‘20’ are in left subtree and elements on right are in right subtree. So we know below structure now. " }, { "code": null, "e": 38856, "s": 38780, "text": " 20\n / \\\n / \\ \n {4,8,10,12,14} {22}" }, { "code": null, "e": 39349, "s": 38856, "text": "Let us call {4,8,10,12,14} as left subarray in Inorder traversal and {22} as right subarray in Inorder traversal. In level order traversal, keys of left and right subtrees are not consecutive. So we extract all nodes from level order traversal which are in left subarray of Inorder traversal. To construct the left subtree of root, we recur for the extracted elements from level order traversal and left subarray of inorder traversal. In the above example, we recur for following two arrays. " }, { "code": null, "e": 39467, "s": 39349, "text": "// Recur for following arrays to construct the left subtree\nIn[] = {4, 8, 10, 12, 14}\nlevel[] = {8, 4, 12, 10, 14}" }, { "code": null, "e": 39545, "s": 39467, "text": "Similarly, we recur for following two arrays and construct the right subtree." }, { "code": null, "e": 39636, "s": 39545, "text": "// Recur for following arrays to construct the right subtree\nIn[] = {22}\nlevel[] = {22}" }, { "code": null, "e": 39692, "s": 39636, "text": "Following is the implementation of the above approach: " }, { "code": null, "e": 39696, "s": 39692, "text": "C++" }, { "code": null, "e": 39701, "s": 39696, "text": "Java" }, { "code": null, "e": 39709, "s": 39701, "text": "Python3" }, { "code": null, "e": 39712, "s": 39709, "text": "C#" }, { "code": null, "e": 39723, "s": 39712, "text": "Javascript" }, { "code": "/* program to construct tree using inorder and levelorder * traversals */#include <bits/stdc++.h>using namespace std; /* A binary tree node */struct Node { int key; struct Node *left, *right;}; /* Function to find index of value in arr[start...end] */int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // n is size of level[], m is size of in[] and m < n. This// function extracts keys from level[] which are present in// in[]. The order of extracted keys must be maintainedint* extrackKeys(int in[], int level[], int m, int n){ int *newlevel = new int[m], j = 0; for (int i = 0; i < n; i++) if (search(in, 0, m - 1, level[i]) != -1) newlevel[j] = level[i], j++; return newlevel;} /* function that allocates a new node with the given key */Node* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node);} /* Recursive function to construct binary tree of size n from Inorder traversal in[] and Level Order traversal level[]. inStrt and inEnd are start and end indexes of array in[] Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and levelorder do not form a tree */Node* buildTree(int in[], int level[], int inStrt, int inEnd, int n){ // If start index is more than the end index if (inStrt > inEnd) return NULL; /* The first node in level order traversal is root */ Node* root = newNode(level[0]); /* If this node has no children then return */ if (inStrt == inEnd) return root; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, root->key); // Extract left subtree keys from level order traversal int* llevel = extrackKeys(in, level, inIndex, n); // Extract right subtree keys from level order traversal int* rlevel = extrackKeys(in + inIndex + 1, level, n - 1, n); /* construct left and right subtrees */ root->left = buildTree(in, llevel, inStrt, inIndex - 1, inIndex - inStrt); root->right = buildTree(in, rlevel, inIndex + 1, inEnd, inEnd - inIndex); // Free memory to avoid memory leak delete[] llevel; delete[] rlevel; return root;} /* utility function to print inorder traversal of binary * tree */void printInorder(Node* node){ if (node == NULL) return; printInorder(node->left); cout << node->key << \" \"; printInorder(node->right);} /* Driver program to test above functions */int main(){ int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, level, 0, n - 1, n); /* Let us test the built tree by printing Inorder * traversal */ cout << \"Inorder traversal of the constructed tree is \" \"\\n\"; printInorder(root); return 0;}", "e": 42803, "s": 39723, "text": null }, { "code": "// Java program to construct a tree from level order and// and inorder traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } public void setLeft(Node left) { this.left = left; } public void setRight(Node right) { this.right = right; }} class Tree { Node root; Node buildTree(int in[], int level[]) { Node startnode = null; return constructTree(startnode, level, in, 0, in.length - 1); } Node constructTree(Node startNode, int[] levelOrder, int[] inOrder, int inStart, int inEnd) { // if start index is more than end index if (inStart > inEnd) return null; if (inStart == inEnd) return new Node(inOrder[inStart]); boolean found = false; int index = 0; // it represents the index in inOrder array of // element that appear first in levelOrder array. for (int i = 0; i < levelOrder.length - 1; i++) { int data = levelOrder[i]; for (int j = inStart; j < inEnd; j++) { if (data == inOrder[j]) { startNode = new Node(data); index = j; found = true; break; } } if (found == true) break; } // elements present before index are part of left // child of startNode. elements present after index // are part of right child of startNode. startNode.setLeft( constructTree(startNode, levelOrder, inOrder, inStart, index - 1)); startNode.setRight( constructTree(startNode, levelOrder, inOrder, index + 1, inEnd)); return startNode; } /* Utility function to print inorder traversal of binary * tree */ void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } // Driver program to test the above functions public static void main(String args[]) { Tree tree = new Tree(); int in[] = new int[] { 4, 8, 10, 12, 14, 20, 22 }; int level[] = new int[] { 20, 8, 22, 4, 12, 10, 14 }; int n = in.length; Node node = tree.buildTree(in, level); /* Let us test the built tree by printing Inorder * traversal */ System.out.print( \"Inorder traversal of the constructed tree is \"); tree.printInorder(node); }} // This code has been contributed by Mayank Jaiswal", "e": 45564, "s": 42803, "text": null }, { "code": "# Python program to construct tree using# inorder and level order traversals # A binary tree node class Node: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None \"\"\"Recursive function to construct binary tree of size n fromInorder traversal ino[] and Level Order traversal level[].The function doesn't do any error checking for caseswhere inorder and levelorder do not form a tree \"\"\" def buildTree(level, ino): # If ino array is not empty if ino: # Check if that element exist in level order for i in range(0, len(level)): if level[i] in ino: # Create a new node with # the matched element node = Node(level[i]) # Get the index of the matched element # in level order array io_index = ino.index(level[i]) break # Construct left and right subtree node.left = buildTree(level, ino[0:io_index]) node.right = buildTree(level, ino[io_index + 1:len(ino)]) return node else: return None def printInorder(node): if node is None: return # first recur on left child printInorder(node.left) # then print the data of node print(node.data, end=\" \") # now recur on right child printInorder(node.right) # Driver code levelorder = [20, 8, 22, 4, 12, 10, 14]inorder = [4, 8, 10, 12, 14, 20, 22] ino_len = len(inorder)root = buildTree(levelorder, inorder) # Let us test the build tree by# printing Inorder traversalprint(\"Inorder traversal of the constructed tree is\")printInorder(root) # This code is contributed by 'Vaibhav Kumar'", "e": 47284, "s": 45564, "text": null }, { "code": "// C# program to construct a tree from// level order and and inorder traversalusing System; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; } public virtual Node Left { set { this.left = value; } } public virtual Node Right { set { this.right = value; } }} class GFG { public Node root; public virtual Node buildTree(int[] arr, int[] level) { Node startnode = null; return constructTree(startnode, level, arr, 0, arr.Length - 1); } public virtual Node constructTree(Node startNode, int[] levelOrder, int[] inOrder, int inStart, int inEnd) { // if start index is more than end index if (inStart > inEnd) { return null; } if (inStart == inEnd) { return new Node(inOrder[inStart]); } bool found = false; int index = 0; // it represents the index in inOrder // array of element that appear first // in levelOrder array. for (int i = 0; i < levelOrder.Length - 1; i++) { int data = levelOrder[i]; for (int j = inStart; j < inEnd; j++) { if (data == inOrder[j]) { startNode = new Node(data); index = j; found = true; break; } } if (found == true) { break; } } // elements present before index are // part of left child of startNode. // elements present after index are // part of right child of startNode. startNode.Left = constructTree(startNode, levelOrder, inOrder, inStart, index - 1); startNode.Right = constructTree(startNode, levelOrder, inOrder, index + 1, inEnd); return startNode; } /* Utility function to print inorder traversal of binary tree */ public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver Code public static void Main(string[] args) { GFG tree = new GFG(); int[] arr = new int[] { 4, 8, 10, 12, 14, 20, 22 }; int[] level = new int[] { 20, 8, 22, 4, 12, 10, 14 }; int n = arr.Length; Node node = tree.buildTree(arr, level); /* Let us test the built tree by printing Inorder traversal */ Console.Write(\"Inorder traversal of the \" + \"constructed tree is \" + \"\\n\"); tree.printInorder(node); }} // This code is contributed by Shrikant13", "e": 50200, "s": 47284, "text": null }, { "code": "<script> // inorder and level order traversals// A binary tree nodeclass Node{ // Constructor to create a new node constructor(key){ this.data = key this.left = null this.right = null } } // Recursive function to construct binary tree of size n from// Inorder traversal ino[] and Level Order traversal level[].// The function doesn't do any error checking for cases// where inorder and levelorder do not form a treefunction buildTree(level, ino){ // If ino array is not empty if(ino.length > 0) { // Check if that element exist in level order let io_index; let node; for (let i = 0; i < level.length; i++) { if(ino.indexOf(level[i]) !== -1) { // Create a new node with // the matched element node = new Node(level[i]) // Get the index of the matched element // in level order array io_index = ino.indexOf(level[i]); break } } // Construct left and right subtree node.left = buildTree(level, ino.slice(0,io_index)) node.right = buildTree(level, ino.slice(io_index+1,ino.length)) return node } else return null; } function printInorder(node){ if(node === null) return // first recur on left child printInorder(node.left) // then print the data of node document.write(node.data,\" \") // now recur on right child printInorder(node.right)} // Driver codelet levelorder = [20, 8, 22, 4, 12, 10, 14];let inorder = [4, 8, 10, 12, 14, 20, 22]; root = buildTree(levelorder, inorder); // Let us test the build tree by// printing Inorder traversaldocument.write(\"Inorder traversal of the constructed tree is\",\"</br>\");printInorder(root); // This code is contributed by shinjanpatra </script>", "e": 52097, "s": 50200, "text": null }, { "code": null, "e": 52106, "s": 52097, "text": "Output: " }, { "code": null, "e": 52170, "s": 52106, "text": "Inorder traversal of the constructed tree is\n4 8 10 12 14 20 22" }, { "code": null, "e": 52617, "s": 52170, "text": "An upper bound on time complexity of above method is O(n3). In the main recursive function, extractNodes() is called which takes O(n2) time.The code can be optimized in many ways and there may be better solutions. Construct a tree from Inorder and Level order traversals | Set 2This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 52629, "s": 52617, "text": "shrikanth13" }, { "code": null, "e": 52641, "s": 52629, "text": "gjaiswal108" }, { "code": null, "e": 52652, "s": 52641, "text": "leviosa317" }, { "code": null, "e": 52667, "s": 52652, "text": "arunsathyanpkd" }, { "code": null, "e": 52681, "s": 52667, "text": "aneeketmangal" }, { "code": null, "e": 52691, "s": 52681, "text": "ruhelaa48" }, { "code": null, "e": 52707, "s": 52691, "text": "simranarora5sos" }, { "code": null, "e": 52720, "s": 52707, "text": "shinjanpatra" }, { "code": null, "e": 52737, "s": 52720, "text": "tree-level-order" }, { "code": null, "e": 52742, "s": 52737, "text": "Tree" }, { "code": null, "e": 52747, "s": 52742, "text": "Tree" }, { "code": null, "e": 52845, "s": 52747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52879, "s": 52845, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 52908, "s": 52879, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 52970, "s": 52908, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 53020, "s": 52970, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 53034, "s": 53020, "text": "Decision Tree" }, { "code": null, "e": 53117, "s": 53034, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 53153, "s": 53117, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 53201, "s": 53153, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
Java program to display Hostname and IP address
To display Hostname and IP address in Java, the code is as follows − Live Demo import java.net.*; public class Demo{ public static void main(String[] args){ try{ InetAddress my_address = InetAddress.getLocalHost(); System.out.println("The IP address is : " + my_address.getHostAddress()); System.out.println("The host name is : " + my_address.getHostName()); } catch (UnknownHostException e){ System.out.println( "Couldn't find the local address."); } } } The IP address is : 127.0.0.1 The host name is : jdoodle A class named Demo contains the main function. In this main function, a ‘try’ and ‘catch’ block is defined. In the ‘try’ block, an instance of InetAddress is created and the ‘getLocalHost’ function is used to get the Host address and host name of the InetAddress instance. In case one of the attributes is not found, the ‘catch’ block defines catching the exception and printing the relevant message on the console.
[ { "code": null, "e": 1131, "s": 1062, "text": "To display Hostname and IP address in Java, the code is as follows −" }, { "code": null, "e": 1142, "s": 1131, "text": " Live Demo" }, { "code": null, "e": 1585, "s": 1142, "text": "import java.net.*;\npublic class Demo{\n public static void main(String[] args){\n try{\n InetAddress my_address = InetAddress.getLocalHost();\n System.out.println(\"The IP address is : \" + my_address.getHostAddress());\n System.out.println(\"The host name is : \" + my_address.getHostName());\n }\n catch (UnknownHostException e){\n System.out.println( \"Couldn't find the local address.\");\n }\n }\n}" }, { "code": null, "e": 1642, "s": 1585, "text": "The IP address is : 127.0.0.1\nThe host name is : jdoodle" }, { "code": null, "e": 2058, "s": 1642, "text": "A class named Demo contains the main function. In this main function, a ‘try’ and ‘catch’ block is defined. In the ‘try’ block, an instance of InetAddress is created and the ‘getLocalHost’ function is used to get the Host address and host name of the InetAddress instance. In case one of the attributes is not found, the ‘catch’ block defines catching the exception and printing the relevant message on the console." } ]
How to display current connection info in MySQL?
MySQL provides many functions that give the current connection information. For instance, to know about the current user, use the user() function. mysql> SELECT CURRENT_USER(); Here is the output that displays the name of the current user. +----------------+ | CURRENT_USER() | +----------------+ | root@% | +----------------+ 1 row in set (0.00 sec) In the above, % tells us about localhost. To check the current connection id, use the following method − mysql> SELECT CONNECTION_ID(); The following is the output that shows the current connection id. +-----------------+ | CONNECTION_ID() | +-----------------+ | 8 | +-----------------+ 1 row in set (0.02 sec) The following is the syntax to check all the current information with a single command. mysql> status; The following is the output − -------------- C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe Ver 8.0.12 for Win64 on x86_64 (MySQL Community Server - GPL) Connection id: 8 Current database: business Current user: root@localhost SSL: Cipher in use is DHE-RSA-AES128-GCM-SHA256 Using delimiter: ; Server version: 8.0.12 MySQL Community Server - GPL Protocol version: 10 Connection: localhost via TCP/IP Server characterset: utf8mb4 Db characterset: utf8mb4 Client characterset: cp850 Conn. characterset: cp850 TCP port: 3306 Uptime: 1 hour 11 min 24 sec Threads: 2 Questions: 26 Slow queries: 0 Opens: 129 Flush tables: 2 Open tables: 105 Queries per second avg: 0.006 --------------
[ { "code": null, "e": 1209, "s": 1062, "text": "MySQL provides many functions that give the current connection information. For instance, to know about the current user, use the user() function." }, { "code": null, "e": 1240, "s": 1209, "text": "mysql> SELECT CURRENT_USER();\n" }, { "code": null, "e": 1303, "s": 1240, "text": "Here is the output that displays the name of the current user." }, { "code": null, "e": 1423, "s": 1303, "text": "+----------------+\n| CURRENT_USER() |\n+----------------+\n| root@% |\n+----------------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 1465, "s": 1423, "text": "In the above, % tells us about localhost." }, { "code": null, "e": 1528, "s": 1465, "text": "To check the current connection id, use the following method −" }, { "code": null, "e": 1559, "s": 1528, "text": "mysql> SELECT CONNECTION_ID();" }, { "code": null, "e": 1625, "s": 1559, "text": "The following is the output that shows the current connection id." }, { "code": null, "e": 1750, "s": 1625, "text": "+-----------------+\n| CONNECTION_ID() |\n+-----------------+\n| 8 |\n+-----------------+\n1 row in set (0.02 sec)\n" }, { "code": null, "e": 1838, "s": 1750, "text": "The following is the syntax to check all the current information with a single command." }, { "code": null, "e": 1853, "s": 1838, "text": "mysql> status;" }, { "code": null, "e": 1883, "s": 1853, "text": "The following is the output −" }, { "code": null, "e": 2675, "s": 1883, "text": "--------------\nC:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe Ver 8.0.12 for Win64 on x86_64 (MySQL Community Server - GPL)\n\nConnection id: 8\nCurrent database: business\nCurrent user: root@localhost\nSSL: Cipher in use is DHE-RSA-AES128-GCM-SHA256\nUsing delimiter: ;\nServer version: 8.0.12 MySQL Community Server - GPL\nProtocol version: 10\nConnection: localhost via TCP/IP\nServer characterset: utf8mb4\nDb characterset: utf8mb4\nClient characterset: cp850\nConn. characterset: cp850\nTCP port: 3306\nUptime: 1 hour 11 min 24 sec\n\nThreads: 2 Questions: 26 Slow queries: 0 Opens: 129 Flush tables: 2 Open tables: 105 Queries per second avg: 0.006\n--------------\n" } ]
Distributed Cache in Hadoop MapReduce - GeeksforGeeks
19 May, 2019 Hadoop’s MapReduce framework provides the facility to cache small to moderate read-only files such as text files, zip files, jar files etc. and broadcast them to all the Datanodes(worker-nodes) where MapReduce job is running. Each Datanode gets a copy of the file(local-copy) which is sent through Distributed Cache. When the job is finished these files are deleted from the DataNodes. Why to cache a file? There are some files which are required by MapReduce jobs so rather than reading every time from HDFS (increases seek time thus latency) for let’s say 100 times (if 100 Mappers are running) we just send the copy of the file to all the Datanode once. Let’s see an example where we count the words from lyrics.txt except the words present in stopWords.txt. You can find these files in here. Prerequisites: 1. Copy both the files from the local filesystem to HDFS. bin/hdfs dfs -put ../Desktop/lyrics.txt /geeksInput // this file will be cached bin/hdfs dfs -put ../Desktop/stopWords.txt /cached_Geeks 2. Get the NameNode server address. Since the file has to be accessed via URI(Uniform Resource Identifier) we need this address. It can be found in core-site.xml Hadoop_Home_dir/etc/hadoop/core-site.xml In my PC it’s hdfs://localhost:9000 it may vary in your PC. Mapper Code: package word_count_DC; import java.io.*;import java.util.*;import java.net.URI; import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path; public class Cached_Word_Count extends Mapper<LongWritable, Text, Text, LongWritable> { ArrayList<String> stopWords = null; public void setup(Context context) throws IOException, InterruptedException { stopWords = new ArrayList<String>(); URI[] cacheFiles = context.getCacheFiles(); if (cacheFiles != null && cacheFiles.length > 0) { try { String line = ""; // Create a FileSystem object and pass the // configuration object in it. The FileSystem // is an abstract base class for a fairly generic // filesystem. All user code that may potentially // use the Hadoop Distributed File System should // be written to use a FileSystem object. FileSystem fs = FileSystem.get(context.getConfiguration()); Path getFilePath = new Path(cacheFiles[0].toString()); // We open the file using FileSystem object, // convert the input byte stream to character // streams using InputStreamReader and wrap it // in BufferedReader to make it more efficient BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(getFilePath))); while ((line = reader.readLine()) != null) { String[] words = line.split(" "); for (int i = 0; i < words.length; i++) { // add the words to ArrayList stopWords.add(words[i]); } } } catch (Exception e) { System.out.println("Unable to read the File"); System.exit(1); } } } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String words[] = value.toString().split(" "); for (int i = 0; i < words.length; i++) { // removing all special symbols // and converting it to lowerCase String temp = words[i].replaceAll("[?, '()]", "").toLowerCase(); // if not present in ArrayList we write if (!stopWords.contains(temp)) { context.write(new Text(temp), new LongWritable(1)); } } }} Reducer Code: package word_count_DC; import java.io.*;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Reducer; public class Cached_Reducer extends Reducer<Text, LongWritable, Text, LongWritable> { public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { long sum = 0; for (LongWritable val : values) { sum += val.get(); } context.write(key, new LongWritable(sum)); }} Driver Code: package word_count_DC; import java.io.*;import java.net.URI;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.util.GenericOptionsParser; public class Driver { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Error: Give only two paths for <input> <output>"); System.exit(1); } Job job = Job.getInstance(conf, "Distributed Cache"); job.setJarByClass(Driver.class); job.setMapperClass(Cached_Word_Count.class); job.setReducerClass(Cached_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); try { // the complete URI(Uniform Resource // Identifier) file path in Hdfs job.addCacheFile(new URI("hdfs://localhost:9000/cached_Geeks/stopWords.txt")); } catch (Exception e) { System.out.println("File Not Added"); System.exit(1); } FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); // throws ClassNotFoundException, so handle it System.exit(job.waitForCompletion(true) ? 0 : 1); }} How to Execute the Code? Export the project as a jar file and copy to your Ubuntu desktop as distributedExample.jarStart your Hadoop services. Go inside hadoop_home_dir and in terminal typesbin/start-all.sh Run the jar filebin/yarn jar jar_file_path packageName.Driver_Class_Name inputFilePath outputFilePathbin/yarn jar ../Desktop/distributedExample.jar word_count_DC.Driver /geeksInput /geeksOutputOutput:// will print the words starting with t bin/hdfs dfs -cat /geeksOutput/part* | grep ^t In the output, we can observe there is no the or to words which we wanted to ignore. Export the project as a jar file and copy to your Ubuntu desktop as distributedExample.jar Start your Hadoop services. Go inside hadoop_home_dir and in terminal typesbin/start-all.sh sbin/start-all.sh Run the jar filebin/yarn jar jar_file_path packageName.Driver_Class_Name inputFilePath outputFilePathbin/yarn jar ../Desktop/distributedExample.jar word_count_DC.Driver /geeksInput /geeksOutputOutput:// will print the words starting with t bin/hdfs dfs -cat /geeksOutput/part* | grep ^t In the output, we can observe there is no the or to words which we wanted to ignore. bin/yarn jar jar_file_path packageName.Driver_Class_Name inputFilePath outputFilePath bin/yarn jar ../Desktop/distributedExample.jar word_count_DC.Driver /geeksInput /geeksOutput Output: // will print the words starting with t bin/hdfs dfs -cat /geeksOutput/part* | grep ^t In the output, we can observe there is no the or to words which we wanted to ignore. Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create Table in Hive? Hadoop - Schedulers and Types of Schedulers Hive - Alter Table Import and Export Data using SQOOP MapReduce - Understanding With Real-Life Example Hadoop - File Blocks and Replication Factor MapReduce - Combiners Difference Between Hadoop 2.x vs Hadoop 3.x Hadoop - Pros and Cons Difference Between HDFS and HBase
[ { "code": null, "e": 24372, "s": 24344, "text": "\n19 May, 2019" }, { "code": null, "e": 24758, "s": 24372, "text": "Hadoop’s MapReduce framework provides the facility to cache small to moderate read-only files such as text files, zip files, jar files etc. and broadcast them to all the Datanodes(worker-nodes) where MapReduce job is running. Each Datanode gets a copy of the file(local-copy) which is sent through Distributed Cache. When the job is finished these files are deleted from the DataNodes." }, { "code": null, "e": 24779, "s": 24758, "text": "Why to cache a file?" }, { "code": null, "e": 25029, "s": 24779, "text": "There are some files which are required by MapReduce jobs so rather than reading every time from HDFS (increases seek time thus latency) for let’s say 100 times (if 100 Mappers are running) we just send the copy of the file to all the Datanode once." }, { "code": null, "e": 25168, "s": 25029, "text": "Let’s see an example where we count the words from lyrics.txt except the words present in stopWords.txt. You can find these files in here." }, { "code": null, "e": 25183, "s": 25168, "text": "Prerequisites:" }, { "code": null, "e": 25241, "s": 25183, "text": "1. Copy both the files from the local filesystem to HDFS." }, { "code": null, "e": 25381, "s": 25241, "text": "bin/hdfs dfs -put ../Desktop/lyrics.txt /geeksInput\n\n// this file will be cached\nbin/hdfs dfs -put ../Desktop/stopWords.txt /cached_Geeks\n" }, { "code": null, "e": 25543, "s": 25381, "text": "2. Get the NameNode server address. Since the file has to be accessed via URI(Uniform Resource Identifier) we need this address. It can be found in core-site.xml" }, { "code": null, "e": 25585, "s": 25543, "text": "Hadoop_Home_dir/etc/hadoop/core-site.xml\n" }, { "code": null, "e": 25645, "s": 25585, "text": "In my PC it’s hdfs://localhost:9000 it may vary in your PC." }, { "code": null, "e": 25658, "s": 25645, "text": "Mapper Code:" }, { "code": "package word_count_DC; import java.io.*;import java.util.*;import java.net.URI; import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path; public class Cached_Word_Count extends Mapper<LongWritable, Text, Text, LongWritable> { ArrayList<String> stopWords = null; public void setup(Context context) throws IOException, InterruptedException { stopWords = new ArrayList<String>(); URI[] cacheFiles = context.getCacheFiles(); if (cacheFiles != null && cacheFiles.length > 0) { try { String line = \"\"; // Create a FileSystem object and pass the // configuration object in it. The FileSystem // is an abstract base class for a fairly generic // filesystem. All user code that may potentially // use the Hadoop Distributed File System should // be written to use a FileSystem object. FileSystem fs = FileSystem.get(context.getConfiguration()); Path getFilePath = new Path(cacheFiles[0].toString()); // We open the file using FileSystem object, // convert the input byte stream to character // streams using InputStreamReader and wrap it // in BufferedReader to make it more efficient BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(getFilePath))); while ((line = reader.readLine()) != null) { String[] words = line.split(\" \"); for (int i = 0; i < words.length; i++) { // add the words to ArrayList stopWords.add(words[i]); } } } catch (Exception e) { System.out.println(\"Unable to read the File\"); System.exit(1); } } } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String words[] = value.toString().split(\" \"); for (int i = 0; i < words.length; i++) { // removing all special symbols // and converting it to lowerCase String temp = words[i].replaceAll(\"[?, '()]\", \"\").toLowerCase(); // if not present in ArrayList we write if (!stopWords.contains(temp)) { context.write(new Text(temp), new LongWritable(1)); } } }}", "e": 28425, "s": 25658, "text": null }, { "code": null, "e": 28439, "s": 28425, "text": "Reducer Code:" }, { "code": "package word_count_DC; import java.io.*;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Reducer; public class Cached_Reducer extends Reducer<Text, LongWritable, Text, LongWritable> { public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { long sum = 0; for (LongWritable val : values) { sum += val.get(); } context.write(key, new LongWritable(sum)); }}", "e": 29001, "s": 28439, "text": null }, { "code": null, "e": 29014, "s": 29001, "text": "Driver Code:" }, { "code": "package word_count_DC; import java.io.*;import java.net.URI;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.util.GenericOptionsParser; public class Driver { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println(\"Error: Give only two paths for <input> <output>\"); System.exit(1); } Job job = Job.getInstance(conf, \"Distributed Cache\"); job.setJarByClass(Driver.class); job.setMapperClass(Cached_Word_Count.class); job.setReducerClass(Cached_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); try { // the complete URI(Uniform Resource // Identifier) file path in Hdfs job.addCacheFile(new URI(\"hdfs://localhost:9000/cached_Geeks/stopWords.txt\")); } catch (Exception e) { System.out.println(\"File Not Added\"); System.exit(1); } FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); // throws ClassNotFoundException, so handle it System.exit(job.waitForCompletion(true) ? 0 : 1); }}", "e": 30871, "s": 29014, "text": null }, { "code": null, "e": 30896, "s": 30871, "text": "How to Execute the Code?" }, { "code": null, "e": 31451, "s": 30896, "text": "Export the project as a jar file and copy to your Ubuntu desktop as distributedExample.jarStart your Hadoop services. Go inside hadoop_home_dir and in terminal typesbin/start-all.sh\nRun the jar filebin/yarn jar jar_file_path packageName.Driver_Class_Name inputFilePath outputFilePathbin/yarn jar ../Desktop/distributedExample.jar word_count_DC.Driver /geeksInput /geeksOutputOutput:// will print the words starting with t\n\nbin/hdfs dfs -cat /geeksOutput/part* | grep ^t\nIn the output, we can observe there is no the or to words which we wanted to ignore." }, { "code": null, "e": 31542, "s": 31451, "text": "Export the project as a jar file and copy to your Ubuntu desktop as distributedExample.jar" }, { "code": null, "e": 31635, "s": 31542, "text": "Start your Hadoop services. Go inside hadoop_home_dir and in terminal typesbin/start-all.sh\n" }, { "code": null, "e": 31654, "s": 31635, "text": "sbin/start-all.sh\n" }, { "code": null, "e": 32027, "s": 31654, "text": "Run the jar filebin/yarn jar jar_file_path packageName.Driver_Class_Name inputFilePath outputFilePathbin/yarn jar ../Desktop/distributedExample.jar word_count_DC.Driver /geeksInput /geeksOutputOutput:// will print the words starting with t\n\nbin/hdfs dfs -cat /geeksOutput/part* | grep ^t\nIn the output, we can observe there is no the or to words which we wanted to ignore." }, { "code": null, "e": 32113, "s": 32027, "text": "bin/yarn jar jar_file_path packageName.Driver_Class_Name inputFilePath outputFilePath" }, { "code": null, "e": 32206, "s": 32113, "text": "bin/yarn jar ../Desktop/distributedExample.jar word_count_DC.Driver /geeksInput /geeksOutput" }, { "code": null, "e": 32214, "s": 32206, "text": "Output:" }, { "code": null, "e": 32303, "s": 32214, "text": "// will print the words starting with t\n\nbin/hdfs dfs -cat /geeksOutput/part* | grep ^t\n" }, { "code": null, "e": 32388, "s": 32303, "text": "In the output, we can observe there is no the or to words which we wanted to ignore." }, { "code": null, "e": 32395, "s": 32388, "text": "Hadoop" }, { "code": null, "e": 32402, "s": 32395, "text": "Hadoop" }, { "code": null, "e": 32500, "s": 32402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32529, "s": 32500, "text": "How to Create Table in Hive?" }, { "code": null, "e": 32573, "s": 32529, "text": "Hadoop - Schedulers and Types of Schedulers" }, { "code": null, "e": 32592, "s": 32573, "text": "Hive - Alter Table" }, { "code": null, "e": 32627, "s": 32592, "text": "Import and Export Data using SQOOP" }, { "code": null, "e": 32676, "s": 32627, "text": "MapReduce - Understanding With Real-Life Example" }, { "code": null, "e": 32720, "s": 32676, "text": "Hadoop - File Blocks and Replication Factor" }, { "code": null, "e": 32742, "s": 32720, "text": "MapReduce - Combiners" }, { "code": null, "e": 32786, "s": 32742, "text": "Difference Between Hadoop 2.x vs Hadoop 3.x" }, { "code": null, "e": 32809, "s": 32786, "text": "Hadoop - Pros and Cons" } ]
Align a flex item at the end in Bootstrap 4
Use the .align-self-end class to align flex item at the end in Bootstrap 4. The following is my div − <div class="d-flex bg-info" style="height:200px"> Now you need to set the flex items, wherein I am aligning the 3rd flex item − <div class="d-flex bg-info" style="height:200px"> <div class="p-2 border">Item 1</div> <div class="p-2 border">Item 2</div> <div class="p-2 border align-self-end">Item 3</div> <div class="p-2 border">Item 4</div> </div> You can try to run the following code to implement the align-self-end class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-3"> <h1>Align Specific Flex Item from the end</h1> <div class="d-flex bg-info" style="height:200px"> <div class="p-2 border">Item 1</div> <div class="p-2 border">Item 2</div> <div class="p-2 border align-self-end">Item 3</div> <div class="p-2 border">Item 4</div> </div> </div> </body> </html>
[ { "code": null, "e": 1138, "s": 1062, "text": "Use the .align-self-end class to align flex item at the end in Bootstrap 4." }, { "code": null, "e": 1164, "s": 1138, "text": "The following is my div −" }, { "code": null, "e": 1214, "s": 1164, "text": "<div class=\"d-flex bg-info\" style=\"height:200px\">" }, { "code": null, "e": 1292, "s": 1214, "text": "Now you need to set the flex items, wherein I am aligning the 3rd flex item −" }, { "code": null, "e": 1520, "s": 1292, "text": "<div class=\"d-flex bg-info\" style=\"height:200px\">\n <div class=\"p-2 border\">Item 1</div>\n <div class=\"p-2 border\">Item 2</div>\n <div class=\"p-2 border align-self-end\">Item 3</div>\n <div class=\"p-2 border\">Item 4</div>\n</div>" }, { "code": null, "e": 1598, "s": 1520, "text": "You can try to run the following code to implement the align-self-end class −" }, { "code": null, "e": 1608, "s": 1598, "text": "Live Demo" }, { "code": null, "e": 2470, "s": 1608, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container mt-3\">\n <h1>Align Specific Flex Item from the end</h1>\n <div class=\"d-flex bg-info\" style=\"height:200px\">\n <div class=\"p-2 border\">Item 1</div>\n <div class=\"p-2 border\">Item 2</div>\n <div class=\"p-2 border align-self-end\">Item 3</div>\n <div class=\"p-2 border\">Item 4</div>\n </div>\n </div>\n </body>\n</html>" } ]
JavaScript String - substr() Method
This method returns the characters in a string beginning at the specified location through the specified number of characters. The syntax to use substr() is as follows − string.substr(start[, length]); start − Location at which to start extracting characters (an integer between 0 and one less than the length of the string). start − Location at which to start extracting characters (an integer between 0 and one less than the length of the string). length − The number of characters to extract. length − The number of characters to extract. Note − If start is negative, substr uses it as a character index from the end of the string. The substr() method returns the new sub-string based on given parameters. Try the following example. <html> <head> <title>JavaScript String substr() Method</title> </head> <body> <script type = "text/javascript"> var str = "Apples are round, and apples are juicy."; document.write("(1,2): " + str.substr(1,2)); document.write("<br />(-2,2): " + str.substr(-2,2)); document.write("<br />(1): " + str.substr(1)); document.write("<br />(-20, 2): " + str.substr(-20,2)); document.write("<br />(20, 2): " + str.substr(20,2)); </script> </body> </html> (1,2): pp (-2,2): y. (1): pples are round, and apples are juicy. (-20, 2): nd (20, 2): d 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2593, "s": 2466, "text": "This method returns the characters in a string beginning at the specified location through the specified number of characters." }, { "code": null, "e": 2636, "s": 2593, "text": "The syntax to use substr() is as follows −" }, { "code": null, "e": 2669, "s": 2636, "text": "string.substr(start[, length]);\n" }, { "code": null, "e": 2793, "s": 2669, "text": "start − Location at which to start extracting characters (an integer between 0 and one less than the length of the string)." }, { "code": null, "e": 2917, "s": 2793, "text": "start − Location at which to start extracting characters (an integer between 0 and one less than the length of the string)." }, { "code": null, "e": 2963, "s": 2917, "text": "length − The number of characters to extract." }, { "code": null, "e": 3009, "s": 2963, "text": "length − The number of characters to extract." }, { "code": null, "e": 3102, "s": 3009, "text": "Note − If start is negative, substr uses it as a character index from the end of the string." }, { "code": null, "e": 3176, "s": 3102, "text": "The substr() method returns the new sub-string based on given parameters." }, { "code": null, "e": 3203, "s": 3176, "text": "Try the following example." }, { "code": null, "e": 3766, "s": 3203, "text": "<html>\n <head>\n <title>JavaScript String substr() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = \"Apples are round, and apples are juicy.\"; \n document.write(\"(1,2): \" + str.substr(1,2));\n document.write(\"<br />(-2,2): \" + str.substr(-2,2));\n document.write(\"<br />(1): \" + str.substr(1));\n document.write(\"<br />(-20, 2): \" + str.substr(-20,2));\n document.write(\"<br />(20, 2): \" + str.substr(20,2));\n </script> \n </body>\n</html>" }, { "code": null, "e": 3856, "s": 3766, "text": "(1,2): pp\n(-2,2): y.\n(1): pples are round, and apples are juicy.\n(-20, 2): nd\n(20, 2): d\n" }, { "code": null, "e": 3891, "s": 3856, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3905, "s": 3891, "text": " Anadi Sharma" }, { "code": null, "e": 3939, "s": 3905, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3953, "s": 3939, "text": " Lets Kode It" }, { "code": null, "e": 3988, "s": 3953, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4005, "s": 3988, "text": " Frahaan Hussain" }, { "code": null, "e": 4040, "s": 4005, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4057, "s": 4040, "text": " Frahaan Hussain" }, { "code": null, "e": 4090, "s": 4057, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4118, "s": 4090, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4152, "s": 4118, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4180, "s": 4152, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4187, "s": 4180, "text": " Print" }, { "code": null, "e": 4198, "s": 4187, "text": " Add Notes" } ]
Sort an array which contain 1 to n values - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make Apps School Guide Python Programming Learn To Make Apps All Courses TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON Events WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps School Guide Python Programming Learn To Make Apps Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Sort an array which contain 1 to n values Sort 1 to N by swapping adjacent elements Sort an array containing two types of elements Sort elements by frequency | Set 1 Sort elements by frequency | Set 2 Sort elements by frequency | Set 4 (Efficient approach using hash) Sorting Array Elements By Frequency | Set 3 (Using STL) Sort elements by frequency | Set 5 (using Java Map) Sorting a Hashmap according to values Sorting a HashMap according to keys in Java TreeMap in Java TreeSet in Java HashSet in Java HashMap in Java with Examples Internal Working of HashMap in Java Internal working of Set/HashSet in Java Merge Two Sets in Java Set in Java Map Interface in Java How to iterate any Map in Java Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Maximum and minimum of an array using minimum number of comparisons Sort an array which contain 1 to n values Sort 1 to N by swapping adjacent elements Sort an array containing two types of elements Sort elements by frequency | Set 1 Sort elements by frequency | Set 2 Sort elements by frequency | Set 4 (Efficient approach using hash) Sorting Array Elements By Frequency | Set 3 (Using STL) Sort elements by frequency | Set 5 (using Java Map) Sorting a Hashmap according to values Sorting a HashMap according to keys in Java TreeMap in Java TreeSet in Java HashSet in Java HashMap in Java with Examples Internal Working of HashMap in Java Internal working of Set/HashSet in Java Merge Two Sets in Java Set in Java Map Interface in Java How to iterate any Map in Java Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Maximum and minimum of an array using minimum number of comparisons Difficulty Level : Easy You have given an array which contain 1 to n element, your task is to sort this array in an efficient way and without replace with 1 to n numbers.Examples : Input : arr[] = {10, 7, 9, 2, 8, 3, 5, 4, 6, 1}; Output : 1 2 3 4 5 6 7 8 9 10 Native approach : Sort this array with the use of any type of sorting method. it takes O(nlogn) minimum time.Efficient approach : Replace every element with it’s position. it takes O(n) efficient time and give you the sorted array. Let’s understand this approach with the code below. C++ Java Python3 C# PHP Javascript // Efficient C++ program to sort an array of// numbers in range from 1 to n.#include <bits/stdc++.h> using namespace std; // function for sort arrayvoid sortit(int arr[], int n){ for (int i = 0; i < n; i++) { arr[i]=i+1; }} // Driver codeint main(){ int arr[] = { 10, 7, 9, 2, 8, 3, 5, 4, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // for sort an array sortit(arr, n); // for print all the element in sorted way for (int i = 0; i < n; i++) cout << arr[i] << " "; } // Efficient Java program to sort an// array of numbers in range from 1// to n.import java.io.*;import java.util.*; public class GFG { // function for sort array static void sortit(int []arr, int n) { for (int i = 0; i < n; i++) { arr[i]=i+1; } } // Driver code public static void main(String args[]) { int []arr = {10, 7, 9, 2, 8, 3, 5, 4, 6, 1}; int n = arr.length; // for sort an array sortit(arr, n); // for print all the // element in sorted way for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} // This code is contributed by Manish Shaw// (manishshaw1) # Python3 program to sort an array of# numbers in range from 1 to n. # function for sort arraydef sortit(arr,n): for i in range(n): arr[i] = i+1 # Driver codeif __name__=='__main__': arr = [10, 7, 9, 2, 8, 3, 5, 4, 6, 1 ] n = len(arr) # for sort an array sortit(arr,n) # for print all the element # in sorted way for i in range(n): print(arr[i],end=" ") # This code is contributed by# Shrikant13 // Efficient C# program to sort an array of// numbers in range from 1 to n.using System;using System.Collections.Generic; class GFG { // function for sort array static void sortit(int []arr, int n) { for (int i = 0; i < n; i++) { arr[i]=i+1; } } // Driver code public static void Main() { int []arr = {10, 7, 9, 2, 8, 3, 5, 4, 6, 1}; int n = arr.Length; // for sort an array sortit(arr, n); // for print all the // element in sorted way for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by// Manish Shaw (manishshaw1) <?php// Efficient PHP program to sort an// array of numbers in range from 1 to n. // function for sort arrayfunction sortit(&$arr, $n){ for ($i = 0; $i < $n; $i++) { $arr[$i]=$i+1; }} // Driver code$arr = array(10, 7, 9, 2, 8, 3, 5, 4, 6, 1);$n = count($arr); // for sort an arraysortit($arr, $n); // for print all the// element in sorted wayfor ($i = 0; $i < $n; $i++) echo $arr[$i]." "; //This code is contributed by Manish Shaw//(manishshaw1)?> <script> // Efficient JavaScript program to sort an array of// numbers in range from 1 to n. // function for sort arrayfunction sortit(arr, n){ for (let i = 0; i < n; i++) { arr[i]=i+1; }} // Driver code let arr = [ 10, 7, 9, 2, 8, 3, 5, 4, 6, 1 ]; let n = arr.length; // for sort an array sortit(arr, n); // for print all the element in sorted way for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi. </script> 1 2 3 4 5 6 7 8 9 10 Time Complexity: O(n) Space Complexity: O(1) manishshaw1 _Keep_Silence_ shrikanth13 surbhityagi15 prasanna1995 limited-range-elements Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Queue | Set 1 (Introduction and Array Implementation) Subset Sum Problem | DP-25
[ { "code": null, "e": 407, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses" }, { "code": null, "e": 588, "s": 407, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 673, "s": 588, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 690, "s": 673, "text": "DSA Live Classes" }, { "code": null, "e": 704, "s": 690, "text": "System Design" }, { "code": null, "e": 729, "s": 704, "text": "Java Backend Development" }, { "code": null, "e": 745, "s": 729, "text": "Full Stack LIVE" }, { "code": null, "e": 758, "s": 745, "text": "Explore More" }, { "code": null, "e": 830, "s": 758, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 846, "s": 830, "text": "DSA- Self Paced" }, { "code": null, "e": 857, "s": 846, "text": "SDE Theory" }, { "code": null, "e": 882, "s": 857, "text": "Must-Do Coding Questions" }, { "code": null, "e": 895, "s": 882, "text": "Explore More" }, { "code": null, "e": 1042, "s": 895, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1118, "s": 1042, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1142, "s": 1118, "text": "Competitive Programming" }, { "code": null, "e": 1167, "s": 1142, "text": "Data Structures with C++" }, { "code": null, "e": 1180, "s": 1167, "text": "Data Science" }, { "code": null, "e": 1193, "s": 1180, "text": "Explore More" }, { "code": null, "e": 1253, "s": 1193, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1269, "s": 1253, "text": "DSA- Self Paced" }, { "code": null, "e": 1273, "s": 1269, "text": "CIP" }, { "code": null, "e": 1293, "s": 1273, "text": "JAVA / Python / C++" }, { "code": null, "e": 1306, "s": 1293, "text": "Explore More" }, { "code": null, "e": 1369, "s": 1306, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make Apps" }, { "code": null, "e": 1382, "s": 1369, "text": "School Guide" }, { "code": null, "e": 1401, "s": 1382, "text": "Python Programming" }, { "code": null, "e": 1420, "s": 1401, "text": "Learn To Make Apps" }, { "code": null, "e": 1432, "s": 1420, "text": "All Courses" }, { "code": null, "e": 3999, "s": 1432, "text": "TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 4066, "s": 3999, "text": "Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise" }, { "code": null, "e": 4084, "s": 4066, "text": "Must Do Questions" }, { "code": null, "e": 4099, "s": 4084, "text": "DSA Topic-wise" }, { "code": null, "e": 4116, "s": 4099, "text": "DSA Company-wise" }, { "code": null, "e": 4697, "s": 4116, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 5030, "s": 4697, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 5050, "s": 5030, "text": "Asymptotic Analysis" }, { "code": null, "e": 5080, "s": 5050, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 5101, "s": 5080, "text": "Asymptotic Notations" }, { "code": null, "e": 5137, "s": 5101, "text": "Little o and little omega notations" }, { "code": null, "e": 5166, "s": 5137, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5184, "s": 5166, "text": "Analysis of Loops" }, { "code": null, "e": 5204, "s": 5184, "text": "Solving Recurrences" }, { "code": null, "e": 5223, "s": 5204, "text": "Amortized Analysis" }, { "code": null, "e": 5259, "s": 5223, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5288, "s": 5259, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5325, "s": 5288, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5352, "s": 5325, "text": "A Time Complexity Question" }, { "code": null, "e": 5373, "s": 5352, "text": "Searching Algorithms" }, { "code": null, "e": 5392, "s": 5373, "text": "Sorting Algorithms" }, { "code": null, "e": 5409, "s": 5392, "text": "Graph Algorithms" }, { "code": null, "e": 5427, "s": 5409, "text": "Pattern Searching" }, { "code": null, "e": 5448, "s": 5427, "text": "Geometric Algorithms" }, { "code": null, "e": 5461, "s": 5448, "text": "Mathematical" }, { "code": null, "e": 5480, "s": 5461, "text": "Bitwise Algorithms" }, { "code": null, "e": 5502, "s": 5480, "text": "Randomized Algorithms" }, { "code": null, "e": 5520, "s": 5502, "text": "Greedy Algorithms" }, { "code": null, "e": 5540, "s": 5520, "text": "Dynamic Programming" }, { "code": null, "e": 5559, "s": 5540, "text": "Divide and Conquer" }, { "code": null, "e": 5572, "s": 5559, "text": "Backtracking" }, { "code": null, "e": 5589, "s": 5572, "text": "Branch and Bound" }, { "code": null, "e": 5604, "s": 5589, "text": "All Algorithms" }, { "code": null, "e": 5747, "s": 5604, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5754, "s": 5747, "text": "Arrays" }, { "code": null, "e": 5766, "s": 5754, "text": "Linked List" }, { "code": null, "e": 5772, "s": 5766, "text": "Stack" }, { "code": null, "e": 5778, "s": 5772, "text": "Queue" }, { "code": null, "e": 5790, "s": 5778, "text": "Binary Tree" }, { "code": null, "e": 5809, "s": 5790, "text": "Binary Search Tree" }, { "code": null, "e": 5814, "s": 5809, "text": "Heap" }, { "code": null, "e": 5822, "s": 5814, "text": "Hashing" }, { "code": null, "e": 5828, "s": 5822, "text": "Graph" }, { "code": null, "e": 5852, "s": 5828, "text": "Advanced Data Structure" }, { "code": null, "e": 5859, "s": 5852, "text": "Matrix" }, { "code": null, "e": 5867, "s": 5859, "text": "Strings" }, { "code": null, "e": 5887, "s": 5867, "text": "All Data Structures" }, { "code": null, "e": 6107, "s": 5887, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 6127, "s": 6107, "text": "Company Preparation" }, { "code": null, "e": 6138, "s": 6127, "text": "Top Topics" }, { "code": null, "e": 6165, "s": 6138, "text": "Practice Company Questions" }, { "code": null, "e": 6187, "s": 6165, "text": "Interview Experiences" }, { "code": null, "e": 6210, "s": 6187, "text": "Experienced Interviews" }, { "code": null, "e": 6232, "s": 6210, "text": "Internship Interviews" }, { "code": null, "e": 6257, "s": 6232, "text": "Competititve Programming" }, { "code": null, "e": 6273, "s": 6257, "text": "Design Patterns" }, { "code": null, "e": 6296, "s": 6273, "text": "System Design Tutorial" }, { "code": null, "e": 6320, "s": 6296, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6401, "s": 6320, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6403, "s": 6401, "text": "C" }, { "code": null, "e": 6407, "s": 6403, "text": "C++" }, { "code": null, "e": 6412, "s": 6407, "text": "Java" }, { "code": null, "e": 6419, "s": 6412, "text": "Python" }, { "code": null, "e": 6422, "s": 6419, "text": "C#" }, { "code": null, "e": 6433, "s": 6422, "text": "JavaScript" }, { "code": null, "e": 6440, "s": 6433, "text": "jQuery" }, { "code": null, "e": 6444, "s": 6440, "text": "SQL" }, { "code": null, "e": 6448, "s": 6444, "text": "PHP" }, { "code": null, "e": 6454, "s": 6448, "text": "Scala" }, { "code": null, "e": 6459, "s": 6454, "text": "Perl" }, { "code": null, "e": 6471, "s": 6459, "text": "Go Language" }, { "code": null, "e": 6476, "s": 6471, "text": "HTML" }, { "code": null, "e": 6480, "s": 6476, "text": "CSS" }, { "code": null, "e": 6487, "s": 6480, "text": "Kotlin" }, { "code": null, "e": 6533, "s": 6487, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6550, "s": 6533, "text": "Machine Learning" }, { "code": null, "e": 6563, "s": 6550, "text": "Data Science" }, { "code": null, "e": 6730, "s": 6563, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6742, "s": 6730, "text": "Mathematics" }, { "code": null, "e": 6759, "s": 6742, "text": "Operating System" }, { "code": null, "e": 6764, "s": 6759, "text": "DBMS" }, { "code": null, "e": 6782, "s": 6764, "text": "Computer Networks" }, { "code": null, "e": 6821, "s": 6782, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6843, "s": 6821, "text": "Theory of Computation" }, { "code": null, "e": 6859, "s": 6843, "text": "Compiler Design" }, { "code": null, "e": 6873, "s": 6859, "text": "Digital Logic" }, { "code": null, "e": 6894, "s": 6873, "text": "Software Engineering" }, { "code": null, "e": 7069, "s": 6894, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 7097, "s": 7069, "text": "GATE Computer Science Notes" }, { "code": null, "e": 7115, "s": 7097, "text": "Last Minute Notes" }, { "code": null, "e": 7137, "s": 7115, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7179, "s": 7137, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7195, "s": 7179, "text": "GATE 2021 Dates" }, { "code": null, "e": 7217, "s": 7195, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7246, "s": 7217, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7320, "s": 7246, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7325, "s": 7320, "text": "HTML" }, { "code": null, "e": 7329, "s": 7325, "text": "CSS" }, { "code": null, "e": 7340, "s": 7329, "text": "JavaScript" }, { "code": null, "e": 7350, "s": 7340, "text": "AngularJS" }, { "code": null, "e": 7358, "s": 7350, "text": "ReactJS" }, { "code": null, "e": 7365, "s": 7358, "text": "NodeJS" }, { "code": null, "e": 7375, "s": 7365, "text": "Bootstrap" }, { "code": null, "e": 7382, "s": 7375, "text": "jQuery" }, { "code": null, "e": 7386, "s": 7382, "text": "PHP" }, { "code": null, "e": 7449, "s": 7386, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7474, "s": 7449, "text": "Software Design Patterns" }, { "code": null, "e": 7497, "s": 7474, "text": "System Design Tutorial" }, { "code": null, "e": 8054, "s": 7497, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8073, "s": 8054, "text": "School Programming" }, { "code": null, "e": 8165, "s": 8073, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8179, "s": 8165, "text": "Number System" }, { "code": null, "e": 8187, "s": 8179, "text": "Algebra" }, { "code": null, "e": 8200, "s": 8187, "text": "Trigonometry" }, { "code": null, "e": 8211, "s": 8200, "text": "Statistics" }, { "code": null, "e": 8223, "s": 8211, "text": "Probability" }, { "code": null, "e": 8232, "s": 8223, "text": "Geometry" }, { "code": null, "e": 8244, "s": 8232, "text": "Mensuration" }, { "code": null, "e": 8253, "s": 8244, "text": "Calculus" }, { "code": null, "e": 8346, "s": 8253, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8360, "s": 8346, "text": "Class 8 Notes" }, { "code": null, "e": 8374, "s": 8360, "text": "Class 9 Notes" }, { "code": null, "e": 8389, "s": 8374, "text": "Class 10 Notes" }, { "code": null, "e": 8404, "s": 8389, "text": "Class 11 Notes" }, { "code": null, "e": 8419, "s": 8404, "text": "Class 12 Notes" }, { "code": null, "e": 8548, "s": 8419, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8571, "s": 8548, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8594, "s": 8571, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8618, "s": 8594, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8642, "s": 8618, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8666, "s": 8642, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8799, "s": 8666, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8822, "s": 8799, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8845, "s": 8822, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8869, "s": 8845, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8893, "s": 8869, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8917, "s": 8893, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8998, "s": 8917, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 9012, "s": 8998, "text": "Class 8 Notes" }, { "code": null, "e": 9026, "s": 9012, "text": "Class 9 Notes" }, { "code": null, "e": 9041, "s": 9026, "text": "Class 10 Notes" }, { "code": null, "e": 9056, "s": 9041, "text": "Class 11 Notes" }, { "code": null, "e": 9262, "s": 9056, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9373, "s": 9262, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9415, "s": 9373, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9437, "s": 9415, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9482, "s": 9437, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9565, "s": 9482, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9591, "s": 9565, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9618, "s": 9591, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9643, "s": 9618, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9833, "s": 9643, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 9859, "s": 9833, "text": "Campus Ambassador Program" }, { "code": null, "e": 9885, "s": 9859, "text": "School Ambassador Program" }, { "code": null, "e": 9893, "s": 9885, "text": "Project" }, { "code": null, "e": 9911, "s": 9893, "text": "Geek of the Month" }, { "code": null, "e": 9936, "s": 9911, "text": "Campus Geek of the Month" }, { "code": null, "e": 9953, "s": 9936, "text": "Placement Course" }, { "code": null, "e": 9978, "s": 9953, "text": "Competititve Programming" }, { "code": null, "e": 9991, "s": 9978, "text": "Testimonials" }, { "code": null, "e": 10007, "s": 9991, "text": "Geek on the Top" }, { "code": null, "e": 10015, "s": 10007, "text": "Careers" }, { "code": null, "e": 10026, "s": 10015, "text": "Internship" }, { "code": null, "e": 10065, "s": 10026, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 10080, "s": 10065, "text": "Apply for Jobs" }, { "code": null, "e": 10091, "s": 10080, "text": "Post a Job" }, { "code": null, "e": 10102, "s": 10091, "text": "JOB-A-THON" }, { "code": null, "e": 10109, "s": 10102, "text": "Events" }, { "code": null, "e": 10380, "s": 10113, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10393, "s": 10380, "text": "Geeks Digest" }, { "code": null, "e": 10401, "s": 10393, "text": "Quizzes" }, { "code": null, "e": 10414, "s": 10401, "text": "Geeks Campus" }, { "code": null, "e": 10429, "s": 10414, "text": "Gblog Articles" }, { "code": null, "e": 10433, "s": 10429, "text": "IDE" }, { "code": null, "e": 10447, "s": 10433, "text": "Campus Mantri" }, { "code": null, "e": 10455, "s": 10447, "text": "Sign In" }, { "code": null, "e": 10463, "s": 10455, "text": "Sign In" }, { "code": null, "e": 10468, "s": 10463, "text": "Home" }, { "code": null, "e": 10481, "s": 10468, "text": "Saved Videos" }, { "code": null, "e": 10489, "s": 10481, "text": "Courses" }, { "code": null, "e": 14680, "s": 10489, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\n\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 14734, "s": 14680, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 14857, "s": 14734, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 14876, "s": 14857, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 14892, "s": 14876, "text": "\nSystem Design\n" }, { "code": null, "e": 14919, "s": 14892, "text": "\nJava Backend Development\n" }, { "code": null, "e": 14937, "s": 14919, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 14952, "s": 14937, "text": "\nExplore More\n" }, { "code": null, "e": 15060, "s": 14952, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15078, "s": 15060, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15091, "s": 15078, "text": "\nSDE Theory\n" }, { "code": null, "e": 15118, "s": 15091, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15133, "s": 15118, "text": "\nExplore More\n" }, { "code": null, "e": 15174, "s": 15133, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 15286, "s": 15174, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 15312, "s": 15286, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 15339, "s": 15312, "text": "\nData Structures with C++\n" }, { "code": null, "e": 15354, "s": 15339, "text": "\nData Science\n" }, { "code": null, "e": 15369, "s": 15354, "text": "\nExplore More\n" }, { "code": null, "e": 15465, "s": 15369, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 15483, "s": 15465, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15489, "s": 15483, "text": "\nCIP\n" }, { "code": null, "e": 15511, "s": 15489, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 15526, "s": 15511, "text": "\nExplore More\n" }, { "code": null, "e": 15623, "s": 15526, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n" }, { "code": null, "e": 15638, "s": 15623, "text": "\nSchool Guide\n" }, { "code": null, "e": 15659, "s": 15638, "text": "\nPython Programming\n" }, { "code": null, "e": 15680, "s": 15659, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 15781, "s": 15680, "text": "\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n" }, { "code": null, "e": 15801, "s": 15781, "text": "\nMust Do Questions\n" }, { "code": null, "e": 15818, "s": 15801, "text": "\nDSA Topic-wise\n" }, { "code": null, "e": 15837, "s": 15818, "text": "\nDSA Company-wise\n" }, { "code": null, "e": 16142, "s": 15837, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16165, "s": 16142, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16186, "s": 16165, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16205, "s": 16186, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16225, "s": 16205, "text": "\nPattern Searching\n" }, { "code": null, "e": 16248, "s": 16225, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16263, "s": 16248, "text": "\nMathematical\n" }, { "code": null, "e": 16284, "s": 16263, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16308, "s": 16284, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 16328, "s": 16308, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 16350, "s": 16328, "text": "\nDynamic Programming\n" }, { "code": null, "e": 16371, "s": 16350, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 16386, "s": 16371, "text": "\nBacktracking\n" }, { "code": null, "e": 16405, "s": 16386, "text": "\nBranch and Bound\n" }, { "code": null, "e": 16422, "s": 16405, "text": "\nAll Algorithms\n" }, { "code": null, "e": 16807, "s": 16422, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 16829, "s": 16807, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 16861, "s": 16829, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 16884, "s": 16861, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 16922, "s": 16884, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 16953, "s": 16922, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 16973, "s": 16953, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 16995, "s": 16973, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17016, "s": 16995, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17054, "s": 17016, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17085, "s": 17054, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17124, "s": 17085, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17153, "s": 17124, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 17350, "s": 17153, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 17359, "s": 17350, "text": "\nArrays\n" }, { "code": null, "e": 17373, "s": 17359, "text": "\nLinked List\n" }, { "code": null, "e": 17381, "s": 17373, "text": "\nStack\n" }, { "code": null, "e": 17389, "s": 17381, "text": "\nQueue\n" }, { "code": null, "e": 17403, "s": 17389, "text": "\nBinary Tree\n" }, { "code": null, "e": 17424, "s": 17403, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 17431, "s": 17424, "text": "\nHeap\n" }, { "code": null, "e": 17441, "s": 17431, "text": "\nHashing\n" }, { "code": null, "e": 17449, "s": 17441, "text": "\nGraph\n" }, { "code": null, "e": 17475, "s": 17449, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 17484, "s": 17475, "text": "\nMatrix\n" }, { "code": null, "e": 17494, "s": 17484, "text": "\nStrings\n" }, { "code": null, "e": 17516, "s": 17494, "text": "\nAll Data Structures\n" }, { "code": null, "e": 17784, "s": 17516, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 17806, "s": 17784, "text": "\nCompany Preparation\n" }, { "code": null, "e": 17819, "s": 17806, "text": "\nTop Topics\n" }, { "code": null, "e": 17848, "s": 17819, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 17872, "s": 17848, "text": "\nInterview Experiences\n" }, { "code": null, "e": 17897, "s": 17872, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 17921, "s": 17897, "text": "\nInternship Interviews\n" }, { "code": null, "e": 17948, "s": 17921, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 17966, "s": 17948, "text": "\nDesign Patterns\n" }, { "code": null, "e": 17991, "s": 17966, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18017, "s": 17991, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18156, "s": 18017, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18160, "s": 18156, "text": "\nC\n" }, { "code": null, "e": 18166, "s": 18160, "text": "\nC++\n" }, { "code": null, "e": 18173, "s": 18166, "text": "\nJava\n" }, { "code": null, "e": 18182, "s": 18173, "text": "\nPython\n" }, { "code": null, "e": 18187, "s": 18182, "text": "\nC#\n" }, { "code": null, "e": 18200, "s": 18187, "text": "\nJavaScript\n" }, { "code": null, "e": 18209, "s": 18200, "text": "\njQuery\n" }, { "code": null, "e": 18215, "s": 18209, "text": "\nSQL\n" }, { "code": null, "e": 18221, "s": 18215, "text": "\nPHP\n" }, { "code": null, "e": 18229, "s": 18221, "text": "\nScala\n" }, { "code": null, "e": 18236, "s": 18229, "text": "\nPerl\n" }, { "code": null, "e": 18250, "s": 18236, "text": "\nGo Language\n" }, { "code": null, "e": 18257, "s": 18250, "text": "\nHTML\n" }, { "code": null, "e": 18263, "s": 18257, "text": "\nCSS\n" }, { "code": null, "e": 18272, "s": 18263, "text": "\nKotlin\n" }, { "code": null, "e": 18350, "s": 18272, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 18369, "s": 18350, "text": "\nMachine Learning\n" }, { "code": null, "e": 18384, "s": 18369, "text": "\nData Science\n" }, { "code": null, "e": 18597, "s": 18384, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 18611, "s": 18597, "text": "\nMathematics\n" }, { "code": null, "e": 18630, "s": 18611, "text": "\nOperating System\n" }, { "code": null, "e": 18637, "s": 18630, "text": "\nDBMS\n" }, { "code": null, "e": 18657, "s": 18637, "text": "\nComputer Networks\n" }, { "code": null, "e": 18698, "s": 18657, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 18722, "s": 18698, "text": "\nTheory of Computation\n" }, { "code": null, "e": 18740, "s": 18722, "text": "\nCompiler Design\n" }, { "code": null, "e": 18756, "s": 18740, "text": "\nDigital Logic\n" }, { "code": null, "e": 18779, "s": 18756, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 18996, "s": 18779, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19026, "s": 18996, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19046, "s": 19026, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19070, "s": 19046, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19114, "s": 19070, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19132, "s": 19114, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19156, "s": 19132, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19187, "s": 19156, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19307, "s": 19187, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19314, "s": 19307, "text": "\nHTML\n" }, { "code": null, "e": 19320, "s": 19314, "text": "\nCSS\n" }, { "code": null, "e": 19333, "s": 19320, "text": "\nJavaScript\n" }, { "code": null, "e": 19345, "s": 19333, "text": "\nAngularJS\n" }, { "code": null, "e": 19355, "s": 19345, "text": "\nReactJS\n" }, { "code": null, "e": 19364, "s": 19355, "text": "\nNodeJS\n" }, { "code": null, "e": 19376, "s": 19364, "text": "\nBootstrap\n" }, { "code": null, "e": 19385, "s": 19376, "text": "\njQuery\n" }, { "code": null, "e": 19391, "s": 19385, "text": "\nPHP\n" }, { "code": null, "e": 19486, "s": 19391, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 19513, "s": 19486, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 19538, "s": 19513, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 19602, "s": 19538, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 19623, "s": 19602, "text": "\nSchool Programming\n" }, { "code": null, "e": 19759, "s": 19623, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 19775, "s": 19759, "text": "\nNumber System\n" }, { "code": null, "e": 19785, "s": 19775, "text": "\nAlgebra\n" }, { "code": null, "e": 19800, "s": 19785, "text": "\nTrigonometry\n" }, { "code": null, "e": 19813, "s": 19800, "text": "\nStatistics\n" }, { "code": null, "e": 19827, "s": 19813, "text": "\nProbability\n" }, { "code": null, "e": 19838, "s": 19827, "text": "\nGeometry\n" }, { "code": null, "e": 19852, "s": 19838, "text": "\nMensuration\n" }, { "code": null, "e": 19863, "s": 19852, "text": "\nCalculus\n" }, { "code": null, "e": 19994, "s": 19863, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20010, "s": 19994, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20026, "s": 20010, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20043, "s": 20026, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20060, "s": 20043, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20077, "s": 20060, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20244, "s": 20077, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20269, "s": 20244, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20294, "s": 20269, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20320, "s": 20294, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20346, "s": 20320, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20372, "s": 20346, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20543, "s": 20372, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20568, "s": 20543, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20593, "s": 20568, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20619, "s": 20593, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20645, "s": 20619, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20671, "s": 20645, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20788, "s": 20671, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 20804, "s": 20788, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20820, "s": 20804, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20837, "s": 20820, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20854, "s": 20837, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20896, "s": 20854, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21041, "s": 20896, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21085, "s": 21041, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21109, "s": 21085, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21156, "s": 21109, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21273, "s": 21156, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21301, "s": 21273, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 21330, "s": 21301, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 21357, "s": 21330, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21597, "s": 21357, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n" }, { "code": null, "e": 21625, "s": 21597, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 21653, "s": 21625, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 21663, "s": 21653, "text": "\nProject\n" }, { "code": null, "e": 21683, "s": 21663, "text": "\nGeek of the Month\n" }, { "code": null, "e": 21710, "s": 21683, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 21729, "s": 21710, "text": "\nPlacement Course\n" }, { "code": null, "e": 21756, "s": 21729, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 21771, "s": 21756, "text": "\nTestimonials\n" }, { "code": null, "e": 21789, "s": 21771, "text": "\nGeek on the Top\n" }, { "code": null, "e": 21799, "s": 21789, "text": "\nCareers\n" }, { "code": null, "e": 21812, "s": 21799, "text": "\nInternship\n" }, { "code": null, "e": 21850, "s": 21812, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 21923, "s": 21850, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 21940, "s": 21923, "text": "\nApply for Jobs\n" }, { "code": null, "e": 21953, "s": 21940, "text": "\nPost a Job\n" }, { "code": null, "e": 21966, "s": 21953, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 21972, "s": 21966, "text": "GBlog" }, { "code": null, "e": 21980, "s": 21972, "text": "Puzzles" }, { "code": null, "e": 21993, "s": 21980, "text": "What's New ?" }, { "code": null, "e": 21999, "s": 21993, "text": "Array" }, { "code": null, "e": 22006, "s": 21999, "text": "Matrix" }, { "code": null, "e": 22014, "s": 22006, "text": "Strings" }, { "code": null, "e": 22022, "s": 22014, "text": "Hashing" }, { "code": null, "e": 22034, "s": 22022, "text": "Linked List" }, { "code": null, "e": 22040, "s": 22034, "text": "Stack" }, { "code": null, "e": 22046, "s": 22040, "text": "Queue" }, { "code": null, "e": 22058, "s": 22046, "text": "Binary Tree" }, { "code": null, "e": 22077, "s": 22058, "text": "Binary Search Tree" }, { "code": null, "e": 22082, "s": 22077, "text": "Heap" }, { "code": null, "e": 22088, "s": 22082, "text": "Graph" }, { "code": null, "e": 22098, "s": 22088, "text": "Searching" }, { "code": null, "e": 22106, "s": 22098, "text": "Sorting" }, { "code": null, "e": 22123, "s": 22106, "text": "Divide & Conquer" }, { "code": null, "e": 22136, "s": 22123, "text": "Mathematical" }, { "code": null, "e": 22146, "s": 22136, "text": "Geometric" }, { "code": null, "e": 22154, "s": 22146, "text": "Bitwise" }, { "code": null, "e": 22161, "s": 22154, "text": "Greedy" }, { "code": null, "e": 22174, "s": 22161, "text": "Backtracking" }, { "code": null, "e": 22191, "s": 22174, "text": "Branch and Bound" }, { "code": null, "e": 22211, "s": 22191, "text": "Dynamic Programming" }, { "code": null, "e": 22229, "s": 22211, "text": "Pattern Searching" }, { "code": null, "e": 22240, "s": 22229, "text": "Randomized" }, { "code": null, "e": 22282, "s": 22240, "text": "Sort an array which contain 1 to n values" }, { "code": null, "e": 22324, "s": 22282, "text": "Sort 1 to N by swapping adjacent elements" }, { "code": null, "e": 22371, "s": 22324, "text": "Sort an array containing two types of elements" }, { "code": null, "e": 22406, "s": 22371, "text": "Sort elements by frequency | Set 1" }, { "code": null, "e": 22441, "s": 22406, "text": "Sort elements by frequency | Set 2" }, { "code": null, "e": 22508, "s": 22441, "text": "Sort elements by frequency | Set 4 (Efficient approach using hash)" }, { "code": null, "e": 22564, "s": 22508, "text": "Sorting Array Elements By Frequency | Set 3 (Using STL)" }, { "code": null, "e": 22616, "s": 22564, "text": "Sort elements by frequency | Set 5 (using Java Map)" }, { "code": null, "e": 22654, "s": 22616, "text": "Sorting a Hashmap according to values" }, { "code": null, "e": 22698, "s": 22654, "text": "Sorting a HashMap according to keys in Java" }, { "code": null, "e": 22714, "s": 22698, "text": "TreeMap in Java" }, { "code": null, "e": 22730, "s": 22714, "text": "TreeSet in Java" }, { "code": null, "e": 22746, "s": 22730, "text": "HashSet in Java" }, { "code": null, "e": 22776, "s": 22746, "text": "HashMap in Java with Examples" }, { "code": null, "e": 22812, "s": 22776, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 22852, "s": 22812, "text": "Internal working of Set/HashSet in Java" }, { "code": null, "e": 22875, "s": 22852, "text": "Merge Two Sets in Java" }, { "code": null, "e": 22887, "s": 22875, "text": "Set in Java" }, { "code": null, "e": 22909, "s": 22887, "text": "Map Interface in Java" }, { "code": null, "e": 22940, "s": 22909, "text": "How to iterate any Map in Java" }, { "code": null, "e": 22955, "s": 22940, "text": "Arrays in Java" }, { "code": null, "e": 23001, "s": 22955, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 23033, "s": 23001, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 23060, "s": 23033, "text": "Program for array rotation" }, { "code": null, "e": 23076, "s": 23060, "text": "Arrays in C/C++" }, { "code": null, "e": 23124, "s": 23076, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 23168, "s": 23124, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 23182, "s": 23168, "text": "Linear Search" }, { "code": null, "e": 23267, "s": 23182, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 23335, "s": 23267, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 23377, "s": 23335, "text": "Sort an array which contain 1 to n values" }, { "code": null, "e": 23419, "s": 23377, "text": "Sort 1 to N by swapping adjacent elements" }, { "code": null, "e": 23466, "s": 23419, "text": "Sort an array containing two types of elements" }, { "code": null, "e": 23501, "s": 23466, "text": "Sort elements by frequency | Set 1" }, { "code": null, "e": 23536, "s": 23501, "text": "Sort elements by frequency | Set 2" }, { "code": null, "e": 23603, "s": 23536, "text": "Sort elements by frequency | Set 4 (Efficient approach using hash)" }, { "code": null, "e": 23659, "s": 23603, "text": "Sorting Array Elements By Frequency | Set 3 (Using STL)" }, { "code": null, "e": 23711, "s": 23659, "text": "Sort elements by frequency | Set 5 (using Java Map)" }, { "code": null, "e": 23749, "s": 23711, "text": "Sorting a Hashmap according to values" }, { "code": null, "e": 23793, "s": 23749, "text": "Sorting a HashMap according to keys in Java" }, { "code": null, "e": 23809, "s": 23793, "text": "TreeMap in Java" }, { "code": null, "e": 23825, "s": 23809, "text": "TreeSet in Java" }, { "code": null, "e": 23841, "s": 23825, "text": "HashSet in Java" }, { "code": null, "e": 23871, "s": 23841, "text": "HashMap in Java with Examples" }, { "code": null, "e": 23907, "s": 23871, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 23947, "s": 23907, "text": "Internal working of Set/HashSet in Java" }, { "code": null, "e": 23970, "s": 23947, "text": "Merge Two Sets in Java" }, { "code": null, "e": 23982, "s": 23970, "text": "Set in Java" }, { "code": null, "e": 24004, "s": 23982, "text": "Map Interface in Java" }, { "code": null, "e": 24035, "s": 24004, "text": "How to iterate any Map in Java" }, { "code": null, "e": 24050, "s": 24035, "text": "Arrays in Java" }, { "code": null, "e": 24096, "s": 24050, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24128, "s": 24096, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 24155, "s": 24128, "text": "Program for array rotation" }, { "code": null, "e": 24171, "s": 24155, "text": "Arrays in C/C++" }, { "code": null, "e": 24219, "s": 24171, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 24263, "s": 24219, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 24277, "s": 24263, "text": "Linear Search" }, { "code": null, "e": 24362, "s": 24277, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 24430, "s": 24362, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 24454, "s": 24430, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 24613, "s": 24454, "text": "You have given an array which contain 1 to n element, your task is to sort this array in an efficient way and without replace with 1 to n numbers.Examples : " }, { "code": null, "e": 24710, "s": 24613, "text": "Input : arr[] = {10, 7, 9, 2, 8, \n 3, 5, 4, 6, 1};\nOutput : 1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 24998, "s": 24712, "text": "Native approach : Sort this array with the use of any type of sorting method. it takes O(nlogn) minimum time.Efficient approach : Replace every element with it’s position. it takes O(n) efficient time and give you the sorted array. Let’s understand this approach with the code below. " }, { "code": null, "e": 25002, "s": 24998, "text": "C++" }, { "code": null, "e": 25007, "s": 25002, "text": "Java" }, { "code": null, "e": 25015, "s": 25007, "text": "Python3" }, { "code": null, "e": 25018, "s": 25015, "text": "C#" }, { "code": null, "e": 25022, "s": 25018, "text": "PHP" }, { "code": null, "e": 25033, "s": 25022, "text": "Javascript" }, { "code": "// Efficient C++ program to sort an array of// numbers in range from 1 to n.#include <bits/stdc++.h> using namespace std; // function for sort arrayvoid sortit(int arr[], int n){ for (int i = 0; i < n; i++) { arr[i]=i+1; }} // Driver codeint main(){ int arr[] = { 10, 7, 9, 2, 8, 3, 5, 4, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // for sort an array sortit(arr, n); // for print all the element in sorted way for (int i = 0; i < n; i++) cout << arr[i] << \" \"; }", "e": 25541, "s": 25033, "text": null }, { "code": "// Efficient Java program to sort an// array of numbers in range from 1// to n.import java.io.*;import java.util.*; public class GFG { // function for sort array static void sortit(int []arr, int n) { for (int i = 0; i < n; i++) { arr[i]=i+1; } } // Driver code public static void main(String args[]) { int []arr = {10, 7, 9, 2, 8, 3, 5, 4, 6, 1}; int n = arr.length; // for sort an array sortit(arr, n); // for print all the // element in sorted way for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 26304, "s": 25541, "text": null }, { "code": "# Python3 program to sort an array of# numbers in range from 1 to n. # function for sort arraydef sortit(arr,n): for i in range(n): arr[i] = i+1 # Driver codeif __name__=='__main__': arr = [10, 7, 9, 2, 8, 3, 5, 4, 6, 1 ] n = len(arr) # for sort an array sortit(arr,n) # for print all the element # in sorted way for i in range(n): print(arr[i],end=\" \") # This code is contributed by# Shrikant13", "e": 26741, "s": 26304, "text": null }, { "code": "// Efficient C# program to sort an array of// numbers in range from 1 to n.using System;using System.Collections.Generic; class GFG { // function for sort array static void sortit(int []arr, int n) { for (int i = 0; i < n; i++) { arr[i]=i+1; } } // Driver code public static void Main() { int []arr = {10, 7, 9, 2, 8, 3, 5, 4, 6, 1}; int n = arr.Length; // for sort an array sortit(arr, n); // for print all the // element in sorted way for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by// Manish Shaw (manishshaw1)", "e": 27468, "s": 26741, "text": null }, { "code": "<?php// Efficient PHP program to sort an// array of numbers in range from 1 to n. // function for sort arrayfunction sortit(&$arr, $n){ for ($i = 0; $i < $n; $i++) { $arr[$i]=$i+1; }} // Driver code$arr = array(10, 7, 9, 2, 8, 3, 5, 4, 6, 1);$n = count($arr); // for sort an arraysortit($arr, $n); // for print all the// element in sorted wayfor ($i = 0; $i < $n; $i++) echo $arr[$i].\" \"; //This code is contributed by Manish Shaw//(manishshaw1)?>", "e": 27950, "s": 27468, "text": null }, { "code": "<script> // Efficient JavaScript program to sort an array of// numbers in range from 1 to n. // function for sort arrayfunction sortit(arr, n){ for (let i = 0; i < n; i++) { arr[i]=i+1; }} // Driver code let arr = [ 10, 7, 9, 2, 8, 3, 5, 4, 6, 1 ]; let n = arr.length; // for sort an array sortit(arr, n); // for print all the element in sorted way for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by Surbhi Tyagi. </script>", "e": 28454, "s": 27950, "text": null }, { "code": null, "e": 28475, "s": 28454, "text": "1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 28499, "s": 28477, "text": "Time Complexity: O(n)" }, { "code": null, "e": 28522, "s": 28499, "text": "Space Complexity: O(1)" }, { "code": null, "e": 28534, "s": 28522, "text": "manishshaw1" }, { "code": null, "e": 28549, "s": 28534, "text": "_Keep_Silence_" }, { "code": null, "e": 28561, "s": 28549, "text": "shrikanth13" }, { "code": null, "e": 28575, "s": 28561, "text": "surbhityagi15" }, { "code": null, "e": 28588, "s": 28575, "text": "prasanna1995" }, { "code": null, "e": 28611, "s": 28588, "text": "limited-range-elements" }, { "code": null, "e": 28618, "s": 28611, "text": "Arrays" }, { "code": null, "e": 28626, "s": 28618, "text": "Sorting" }, { "code": null, "e": 28633, "s": 28626, "text": "Arrays" }, { "code": null, "e": 28641, "s": 28633, "text": "Sorting" }, { "code": null, "e": 28739, "s": 28641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28748, "s": 28739, "text": "Comments" }, { "code": null, "e": 28761, "s": 28748, "text": "Old Comments" }, { "code": null, "e": 28784, "s": 28761, "text": "Introduction to Arrays" }, { "code": null, "e": 28816, "s": 28784, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28837, "s": 28816, "text": "Linked List vs Array" }, { "code": null, "e": 28891, "s": 28837, "text": "Queue | Set 1 (Introduction and Array Implementation)" } ]
Java String codePointBefore() Method
❮ String Methods Return the Unicode of the first character in a string (the Unicode value of "H" is 72): String myStr = "Hello"; int result = myStr.codePointBefore(1); System.out.println(result); Try it Yourself » The codePointBefore() method returns the Unicode value of the character before the specified index in a string. The index of the first character is 1, the second character is 2, and so on. Note: The value 0 will generate an error, as this is a negative number (out of reach). public int codePointBefore(int index) 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 110, "s": 19, "text": "Return the Unicode of the first character in a string (the Unicode value \n of \"H\" is 72):" }, { "code": null, "e": 201, "s": 110, "text": "String myStr = \"Hello\";\nint result = myStr.codePointBefore(1);\nSystem.out.println(result);" }, { "code": null, "e": 221, "s": 201, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 334, "s": 221, "text": "The codePointBefore() method returns the Unicode \nvalue of the character before the specified index in a string." }, { "code": null, "e": 411, "s": 334, "text": "The index of the first character is 1, the second character is 2, and so on." }, { "code": null, "e": 499, "s": 411, "text": "Note: The value 0 will generate an error, as this is a negative number (out \nof reach)." }, { "code": null, "e": 538, "s": 499, "text": "public int codePointBefore(int index)\n" }, { "code": null, "e": 571, "s": 538, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 613, "s": 571, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 720, "s": 613, "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": 739, "s": 720, "text": "help@w3schools.com" } ]
JSTL - fn:replace() Function
The fn:replace() function replaces all occurrences of a string with another string. The fn:replace () function has the following syntax − boolean replace(java.lang.String, java.lang.String, java.lang.String) Following is the example to explain the functionality of the fn:replace() function − <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "string1" value = "This is first String."/> <c:set var = "string2" value = "${fn:replace(string1, 'first', 'second')}" /> <p>Final String : ${string2}</p> </body> </html> You will receive the following result − Final String : This is second String. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2323, "s": 2239, "text": "The fn:replace() function replaces all occurrences of a string with another string." }, { "code": null, "e": 2377, "s": 2323, "text": "The fn:replace () function has the following syntax −" }, { "code": null, "e": 2448, "s": 2377, "text": "boolean replace(java.lang.String, java.lang.String, java.lang.String)\n" }, { "code": null, "e": 2533, "s": 2448, "text": "Following is the example to explain the functionality of the fn:replace() function −" }, { "code": null, "e": 2964, "s": 2533, "text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"string1\" value = \"This is first String.\"/>\n <c:set var = \"string2\" value = \"${fn:replace(string1, 'first', 'second')}\" />\n <p>Final String : ${string2}</p>\n </body>\n</html>" }, { "code": null, "e": 3004, "s": 2964, "text": "You will receive the following result −" }, { "code": null, "e": 3043, "s": 3004, "text": "Final String : This is second String.\n" }, { "code": null, "e": 3078, "s": 3043, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3093, "s": 3078, "text": " Chaand Sheikh" }, { "code": null, "e": 3128, "s": 3093, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3143, "s": 3128, "text": " Chaand Sheikh" }, { "code": null, "e": 3178, "s": 3143, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3192, "s": 3178, "text": " Karthikeya T" }, { "code": null, "e": 3227, "s": 3192, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3243, "s": 3227, "text": " TELCOMA Global" }, { "code": null, "e": 3276, "s": 3243, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3292, "s": 3276, "text": " TELCOMA Global" }, { "code": null, "e": 3326, "s": 3292, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3334, "s": 3326, "text": " Uplatz" }, { "code": null, "e": 3341, "s": 3334, "text": " Print" }, { "code": null, "e": 3352, "s": 3341, "text": " Add Notes" } ]
Notify with Python. Make life easier with Python built... | by James Briggs | Towards Data Science
Working in Python, I often run data processing, transfer, and model training scripts. Now, with any reasonable degree of complexity and/or big data, this can take some time. Although often enough we all have some other work to be done whilst waiting for these processing to complete, occasionally, we don’t. For this purpose, I put together a set of Python scripts built for this exact problem. I use these scripts to send process updates, visualizations and completion notifications to my phone. So, when we do occasionally have those moments of freedom. We can enjoy them without being worried about model progress. Okay so the first thing we need to ask is — what do we need to know? Now of-course, this really depends on the work you are doing. For me I have three main processing tasks that have the potential to take up time: Model training Data processing and/or transfer Financial modelling For each of these, there are of-course different pieces of information that we need to stay informed about. Let’s take a look at an example of each. Update every n epochs, must include key metrics. For example, loss and accuracy for training and validation sets. Notification of completion (of-course). For this I like to include: prediction outputs, for text generation, the generated text (or a sample of it) — for image generation, a (hopefully) cool visualization. visualization of key metrics during training (again, loss and accuracy for both training and validation sets) other, less essential but still useful information such as local model directories, training time, model architecture etc Let’s take the example of training a neural network to reproduce a given artistic style. For this, we want to see; generated images from the model, loss and accuracy plots, and current training time, and a model name. In this scenario, every 100 epochs, an email containing all of the above will be sent. Here is one of those emails: This one is slightly less glamorous, but in terms of time consumed, is number one by a long-shot. We will use the example of bulk data upload to SQL Server using Python (for those of us without BULK INSERT). At the end of the upload script, we include a simple message notifying us of upload completion. If errors are occasionally thrown, we could also add a try-except clause to catch the error, and add it to a list to include in our update and/or completion email. In the case of financial modelling, everything I run is actually pretty quick, so I can only provide you with an ‘example’ use-case here. We will use the example of a cash-flow modelling tool. In-reality, this process take no more than a 10–20 seconds, but for now let’s assume we’re hot-shot Wall Street quants processing a few million (rather than hundred) loans. With this email, we may want to include a high-level summary of the analysed portfolio. We can randomly select a few loans and visualize key values over the given time period — giving us a small sample to cross-check model performance is as expected. All of the functionality above filters from a single script called notify.py. We will use Outlook in our example code. However, translating this to other providers is incredibly easy, which we will also cover quickly at the end. There are two Python libraries we need here, email and smtplib. email — For managing email messages. With this we will setup the email message itself, including subject, body, and attachments. smtplib — Handles the SMTP connection. The simple mail transfer protocol (SMTP) is the protocol used by the majority of email systems, allowing mail to be sent over the internet.’ The message itself is built using a MIMEMultipart object from the email module. We also use three MIME sub-classes, which we attach to the MIMEMultipart object: MIMEText — This will contain the email ‘payload’, meaning the text within the email body. MIMEImage — Reasonably easy to guess, this is used to contain images within our email. MIMEApplication — Used for MIME message application objects. For us, these are file attachments. In addition to these sub-classes, there are also other parameters, such as the Subject value in MimeMultipart. All of these together gives us the following structure. Let’s take a look at putting these all together. This script, for the most part, is reasonably straightforward. At the top, we have our imports — which are the MIME parts we covered before, and Python’s os library. Following this define a function called message. This allows us to call the function with different parameters and build an email message object with ease. For example, we can write an email with multiple images and attachments like so: email_msg = message( text="Model processing complete, please see attached data.", img=['accuracy.png', 'loss.png'], attachments=['data_in.csv', 'data_out.csv']) First we initialize the MIMEMultipart object, assigning it to msg. We then set the email subject using the 'Subject' key. The attach method allows us to add different MIME sub-classes to our MIMEMultipart object. With this we can add the email body, using the MIMEText sub-class. For both images img and attachments attachment, we can pass either nothing, a single file-path, or a list of file-paths. This is handled by first checking if the parameters are None, if they are, we pass. Otherwise, we check the data-type given, is it is not a list, we make it one — this allows us to use the following for loop to iterate through our items. At this point we use the MIMEImage and MIMEApplication sub-classes to attach our images and files respectively. For both we use os.basename to retrieve the filename from the given file-path, which we include as the attachment name. Now that we have built our email message object, we need to send it. This is where the smtplib module comes in. The code is again, pretty straight-forward, with one exception. As we are dealing directly with different email provider’s, and their respective servers, we need different SMTP addresses for each. Fortunately, this is really easy to find. Type “outlook smtp” into Google. Without even clicking on a page, we are given the server address smtp-mail.outlook.com, and port number 587. We use both of these when initalizing the SMTP object with smtplib.SMTP — near the beginning of the send function. smtp.ehlo() and smtp.starttls() are both SMTP commands. ehlo (Extended Hello) essentially greets the server. starttls informs the server we will be communicating using an encrypted transport level security (TLS) connection. You can learn more about SMTP commands here. After this we simply read in our email and password from file, storing both in email and pwd respectively. We then login to the SMTP server with smtp.login, and send the email with smtp.sendmail. I always send the notifications to myself, but in the case of automated reporting (or for any other reason), you may want to send the email elsewhere. To do this, change the destination_address: smtp.sendmail(email, destination_address, msg.as_string). Finally, we terminate the session and close the connection with smtp.quit. All of this is placed within a try-except statement. In the case of momentary network connection loss, we will be unable to connect to the server. Resulting in a socket.gaierror. Implementing this try-except statement prevents the program from breaking in the case of a lapse in network connection. How you deal with this may differ, depending on how important it is for the email to be sent. For me, I use this for ML model training updates and data transfer completion. If an email does not get sent, it doesn’t really matter. So this simple, passive handling of connection loss is suitable. Now we have written both parts of our code, we can send emails with just: # build a message objectmsg = message(text="See attached!", img='important.png', attachment='data.csv')send(msg) # send the email (defaults to Outlook) Jason Farlette pointed out that those of you using Gmail may need to ‘allow access for less secure apps’. Steps for doing so can be found in this Stack Overflow question. That is all for email notification and/or automation using Python. Thanks to the email and smptlib libraries this is an incredibly easy process to setup. For any processing or training tasks that consume a lot of time, progress updates and notification on completion, is often truly liberating. I hope this article has been useful to a few of you out there, as always, let me know if you have any questions or suggestions! Thanks for reading! I’ve also written other ‘quick fix’ articles for making our lives easier with Python, check out this one for Excel and Python integration:
[ { "code": null, "e": 221, "s": 47, "text": "Working in Python, I often run data processing, transfer, and model training scripts. Now, with any reasonable degree of complexity and/or big data, this can take some time." }, { "code": null, "e": 355, "s": 221, "text": "Although often enough we all have some other work to be done whilst waiting for these processing to complete, occasionally, we don’t." }, { "code": null, "e": 544, "s": 355, "text": "For this purpose, I put together a set of Python scripts built for this exact problem. I use these scripts to send process updates, visualizations and completion notifications to my phone." }, { "code": null, "e": 665, "s": 544, "text": "So, when we do occasionally have those moments of freedom. We can enjoy them without being worried about model progress." }, { "code": null, "e": 734, "s": 665, "text": "Okay so the first thing we need to ask is — what do we need to know?" }, { "code": null, "e": 879, "s": 734, "text": "Now of-course, this really depends on the work you are doing. For me I have three main processing tasks that have the potential to take up time:" }, { "code": null, "e": 894, "s": 879, "text": "Model training" }, { "code": null, "e": 926, "s": 894, "text": "Data processing and/or transfer" }, { "code": null, "e": 946, "s": 926, "text": "Financial modelling" }, { "code": null, "e": 1095, "s": 946, "text": "For each of these, there are of-course different pieces of information that we need to stay informed about. Let’s take a look at an example of each." }, { "code": null, "e": 1209, "s": 1095, "text": "Update every n epochs, must include key metrics. For example, loss and accuracy for training and validation sets." }, { "code": null, "e": 1277, "s": 1209, "text": "Notification of completion (of-course). For this I like to include:" }, { "code": null, "e": 1415, "s": 1277, "text": "prediction outputs, for text generation, the generated text (or a sample of it) — for image generation, a (hopefully) cool visualization." }, { "code": null, "e": 1525, "s": 1415, "text": "visualization of key metrics during training (again, loss and accuracy for both training and validation sets)" }, { "code": null, "e": 1647, "s": 1525, "text": "other, less essential but still useful information such as local model directories, training time, model architecture etc" }, { "code": null, "e": 1736, "s": 1647, "text": "Let’s take the example of training a neural network to reproduce a given artistic style." }, { "code": null, "e": 1865, "s": 1736, "text": "For this, we want to see; generated images from the model, loss and accuracy plots, and current training time, and a model name." }, { "code": null, "e": 1981, "s": 1865, "text": "In this scenario, every 100 epochs, an email containing all of the above will be sent. Here is one of those emails:" }, { "code": null, "e": 2079, "s": 1981, "text": "This one is slightly less glamorous, but in terms of time consumed, is number one by a long-shot." }, { "code": null, "e": 2189, "s": 2079, "text": "We will use the example of bulk data upload to SQL Server using Python (for those of us without BULK INSERT)." }, { "code": null, "e": 2285, "s": 2189, "text": "At the end of the upload script, we include a simple message notifying us of upload completion." }, { "code": null, "e": 2449, "s": 2285, "text": "If errors are occasionally thrown, we could also add a try-except clause to catch the error, and add it to a list to include in our update and/or completion email." }, { "code": null, "e": 2587, "s": 2449, "text": "In the case of financial modelling, everything I run is actually pretty quick, so I can only provide you with an ‘example’ use-case here." }, { "code": null, "e": 2815, "s": 2587, "text": "We will use the example of a cash-flow modelling tool. In-reality, this process take no more than a 10–20 seconds, but for now let’s assume we’re hot-shot Wall Street quants processing a few million (rather than hundred) loans." }, { "code": null, "e": 3066, "s": 2815, "text": "With this email, we may want to include a high-level summary of the analysed portfolio. We can randomly select a few loans and visualize key values over the given time period — giving us a small sample to cross-check model performance is as expected." }, { "code": null, "e": 3144, "s": 3066, "text": "All of the functionality above filters from a single script called notify.py." }, { "code": null, "e": 3295, "s": 3144, "text": "We will use Outlook in our example code. However, translating this to other providers is incredibly easy, which we will also cover quickly at the end." }, { "code": null, "e": 3359, "s": 3295, "text": "There are two Python libraries we need here, email and smtplib." }, { "code": null, "e": 3488, "s": 3359, "text": "email — For managing email messages. With this we will setup the email message itself, including subject, body, and attachments." }, { "code": null, "e": 3668, "s": 3488, "text": "smtplib — Handles the SMTP connection. The simple mail transfer protocol (SMTP) is the protocol used by the majority of email systems, allowing mail to be sent over the internet.’" }, { "code": null, "e": 3829, "s": 3668, "text": "The message itself is built using a MIMEMultipart object from the email module. We also use three MIME sub-classes, which we attach to the MIMEMultipart object:" }, { "code": null, "e": 3919, "s": 3829, "text": "MIMEText — This will contain the email ‘payload’, meaning the text within the email body." }, { "code": null, "e": 4006, "s": 3919, "text": "MIMEImage — Reasonably easy to guess, this is used to contain images within our email." }, { "code": null, "e": 4103, "s": 4006, "text": "MIMEApplication — Used for MIME message application objects. For us, these are file attachments." }, { "code": null, "e": 4270, "s": 4103, "text": "In addition to these sub-classes, there are also other parameters, such as the Subject value in MimeMultipart. All of these together gives us the following structure." }, { "code": null, "e": 4319, "s": 4270, "text": "Let’s take a look at putting these all together." }, { "code": null, "e": 4485, "s": 4319, "text": "This script, for the most part, is reasonably straightforward. At the top, we have our imports — which are the MIME parts we covered before, and Python’s os library." }, { "code": null, "e": 4722, "s": 4485, "text": "Following this define a function called message. This allows us to call the function with different parameters and build an email message object with ease. For example, we can write an email with multiple images and attachments like so:" }, { "code": null, "e": 4892, "s": 4722, "text": "email_msg = message( text=\"Model processing complete, please see attached data.\", img=['accuracy.png', 'loss.png'], attachments=['data_in.csv', 'data_out.csv'])" }, { "code": null, "e": 4959, "s": 4892, "text": "First we initialize the MIMEMultipart object, assigning it to msg." }, { "code": null, "e": 5014, "s": 4959, "text": "We then set the email subject using the 'Subject' key." }, { "code": null, "e": 5172, "s": 5014, "text": "The attach method allows us to add different MIME sub-classes to our MIMEMultipart object. With this we can add the email body, using the MIMEText sub-class." }, { "code": null, "e": 5293, "s": 5172, "text": "For both images img and attachments attachment, we can pass either nothing, a single file-path, or a list of file-paths." }, { "code": null, "e": 5531, "s": 5293, "text": "This is handled by first checking if the parameters are None, if they are, we pass. Otherwise, we check the data-type given, is it is not a list, we make it one — this allows us to use the following for loop to iterate through our items." }, { "code": null, "e": 5763, "s": 5531, "text": "At this point we use the MIMEImage and MIMEApplication sub-classes to attach our images and files respectively. For both we use os.basename to retrieve the filename from the given file-path, which we include as the attachment name." }, { "code": null, "e": 5832, "s": 5763, "text": "Now that we have built our email message object, we need to send it." }, { "code": null, "e": 5939, "s": 5832, "text": "This is where the smtplib module comes in. The code is again, pretty straight-forward, with one exception." }, { "code": null, "e": 6114, "s": 5939, "text": "As we are dealing directly with different email provider’s, and their respective servers, we need different SMTP addresses for each. Fortunately, this is really easy to find." }, { "code": null, "e": 6256, "s": 6114, "text": "Type “outlook smtp” into Google. Without even clicking on a page, we are given the server address smtp-mail.outlook.com, and port number 587." }, { "code": null, "e": 6371, "s": 6256, "text": "We use both of these when initalizing the SMTP object with smtplib.SMTP — near the beginning of the send function." }, { "code": null, "e": 6640, "s": 6371, "text": "smtp.ehlo() and smtp.starttls() are both SMTP commands. ehlo (Extended Hello) essentially greets the server. starttls informs the server we will be communicating using an encrypted transport level security (TLS) connection. You can learn more about SMTP commands here." }, { "code": null, "e": 6747, "s": 6640, "text": "After this we simply read in our email and password from file, storing both in email and pwd respectively." }, { "code": null, "e": 6836, "s": 6747, "text": "We then login to the SMTP server with smtp.login, and send the email with smtp.sendmail." }, { "code": null, "e": 7089, "s": 6836, "text": "I always send the notifications to myself, but in the case of automated reporting (or for any other reason), you may want to send the email elsewhere. To do this, change the destination_address: smtp.sendmail(email, destination_address, msg.as_string)." }, { "code": null, "e": 7164, "s": 7089, "text": "Finally, we terminate the session and close the connection with smtp.quit." }, { "code": null, "e": 7343, "s": 7164, "text": "All of this is placed within a try-except statement. In the case of momentary network connection loss, we will be unable to connect to the server. Resulting in a socket.gaierror." }, { "code": null, "e": 7557, "s": 7343, "text": "Implementing this try-except statement prevents the program from breaking in the case of a lapse in network connection. How you deal with this may differ, depending on how important it is for the email to be sent." }, { "code": null, "e": 7758, "s": 7557, "text": "For me, I use this for ML model training updates and data transfer completion. If an email does not get sent, it doesn’t really matter. So this simple, passive handling of connection loss is suitable." }, { "code": null, "e": 7832, "s": 7758, "text": "Now we have written both parts of our code, we can send emails with just:" }, { "code": null, "e": 7998, "s": 7832, "text": "# build a message objectmsg = message(text=\"See attached!\", img='important.png', attachment='data.csv')send(msg) # send the email (defaults to Outlook)" }, { "code": null, "e": 8169, "s": 7998, "text": "Jason Farlette pointed out that those of you using Gmail may need to ‘allow access for less secure apps’. Steps for doing so can be found in this Stack Overflow question." }, { "code": null, "e": 8323, "s": 8169, "text": "That is all for email notification and/or automation using Python. Thanks to the email and smptlib libraries this is an incredibly easy process to setup." }, { "code": null, "e": 8464, "s": 8323, "text": "For any processing or training tasks that consume a lot of time, progress updates and notification on completion, is often truly liberating." }, { "code": null, "e": 8592, "s": 8464, "text": "I hope this article has been useful to a few of you out there, as always, let me know if you have any questions or suggestions!" }, { "code": null, "e": 8612, "s": 8592, "text": "Thanks for reading!" } ]
Bitwise Hacks for Competitive Programming - GeeksforGeeks
23 Feb, 2022 It is recommended to refer Interesting facts about Bitwise Operators as a prerequisite.1. How to set a bit in the number ‘num’ :If we want to set a bit at nth position in number ‘num’ ,it can be done using ‘OR’ operator( | ). First we left shift ‘1’ to n position via (1<<n) Then, use ‘OR’ operator to set bit at that position.’OR’ operator is used because it will set the bit even if the bit is unset previously in binary representation of number ‘num’. CPP #include<iostream>using namespace std;// num is the number and pos is the position// at which we want to set the bit.void set(int & num,int pos){ // First step is shift '1', second // step is bitwise OR num |= (1 << pos);}int main(){ int num = 4, pos = 1; set(num, pos); cout << (int)(num) << endl; return 0;} Output: 6 We have passed the parameter by ‘call by reference’ to make permanent changes in the number.2. How to unset/clear a bit at n’th position in the number ‘num’ : Suppose we want to unset a bit at nth position in number ‘num’ then we have to do this with the help of ‘AND’ (&) operator. First we left shift ‘1’ to n position via (1<<n) than we use bitwise NOT operator ‘~’ to unset this shifted ‘1’. Now after clearing this left shifted ‘1’ i.e making it to ‘0’ we will ‘AND'(&) with the number ‘num’ that will unset bit at nth position. C #include <iostream>using namespace std;// First step is to get a number that has all 1's except the given position.void unset(int &num,int pos){ //Second step is to bitwise and this number with given number num &= (~(1 << pos));}int main(){ int num = 7; int pos = 1; unset(num, pos); cout << num << endl; return 0;} Output: 5 3. Toggling a bit at nth position :Toggling means to turn bit ‘on'(1) if it was ‘off'(0) and to turn ‘off'(0) if it was ‘on'(1) previously.We will be using ‘XOR’ operator here which is this ‘^’. The reason behind ‘XOR’ operator is because of its properties. Properties of ‘XOR’ operator. 1^1 = 00^0 = 01^0 = 10^1 = 1 1^1 = 0 0^0 = 0 1^0 = 1 0^1 = 1 If two bits are different then ‘XOR’ operator returns a set bit(1) else it returns an unset bit(0). C #include <iostream>using namespace std;// First step is to shift 1,Second step is to XOR with given numbervoid toggle(int &num,int pos){ num ^= (1 << pos);}int main(){ int num = 4; int pos = 1; toggle(num, pos); cout << num << endl; return 0;} Output: 6 4. Checking if bit at nth position is set or unset: It is quite easily doable using ‘AND’ operator. Left shift ‘1’ to given position and then ‘AND'(‘&’). C #include <iostream>using namespace std; bool at_position(int num,int pos){ bool bit = num & (1<<pos); return bit;} int main(){ int num = 5; int pos = 0; bool bit = at_position(num, pos); cout << bit << endl; return 0;} Output: 1 Observe that we have first left shifted ‘1’ and then used ‘AND’ operator to get bit at that position. So if there is ‘1’ at position ‘pos’ in ‘num’, then after ‘AND’ our variable ‘bit’ will store ‘1’ else if there is ‘0’ at position ‘pos’ in the number ‘num’ than after ‘AND’ our variable bit will store ‘0’. Some more quick hacks: Inverting every bit of a number/1’s complement: If we want to invert every bit of a number i.e change bit ‘0’ to ‘1’ and bit ‘1’ to ‘0’.We can do this with the help of ‘~’ operator. For example : if number is num=00101100 (binary representation) so ‘~num’ will be ‘11010011’. This is also the ‘1s complement of number’. C #include <iostream>using namespace std;int main(){ int num = 4; // Inverting every bit of number num cout << (~num); return 0;} Output: -5 Two’s complement of the number: 2’s complement of a number is 1’s complement + 1. So formally we can have 2’s complement by finding 1s complement and adding 1 to the result i.e (~num+1) or what else we can do is using ‘-‘ operator. C #include <iostream>using namespace std;int main(){ int num = 4; int twos_complement = -num; cout << "This is two's complement " << twos_complement << endl; cout << "This is also two's complement " << (~num+1) << endl; return 0;} Output: This is two's complement -4 This is also two's complement -4 Stripping off the lowest set bit : In many situations we want to strip off the lowest set bit for example in Binary Indexed tree data structure, counting number of set bit in a number. We do something like this: X = X & (X-1) But how does it even work ?Let us see this by taking an example, let X = 1100.(X-1) inverts all the bits till it encounter lowest set ‘1’ and it also invert that lowest set ‘1’.X-1 becomes 1011. After ‘ANDing’ X with X-1 we get lowest set bit stripped. C #include <iostream>using namespace std;void strip_last_set_bit(int &num){ num = num & (num-1);}int main(){ int num = 7; strip_last_set_bit(num); cout << num << endl; return 0;} Output: 6 Getting lowest set bit of a number: This is done by using expression ‘X &(-X)’Let us see this by taking an example:Let X = 00101100. So ~X(1’s complement) will be ‘11010011’ and 2’s complement will be (~X+1 or -X) i.e ‘11010100’.So if we ‘AND’ original number ‘X’ with its two’s complement which is ‘-X’, we get lowest set bit. 00101100 & 11010100 ----------- 00000100 C #include <iostream>using namespace std;int lowest_set_bit(int num){ int ret = num & (-num); return ret;}int main(){ int num = 10; int ans = lowest_set_bit(num); cout << ans << endl; return 0;} Output: 2 Division by 2 and Multiplication by 2 are very frequently that too in loops in Competitive Programming so using Bitwise operators can help in speeding up the code. Divide by 2 using right shift operator: 00001100 >> 1 (00001100 is 12) ------------ 00000110 (00000110 is 6) C++ #include <iostream>using namespace std;int main(){ int num = 12; int ans = num>>1; cout << ans << endl; return 0;} 6 Multiply by 2 using left shift operator: 00001100 << 1 (00001100 is 12) ------------ 00011000 (00000110 is 24) C++ Python3 Javascript #include <iostream>using namespace std;int main(){ int num = 12; int ans = num<<1; cout << ans << endl; return 0;} # Python program for the above approach num = 12ans = num<<1print(ans) # This code is contributed by Shubham Singh <script>// Javascript program for the above approach var num = 12;var ans = num<<1;document.write(ans); //This code is contributed by Shubham Singh</script> 24 Bit Tricks for Competitive ProgrammingRefer BitWise Operators Articles for more articles on Bit Hacks.This article is contributed by Pankaj Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. 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 pulamolusaimohan thedev05 SHUBHAMSINGH10 altyon Bitwise-XOR C++ Competitive Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Socket Programming in C/C++ Templates in C++ with Examples Copy Constructor in C++ Polymorphism in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Top 10 Algorithms and Data Structures for Competitive Programming Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 24282, "s": 24254, "text": "\n23 Feb, 2022" }, { "code": null, "e": 24510, "s": 24282, "text": "It is recommended to refer Interesting facts about Bitwise Operators as a prerequisite.1. How to set a bit in the number ‘num’ :If we want to set a bit at nth position in number ‘num’ ,it can be done using ‘OR’ operator( | ). " }, { "code": null, "e": 24559, "s": 24510, "text": "First we left shift ‘1’ to n position via (1<<n)" }, { "code": null, "e": 24739, "s": 24559, "text": "Then, use ‘OR’ operator to set bit at that position.’OR’ operator is used because it will set the bit even if the bit is unset previously in binary representation of number ‘num’." }, { "code": null, "e": 24745, "s": 24741, "text": "CPP" }, { "code": "#include<iostream>using namespace std;// num is the number and pos is the position// at which we want to set the bit.void set(int & num,int pos){ // First step is shift '1', second // step is bitwise OR num |= (1 << pos);}int main(){ int num = 4, pos = 1; set(num, pos); cout << (int)(num) << endl; return 0;}", "e": 25083, "s": 24745, "text": null }, { "code": null, "e": 25093, "s": 25083, "text": "Output: " }, { "code": null, "e": 25095, "s": 25093, "text": "6" }, { "code": null, "e": 25256, "s": 25095, "text": "We have passed the parameter by ‘call by reference’ to make permanent changes in the number.2. How to unset/clear a bit at n’th position in the number ‘num’ : " }, { "code": null, "e": 25380, "s": 25256, "text": "Suppose we want to unset a bit at nth position in number ‘num’ then we have to do this with the help of ‘AND’ (&) operator." }, { "code": null, "e": 25495, "s": 25382, "text": "First we left shift ‘1’ to n position via (1<<n) than we use bitwise NOT operator ‘~’ to unset this shifted ‘1’." }, { "code": null, "e": 25633, "s": 25495, "text": "Now after clearing this left shifted ‘1’ i.e making it to ‘0’ we will ‘AND'(&) with the number ‘num’ that will unset bit at nth position." }, { "code": null, "e": 25637, "s": 25635, "text": "C" }, { "code": "#include <iostream>using namespace std;// First step is to get a number that has all 1's except the given position.void unset(int &num,int pos){ //Second step is to bitwise and this number with given number num &= (~(1 << pos));}int main(){ int num = 7; int pos = 1; unset(num, pos); cout << num << endl; return 0;}", "e": 25977, "s": 25637, "text": null }, { "code": null, "e": 25987, "s": 25977, "text": "Output: " }, { "code": null, "e": 25989, "s": 25987, "text": "5" }, { "code": null, "e": 26250, "s": 25989, "text": "3. Toggling a bit at nth position :Toggling means to turn bit ‘on'(1) if it was ‘off'(0) and to turn ‘off'(0) if it was ‘on'(1) previously.We will be using ‘XOR’ operator here which is this ‘^’. The reason behind ‘XOR’ operator is because of its properties. " }, { "code": null, "e": 26309, "s": 26250, "text": "Properties of ‘XOR’ operator. 1^1 = 00^0 = 01^0 = 10^1 = 1" }, { "code": null, "e": 26317, "s": 26309, "text": "1^1 = 0" }, { "code": null, "e": 26325, "s": 26317, "text": "0^0 = 0" }, { "code": null, "e": 26333, "s": 26325, "text": "1^0 = 1" }, { "code": null, "e": 26341, "s": 26333, "text": "0^1 = 1" }, { "code": null, "e": 26441, "s": 26341, "text": "If two bits are different then ‘XOR’ operator returns a set bit(1) else it returns an unset bit(0)." }, { "code": null, "e": 26445, "s": 26443, "text": "C" }, { "code": "#include <iostream>using namespace std;// First step is to shift 1,Second step is to XOR with given numbervoid toggle(int &num,int pos){ num ^= (1 << pos);}int main(){ int num = 4; int pos = 1; toggle(num, pos); cout << num << endl; return 0;}", "e": 26707, "s": 26445, "text": null }, { "code": null, "e": 26717, "s": 26707, "text": "Output: " }, { "code": null, "e": 26719, "s": 26717, "text": "6" }, { "code": null, "e": 26773, "s": 26719, "text": "4. Checking if bit at nth position is set or unset: " }, { "code": null, "e": 26821, "s": 26773, "text": "It is quite easily doable using ‘AND’ operator." }, { "code": null, "e": 26877, "s": 26823, "text": "Left shift ‘1’ to given position and then ‘AND'(‘&’)." }, { "code": null, "e": 26881, "s": 26879, "text": "C" }, { "code": "#include <iostream>using namespace std; bool at_position(int num,int pos){ bool bit = num & (1<<pos); return bit;} int main(){ int num = 5; int pos = 0; bool bit = at_position(num, pos); cout << bit << endl; return 0;}", "e": 27121, "s": 26881, "text": null }, { "code": null, "e": 27129, "s": 27121, "text": "Output:" }, { "code": null, "e": 27131, "s": 27129, "text": "1" }, { "code": null, "e": 27440, "s": 27131, "text": "Observe that we have first left shifted ‘1’ and then used ‘AND’ operator to get bit at that position. So if there is ‘1’ at position ‘pos’ in ‘num’, then after ‘AND’ our variable ‘bit’ will store ‘1’ else if there is ‘0’ at position ‘pos’ in the number ‘num’ than after ‘AND’ our variable bit will store ‘0’." }, { "code": null, "e": 27465, "s": 27440, "text": "Some more quick hacks: " }, { "code": null, "e": 27515, "s": 27465, "text": "Inverting every bit of a number/1’s complement: " }, { "code": null, "e": 27743, "s": 27515, "text": "If we want to invert every bit of a number i.e change bit ‘0’ to ‘1’ and bit ‘1’ to ‘0’.We can do this with the help of ‘~’ operator. For example : if number is num=00101100 (binary representation) so ‘~num’ will be ‘11010011’." }, { "code": null, "e": 27790, "s": 27745, "text": "This is also the ‘1s complement of number’. " }, { "code": null, "e": 27792, "s": 27790, "text": "C" }, { "code": "#include <iostream>using namespace std;int main(){ int num = 4; // Inverting every bit of number num cout << (~num); return 0;}", "e": 27933, "s": 27792, "text": null }, { "code": null, "e": 27945, "s": 27933, "text": "Output:\n -5" }, { "code": null, "e": 28027, "s": 27945, "text": "Two’s complement of the number: 2’s complement of a number is 1’s complement + 1." }, { "code": null, "e": 28177, "s": 28027, "text": "So formally we can have 2’s complement by finding 1s complement and adding 1 to the result i.e (~num+1) or what else we can do is using ‘-‘ operator." }, { "code": null, "e": 28179, "s": 28177, "text": "C" }, { "code": "#include <iostream>using namespace std;int main(){ int num = 4; int twos_complement = -num; cout << \"This is two's complement \" << twos_complement << endl; cout << \"This is also two's complement \" << (~num+1) << endl; return 0;}", "e": 28423, "s": 28179, "text": null }, { "code": null, "e": 28433, "s": 28423, "text": "Output: " }, { "code": null, "e": 28494, "s": 28433, "text": "This is two's complement -4\nThis is also two's complement -4" }, { "code": null, "e": 28531, "s": 28496, "text": "Stripping off the lowest set bit :" }, { "code": null, "e": 28683, "s": 28533, "text": "In many situations we want to strip off the lowest set bit for example in Binary Indexed tree data structure, counting number of set bit in a number." }, { "code": null, "e": 28712, "s": 28683, "text": "We do something like this: " }, { "code": null, "e": 28726, "s": 28712, "text": "X = X & (X-1)" }, { "code": null, "e": 28981, "s": 28726, "text": "But how does it even work ?Let us see this by taking an example, let X = 1100.(X-1) inverts all the bits till it encounter lowest set ‘1’ and it also invert that lowest set ‘1’.X-1 becomes 1011. After ‘ANDing’ X with X-1 we get lowest set bit stripped. " }, { "code": null, "e": 28983, "s": 28981, "text": "C" }, { "code": "#include <iostream>using namespace std;void strip_last_set_bit(int &num){ num = num & (num-1);}int main(){ int num = 7; strip_last_set_bit(num); cout << num << endl; return 0;}", "e": 29175, "s": 28983, "text": null }, { "code": null, "e": 29185, "s": 29175, "text": "Output: " }, { "code": null, "e": 29187, "s": 29185, "text": "6" }, { "code": null, "e": 29225, "s": 29189, "text": "Getting lowest set bit of a number:" }, { "code": null, "e": 29520, "s": 29225, "text": "This is done by using expression ‘X &(-X)’Let us see this by taking an example:Let X = 00101100. So ~X(1’s complement) will be ‘11010011’ and 2’s complement will be (~X+1 or -X) i.e ‘11010100’.So if we ‘AND’ original number ‘X’ with its two’s complement which is ‘-X’, we get lowest set bit. " }, { "code": null, "e": 29561, "s": 29520, "text": "00101100\n& 11010100\n-----------\n00000100" }, { "code": null, "e": 29565, "s": 29563, "text": "C" }, { "code": "#include <iostream>using namespace std;int lowest_set_bit(int num){ int ret = num & (-num); return ret;}int main(){ int num = 10; int ans = lowest_set_bit(num); cout << ans << endl; return 0;}", "e": 29776, "s": 29565, "text": null }, { "code": null, "e": 29786, "s": 29776, "text": "Output: " }, { "code": null, "e": 29788, "s": 29786, "text": "2" }, { "code": null, "e": 29952, "s": 29788, "text": "Division by 2 and Multiplication by 2 are very frequently that too in loops in Competitive Programming so using Bitwise operators can help in speeding up the code." }, { "code": null, "e": 29992, "s": 29952, "text": "Divide by 2 using right shift operator:" }, { "code": null, "e": 30061, "s": 29992, "text": "00001100 >> 1 (00001100 is 12)\n------------\n00000110 (00000110 is 6)" }, { "code": null, "e": 30065, "s": 30061, "text": "C++" }, { "code": "#include <iostream>using namespace std;int main(){ int num = 12; int ans = num>>1; cout << ans << endl; return 0;}", "e": 30192, "s": 30065, "text": null }, { "code": null, "e": 30194, "s": 30192, "text": "6" }, { "code": null, "e": 30235, "s": 30194, "text": "Multiply by 2 using left shift operator:" }, { "code": null, "e": 30305, "s": 30235, "text": "00001100 << 1 (00001100 is 12)\n------------\n00011000 (00000110 is 24)" }, { "code": null, "e": 30309, "s": 30305, "text": "C++" }, { "code": null, "e": 30317, "s": 30309, "text": "Python3" }, { "code": null, "e": 30328, "s": 30317, "text": "Javascript" }, { "code": "#include <iostream>using namespace std;int main(){ int num = 12; int ans = num<<1; cout << ans << endl; return 0;}", "e": 30455, "s": 30328, "text": null }, { "code": "# Python program for the above approach num = 12ans = num<<1print(ans) # This code is contributed by Shubham Singh", "e": 30570, "s": 30455, "text": null }, { "code": "<script>// Javascript program for the above approach var num = 12;var ans = num<<1;document.write(ans); //This code is contributed by Shubham Singh</script>", "e": 30727, "s": 30570, "text": null }, { "code": null, "e": 30730, "s": 30727, "text": "24" }, { "code": null, "e": 31224, "s": 30730, "text": "Bit Tricks for Competitive ProgrammingRefer BitWise Operators Articles for more articles on Bit Hacks.This article is contributed by Pankaj Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. 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": 31230, "s": 31224, "text": "jit_t" }, { "code": null, "e": 31247, "s": 31230, "text": "pulamolusaimohan" }, { "code": null, "e": 31256, "s": 31247, "text": "thedev05" }, { "code": null, "e": 31271, "s": 31256, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 31278, "s": 31271, "text": "altyon" }, { "code": null, "e": 31290, "s": 31278, "text": "Bitwise-XOR" }, { "code": null, "e": 31294, "s": 31290, "text": "C++" }, { "code": null, "e": 31318, "s": 31294, "text": "Competitive Programming" }, { "code": null, "e": 31322, "s": 31318, "text": "CPP" }, { "code": null, "e": 31420, "s": 31322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31448, "s": 31420, "text": "Operator Overloading in C++" }, { "code": null, "e": 31476, "s": 31448, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31507, "s": 31476, "text": "Templates in C++ with Examples" }, { "code": null, "e": 31531, "s": 31507, "text": "Copy Constructor in C++" }, { "code": null, "e": 31551, "s": 31531, "text": "Polymorphism in C++" }, { "code": null, "e": 31594, "s": 31551, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31637, "s": 31594, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31678, "s": 31637, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31744, "s": 31678, "text": "Top 10 Algorithms and Data Structures for Competitive Programming" } ]
Program to find minimum swaps required to make given anagram in python
Suppose we have two strings S and T and they are anagrams of each other. We have to find the minimum number of swaps required in S to make it same as T. So, if the input is like S = "kolkata" T = "katloka", then the output will be 3, as can swap in this sequence [katloka (given), kotlaka, koltaka, kolkata]. To solve this, we will follow these steps − Define a function util() . This will take S, T, i if i >= size of S , thenreturn 0 return 0 if S[i] is same as T[i], thenreturn util(S, T, i + 1) return util(S, T, i + 1) x := T[i] ret := 99999 for j in range i + 1 to size of T, doif x is same as S[j], thenswap S[i] and S[j]ret := minimum of ret and (1 + util(S, T, i + 1))swap S[i] and S[j] if x is same as S[j], thenswap S[i] and S[j]ret := minimum of ret and (1 + util(S, T, i + 1))swap S[i] and S[j] swap S[i] and S[j] ret := minimum of ret and (1 + util(S, T, i + 1)) swap S[i] and S[j] return ret From the main method do the following: return util(S, T, 0) Let us see the following implementation to get better understanding − Live Demo class Solution: def util(self, S, T, i) : S = list(S) T = list(T) if i >= len(S): return 0 if S[i] == T[i]: return self.util(S, T, i + 1) x = T[i] ret = 99999; for j in range(i + 1, len(T)): if x == S[j]: S[i], S[j] = S[j], S[i] ret = min(ret, 1 + self.util(S, T, i + 1)) S[i], S[j] = S[j], S[i] return ret def solve(self, S, T): return self.util(S, T, 0) ob = Solution() S = "kolkata" T = "katloka" print(ob.solve(S, T)) "kolkata", "katloka" 3
[ { "code": null, "e": 1215, "s": 1062, "text": "Suppose we have two strings S and T and they are anagrams of each other. We have to find the minimum number of swaps required in S to make it same as T." }, { "code": null, "e": 1371, "s": 1215, "text": "So, if the input is like S = \"kolkata\" T = \"katloka\", then the output will be 3, as can swap in this sequence [katloka (given), kotlaka, koltaka, kolkata]." }, { "code": null, "e": 1415, "s": 1371, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1465, "s": 1415, "text": "Define a function util() . This will take S, T, i" }, { "code": null, "e": 1498, "s": 1465, "text": "if i >= size of S , thenreturn 0" }, { "code": null, "e": 1507, "s": 1498, "text": "return 0" }, { "code": null, "e": 1561, "s": 1507, "text": "if S[i] is same as T[i], thenreturn util(S, T, i + 1)" }, { "code": null, "e": 1586, "s": 1561, "text": "return util(S, T, i + 1)" }, { "code": null, "e": 1596, "s": 1586, "text": "x := T[i]" }, { "code": null, "e": 1609, "s": 1596, "text": "ret := 99999" }, { "code": null, "e": 1758, "s": 1609, "text": "for j in range i + 1 to size of T, doif x is same as S[j], thenswap S[i] and S[j]ret := minimum of ret and (1 + util(S, T, i + 1))swap S[i] and S[j]" }, { "code": null, "e": 1870, "s": 1758, "text": "if x is same as S[j], thenswap S[i] and S[j]ret := minimum of ret and (1 + util(S, T, i + 1))swap S[i] and S[j]" }, { "code": null, "e": 1889, "s": 1870, "text": "swap S[i] and S[j]" }, { "code": null, "e": 1939, "s": 1889, "text": "ret := minimum of ret and (1 + util(S, T, i + 1))" }, { "code": null, "e": 1958, "s": 1939, "text": "swap S[i] and S[j]" }, { "code": null, "e": 1969, "s": 1958, "text": "return ret" }, { "code": null, "e": 2008, "s": 1969, "text": "From the main method do the following:" }, { "code": null, "e": 2029, "s": 2008, "text": "return util(S, T, 0)" }, { "code": null, "e": 2099, "s": 2029, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2109, "s": 2099, "text": "Live Demo" }, { "code": null, "e": 2661, "s": 2109, "text": "class Solution:\n def util(self, S, T, i) :\n S = list(S)\n T = list(T)\n if i >= len(S):\n return 0\n if S[i] == T[i]:\n return self.util(S, T, i + 1)\n x = T[i]\n ret = 99999;\n for j in range(i + 1, len(T)):\n if x == S[j]:\n S[i], S[j] = S[j], S[i]\n ret = min(ret, 1 + self.util(S, T, i + 1))\n S[i], S[j] = S[j], S[i]\n return ret\n \n def solve(self, S, T):\n return self.util(S, T, 0)\n\nob = Solution()\nS = \"kolkata\"\nT = \"katloka\"\nprint(ob.solve(S, T))" }, { "code": null, "e": 2682, "s": 2661, "text": "\"kolkata\", \"katloka\"" }, { "code": null, "e": 2684, "s": 2682, "text": "3" } ]
Python MongoDB - Limit
While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result. Following is the syntax of the limit() method − >db.COLLECTION_NAME.find().limit(NUMBER) Assume we have created a collection and inserted 5 documents into it as shown below − > use testDB switched to db testDB > db.createCollection("sample") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Following line retrieves the first 3 documents of the collection. > db.sample.find().limit(3) { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result. Following example retrieves first three documents in a collection. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['l'] #Creating a collection coll = db['myColl'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving first 3 documents using the find() and limit() methods print("First 3 documents in the collection: ") for doc1 in coll.find().limit(3): print(doc1) Data inserted ...... First 3 documents in the collection: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3425, "s": 3205, "text": "While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result." }, { "code": null, "e": 3473, "s": 3425, "text": "Following is the syntax of the limit() method −" }, { "code": null, "e": 3515, "s": 3473, "text": ">db.COLLECTION_NAME.find().limit(NUMBER)\n" }, { "code": null, "e": 3601, "s": 3515, "text": "Assume we have created a collection and inserted 5 documents into it as shown below −" }, { "code": null, "e": 4342, "s": 3601, "text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 4408, "s": 4342, "text": "Following line retrieves the first 3 documents of the collection." }, { "code": null, "e": 4648, "s": 4408, "text": "> db.sample.find().limit(3)\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n" }, { "code": null, "e": 4852, "s": 4648, "text": "To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result." }, { "code": null, "e": 4919, "s": 4852, "text": "Following example retrieves first three documents in a collection." }, { "code": null, "e": 5796, "s": 4919, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['l']\n\n#Creating a collection\ncoll = db['myColl']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving first 3 documents using the find() and limit() methods\nprint(\"First 3 documents in the collection: \")\n\nfor doc1 in coll.find().limit(3):\n print(doc1)" }, { "code": null, "e": 6052, "s": 5796, "text": "Data inserted ......\nFirst 3 documents in the collection:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 6089, "s": 6052, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6105, "s": 6089, "text": " Malhar Lathkar" }, { "code": null, "e": 6138, "s": 6105, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6157, "s": 6138, "text": " Arnab Chakraborty" }, { "code": null, "e": 6192, "s": 6157, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6214, "s": 6192, "text": " In28Minutes Official" }, { "code": null, "e": 6248, "s": 6214, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6276, "s": 6248, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6311, "s": 6276, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6325, "s": 6311, "text": " Lets Kode It" }, { "code": null, "e": 6358, "s": 6325, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6375, "s": 6358, "text": " Abhilash Nelson" }, { "code": null, "e": 6382, "s": 6375, "text": " Print" }, { "code": null, "e": 6393, "s": 6382, "text": " Add Notes" } ]
How can we import data from .CSV file into MySQL table?
Actually.CSV is also a text file in which the values are separated by commas or in other words we can say that text file with CSV(comma separated values). We need to use FIELDS SEPARATED OPTION with LOAD DATA INFILE statement while importing the data from .CSV file to MySQL table. We are considering the following example to make it understand − Followings are the comma separated values in A.CSV file − 105,Chum,USA,11000 106,Danny,AUS,12000 We want to import this data into the following file named employee1_tbl − mysql> Create table employee1_tbl(Id Int, Name Varchar(20), Country Varchar(20),Salary Int); Query OK, 0 rows affected (0.91 sec) Now, the transfer of data from a file to a database table can be done with the help of the following table − mysql> LOAD DATA LOCAL INFILE 'd:\A.csv' INTO table employee1_tbl FIELDS TERMINATED BY ','; Query OK, 2 rows affected (0.16 sec) Records: 2 Deleted: 0 Skipped: 0 Warnings: 0 mysql> Select * from employee1_tbl; +------+-------+---------+--------+ | Id | Name | Country | Salary | +------+-------+---------+--------+ | 105 | Chum | USA | 11000 | | 106 | Danny | AUS | 12000 | +------+-------+---------+--------+ 2 rows in set (0.00 sec) The above result set shows that the data from A.CSV file has been transferred to the table.
[ { "code": null, "e": 1409, "s": 1062, "text": "Actually.CSV is also a text file in which the values are separated by commas or in other words we can say that text file with CSV(comma separated values). We need to use FIELDS SEPARATED OPTION with LOAD DATA INFILE statement while importing the data from .CSV file to MySQL table. We are considering the following example to make it understand −" }, { "code": null, "e": 1467, "s": 1409, "text": "Followings are the comma separated values in A.CSV file −" }, { "code": null, "e": 1506, "s": 1467, "text": "105,Chum,USA,11000\n106,Danny,AUS,12000" }, { "code": null, "e": 1580, "s": 1506, "text": "We want to import this data into the following file named employee1_tbl −" }, { "code": null, "e": 1711, "s": 1580, "text": "mysql> Create table employee1_tbl(Id Int, Name Varchar(20), Country Varchar(20),Salary Int);\n\nQuery OK, 0 rows affected (0.91 sec)" }, { "code": null, "e": 1820, "s": 1711, "text": "Now, the transfer of data from a file to a database table can be done with the help of the following table −" }, { "code": null, "e": 2272, "s": 1820, "text": "mysql> LOAD DATA LOCAL INFILE 'd:\\A.csv' INTO table employee1_tbl FIELDS TERMINATED BY ',';\nQuery OK, 2 rows affected (0.16 sec)\nRecords: 2 Deleted: 0 Skipped: 0 Warnings: 0\n\nmysql> Select * from employee1_tbl;\n+------+-------+---------+--------+\n| Id | Name | Country | Salary |\n+------+-------+---------+--------+\n| 105 | Chum | USA | 11000 |\n| 106 | Danny | AUS | 12000 |\n+------+-------+---------+--------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2364, "s": 2272, "text": "The above result set shows that the data from A.CSV file has been transferred to the table." } ]
Classical Neural Network: What really are Nodes and Layers? | by Michael Chan | Towards Data Science
We have spoken previously about activation functions, and as promised we will explain its link with the layers and the nodes in an architecture of neural networks. Note that this is an explanation for classical Neural Network and not specialized ones. This knowledge will despite it, be of use when studying specific neural networks. Alright, all being said, let’s get started. First, we will be taking as an example the following very simple architecture of neural network (NN). (fig. 1) Input Layer: Node1 → X | Activation: sigmoid Hidden Layer: Node1 →N1 and Node2 → N2 (from top to bottom) | Activation: sigmoid Output Layer: Node1 → M | Activation #This code is the keras implementation of the above described NNdef simple_nn(): model = Sequential() model.add(Dense(2, input_dim=1, activation='sigmoid')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='mean_squared_error', optimizer='sgd') return model Given the above notations, we get the following function (fig.2): Here multiple things are to be noticed: The output of the neural network will always belong to [0,1]. As we mentioned in the activation functions article, the output layer activation function is very much important and pretty much defines the type of model you want to achieve (i.e classification/regression etc...) With only one hidden layer composed of two nodes, we end up with a vector of weights of dimensionality 7. That puts in perspective of difficult the training is when the number of nodes increases. Except for activation functions, operations are linear combinations. Again, activation functions introduce non-linearity. First of all, even though Deep Learning (studies of numerous layers NN) is a category of study by itself, it nonetheless has the same goal as classical Machine Learning: “approaching a specific underlying model/distribution from data points (most of the times)”. Therefore the goal of a NN is also to approach a distribution i.e a function, but then how so? Here intervenes some basic knowledge about Analysis, brace yourself! For simplicity's sake (you can contact me if you are interested to know the more general explanation), we will be changing to the following architecture. Here is its function (fig.3): Let’s first start with a continuous function from reals to reals. Let’s fix ourselves the goal to approach such a function. A canonical way of starting this is to first plot the function our NN represents (fig.3). Since we do not need any specific data to explain the idea, we will not be training the NN and will simply be assigning weights arbitrarily (fig.4). Here is the plot (fig.5): Surprise! What kind of shape is this? A rectangle !!! So our Neural network is actually mimicking the distribution of a rectangle (more or less). For some, this might not seem special, but for some others that have heard of Riemman Integration and step functions, for instance, will more or less see where I am heading to. Exactly, an approximation of the continuous function by step functions like neural network (not exactly a step function but summing up does the job). Few things again to note: The sharpness of the edges for the rectangle is defined by the scalar in front of X and the position of the high-value derivative is defined by the scalar added to the product. Two nodes are enough to make a rectangle, and therefore to approach the continuous function, we simply need to add nodes! (in case of an odd number of nodes, we will simply have rectangles and a step function) Even though it is harder to picture, the approximation of continuous function in higher dimensions works pretty much the same (except for one step where we rescale values). Now that we have seen such approximations, we can be confident in the power of NN to approach a distribution (even if non-continuous). But this explanation still lacks something, we arbitrarily gave some accurate weights to our NN, but unfortunately, we are unable to do such a thing in general datasets since we ignore the distribution. And here intervenes optimization techniques such as the famous SGD (Stochastic Gradient Descent) or Batch GD (etc...). Assuming that these optimizations do get us to a close enough solution, this will imply that we overperformed the original weights (for rectangles) that we were giving. Showing the example above (rectangles) is somehow giving a lower bound to accuracy, even though the mentioned technique seemed optimal, the optimization of weights might not necessarily converge toward the technique’s optimal but will again, outperform it. Thanks for reading and stay tuned for further articles. Also, a nice click on this link (toward the affiliate program) would really help me out! You will simply have to achieve some quick tasks (simply wait and activate notifications) and all of that will really help me out for more future hardware related content!
[ { "code": null, "e": 336, "s": 172, "text": "We have spoken previously about activation functions, and as promised we will explain its link with the layers and the nodes in an architecture of neural networks." }, { "code": null, "e": 506, "s": 336, "text": "Note that this is an explanation for classical Neural Network and not specialized ones. This knowledge will despite it, be of use when studying specific neural networks." }, { "code": null, "e": 550, "s": 506, "text": "Alright, all being said, let’s get started." }, { "code": null, "e": 661, "s": 550, "text": "First, we will be taking as an example the following very simple architecture of neural network (NN). (fig. 1)" }, { "code": null, "e": 706, "s": 661, "text": "Input Layer: Node1 → X | Activation: sigmoid" }, { "code": null, "e": 788, "s": 706, "text": "Hidden Layer: Node1 →N1 and Node2 → N2 (from top to bottom) | Activation: sigmoid" }, { "code": null, "e": 825, "s": 788, "text": "Output Layer: Node1 → M | Activation" }, { "code": null, "e": 1110, "s": 825, "text": "#This code is the keras implementation of the above described NNdef simple_nn(): model = Sequential() model.add(Dense(2, input_dim=1, activation='sigmoid')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='mean_squared_error', optimizer='sgd') return model" }, { "code": null, "e": 1176, "s": 1110, "text": "Given the above notations, we get the following function (fig.2):" }, { "code": null, "e": 1216, "s": 1176, "text": "Here multiple things are to be noticed:" }, { "code": null, "e": 1492, "s": 1216, "text": "The output of the neural network will always belong to [0,1]. As we mentioned in the activation functions article, the output layer activation function is very much important and pretty much defines the type of model you want to achieve (i.e classification/regression etc...)" }, { "code": null, "e": 1688, "s": 1492, "text": "With only one hidden layer composed of two nodes, we end up with a vector of weights of dimensionality 7. That puts in perspective of difficult the training is when the number of nodes increases." }, { "code": null, "e": 1810, "s": 1688, "text": "Except for activation functions, operations are linear combinations. Again, activation functions introduce non-linearity." }, { "code": null, "e": 2237, "s": 1810, "text": "First of all, even though Deep Learning (studies of numerous layers NN) is a category of study by itself, it nonetheless has the same goal as classical Machine Learning: “approaching a specific underlying model/distribution from data points (most of the times)”. Therefore the goal of a NN is also to approach a distribution i.e a function, but then how so? Here intervenes some basic knowledge about Analysis, brace yourself!" }, { "code": null, "e": 2421, "s": 2237, "text": "For simplicity's sake (you can contact me if you are interested to know the more general explanation), we will be changing to the following architecture. Here is its function (fig.3):" }, { "code": null, "e": 2784, "s": 2421, "text": "Let’s first start with a continuous function from reals to reals. Let’s fix ourselves the goal to approach such a function. A canonical way of starting this is to first plot the function our NN represents (fig.3). Since we do not need any specific data to explain the idea, we will not be training the NN and will simply be assigning weights arbitrarily (fig.4)." }, { "code": null, "e": 2810, "s": 2784, "text": "Here is the plot (fig.5):" }, { "code": null, "e": 2864, "s": 2810, "text": "Surprise! What kind of shape is this? A rectangle !!!" }, { "code": null, "e": 3283, "s": 2864, "text": "So our Neural network is actually mimicking the distribution of a rectangle (more or less). For some, this might not seem special, but for some others that have heard of Riemman Integration and step functions, for instance, will more or less see where I am heading to. Exactly, an approximation of the continuous function by step functions like neural network (not exactly a step function but summing up does the job)." }, { "code": null, "e": 3309, "s": 3283, "text": "Few things again to note:" }, { "code": null, "e": 3486, "s": 3309, "text": "The sharpness of the edges for the rectangle is defined by the scalar in front of X and the position of the high-value derivative is defined by the scalar added to the product." }, { "code": null, "e": 3696, "s": 3486, "text": "Two nodes are enough to make a rectangle, and therefore to approach the continuous function, we simply need to add nodes! (in case of an odd number of nodes, we will simply have rectangles and a step function)" }, { "code": null, "e": 3869, "s": 3696, "text": "Even though it is harder to picture, the approximation of continuous function in higher dimensions works pretty much the same (except for one step where we rescale values)." }, { "code": null, "e": 4752, "s": 3869, "text": "Now that we have seen such approximations, we can be confident in the power of NN to approach a distribution (even if non-continuous). But this explanation still lacks something, we arbitrarily gave some accurate weights to our NN, but unfortunately, we are unable to do such a thing in general datasets since we ignore the distribution. And here intervenes optimization techniques such as the famous SGD (Stochastic Gradient Descent) or Batch GD (etc...). Assuming that these optimizations do get us to a close enough solution, this will imply that we overperformed the original weights (for rectangles) that we were giving. Showing the example above (rectangles) is somehow giving a lower bound to accuracy, even though the mentioned technique seemed optimal, the optimization of weights might not necessarily converge toward the technique’s optimal but will again, outperform it." } ]
Compressing string in JavaScript
We are required to write a JavaScript function that takes in a string that might contain some continuous repeating characters. The function should compress the string like this − 'wwwaabbbb' -> 'w3a2b4' 'kkkkj' -> 'k4j' And if the length of the compressed string is greater than or equal to the original string we should return the original string. For example − 'aab' can be compressed to 'a2b1' but it increases its length to 4 so our function should return 'aab' The code for this will be − Live Demo const str1 = 'wwwaabbbb'; const str2 = 'kkkkj'; const str3 = 'aab'; const compressString = (str = '') => { let res = ''; let count = 1; for(let i = 0; i < str.length; i++){ let cur = str[i]; let next = str[i + 1]; if(cur === next){ count++; }else{ res += cur + String(count); count = 1; }; } return res.length < str.length ? res : str; }; console.log(compressString(str1)); console.log(compressString(str2)); console.log(compressString(str3)); And the output in the console will be − 3a2b4 k4j1 aab
[ { "code": null, "e": 1189, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string that might contain some continuous repeating characters." }, { "code": null, "e": 1241, "s": 1189, "text": "The function should compress the string like this −" }, { "code": null, "e": 1282, "s": 1241, "text": "'wwwaabbbb' -> 'w3a2b4'\n'kkkkj' -> 'k4j'" }, { "code": null, "e": 1411, "s": 1282, "text": "And if the length of the compressed string is greater than or equal to the original string we should return the original string." }, { "code": null, "e": 1425, "s": 1411, "text": "For example −" }, { "code": null, "e": 1528, "s": 1425, "text": "'aab' can be compressed to 'a2b1' but it increases its length to 4 so our function should return 'aab'" }, { "code": null, "e": 1556, "s": 1528, "text": "The code for this will be −" }, { "code": null, "e": 1567, "s": 1556, "text": " Live Demo" }, { "code": null, "e": 2083, "s": 1567, "text": "const str1 = 'wwwaabbbb';\nconst str2 = 'kkkkj';\nconst str3 = 'aab';\nconst compressString = (str = '') => {\n let res = '';\n let count = 1;\n for(let i = 0; i < str.length; i++){\n let cur = str[i];\n let next = str[i + 1];\n if(cur === next){\n count++;\n }else{\n res += cur + String(count);\n count = 1;\n };\n }\n return res.length < str.length ? res : str;\n};\nconsole.log(compressString(str1));\nconsole.log(compressString(str2));\nconsole.log(compressString(str3));" }, { "code": null, "e": 2123, "s": 2083, "text": "And the output in the console will be −" }, { "code": null, "e": 2138, "s": 2123, "text": "3a2b4\nk4j1\naab" } ]
Scope of Variables in C#
The scope of a variable is a region of code that indicates where the variables are being accessed. For a variable, it has the following levels − Variable declared inside a method is a local variable. Variable declared inside a class is a local variable are class member variables. Let us see an example of scope of variables − Live Demo using System; namespace Demo { class Program { public int Divide(int num1, int num2) { // local variable in a method int result; result = num1 / num2; return result; } static void Main(string[] args) { // local variable int a = 150; int b = 10; int res; Program p = new Program(); res = p.Divide(a, b); Console.WriteLine("Division Result = {0}", res ); Console.ReadLine(); } } } Division Result = 15
[ { "code": null, "e": 1161, "s": 1062, "text": "The scope of a variable is a region of code that indicates where the variables are being accessed." }, { "code": null, "e": 1207, "s": 1161, "text": "For a variable, it has the following levels −" }, { "code": null, "e": 1262, "s": 1207, "text": "Variable declared inside a method is a local variable." }, { "code": null, "e": 1343, "s": 1262, "text": "Variable declared inside a class is a local variable are class member variables." }, { "code": null, "e": 1389, "s": 1343, "text": "Let us see an example of scope of variables −" }, { "code": null, "e": 1400, "s": 1389, "text": " Live Demo" }, { "code": null, "e": 1918, "s": 1400, "text": "using System;\n\nnamespace Demo {\n class Program {\n public int Divide(int num1, int num2) {\n // local variable in a method\n int result;\n result = num1 / num2;\n return result;\n }\n static void Main(string[] args) {\n // local variable\n int a = 150;\n int b = 10;\n int res;\n Program p = new Program();\n res = p.Divide(a, b);\n Console.WriteLine(\"Division Result = {0}\", res );\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1939, "s": 1918, "text": "Division Result = 15" } ]
Spring Boot - Database Handling
Spring Boot provides a very good support to create a DataSource for Database. We need not write any extra code to create a DataSource in Spring Boot. Just adding the dependencies and doing the configuration details is enough to create a DataSource and connect the Database. In this chapter, we are going to use Spring Boot JDBC driver connection to connect the database. First, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Maven users can add the following dependencies in the pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> Gradle users can add the following dependencies in the build.gradle file. compile('org.springframework.boot:spring-boot-starter-jdbc') To connect the H2 database, we need to add the H2 database dependency in our build configuration file. For Maven users, add the below dependency in your pom.xml file. <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> For Gradle users, add the below dependency in your build.gradle file. compile('com.h2database:h2') We need to create the schema.sql file and data.sql file under the classpath src/main/resources directory to connect the H2 database. The schema.sql file is given below. CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25)); The data.sql file is given below. INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,'Honey'); INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,'Almond'); To connect the MySQL database, we need to add the MySQL dependency into our build configuration file. For Maven users, add the following dependency in your pom.xml file. <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> For Gradle users, add the following dependency in your build.gradle file. compile('mysql:mysql-connector-java') Now, create database and tables in MySQL as shown − For properties file users, add the following properties in the application.properties file. spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true spring.datasource.username = root spring.datasource.password = root spring.datasource.testOnBorrow = true spring.datasource.testWhileIdle = true spring.datasource.timeBetweenEvictionRunsMillis = 60000 spring.datasource.minEvictableIdleTimeMillis = 30000 spring.datasource.validationQuery = SELECT 1 spring.datasource.max-active = 15 spring.datasource.max-idle = 10 spring.datasource.max-wait = 8000 For YAML users, add the following properties in the application.yml file. spring: datasource: driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true" username: "root" password: "root" testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 Redis is an open source database used to store the in-memory data structure. To connect the Redis database in Spring Boot application, we need to add the Redis dependency in our build configuration file. Maven users should add the following dependency in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> Gradle users should add the following dependency in your build.gradle file. compile('org.springframework.boot:spring-boot-starter-data-redis') For Redis connection, we need to use RedisTemplate. For RedisTemplate we need to provide the JedisConnectionFactory details. @Bean JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(); jedisConFactory.setHostName("localhost"); jedisConFactory.setPort(6000); jedisConFactory.setUsePool(true); return jedisConFactory; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); return template; } Now auto wire the RedisTemplate class and access the data from Redis database. @Autowired RedisTemplate<String, Object> redis; Map<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”); To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object. @Autowired JdbcTemplate jdbcTemplate; Collection<Map<String, Object>> rows = jdbc.queryForList("SELECT QUERY"); The @Repository annotation should be added into the class file. The @Repository annotation is used to create database repository for your Spring Boot application. @Repository public class ProductServiceDAO { } We can keep ‘n’ number Datasources in a single Spring Boot application. The example given here shows how to create more than 1 data source in Spring Boot application. Now, add the two data source configuration details in the application properties file. For properties file users, add the following properties into your application.properties file. spring.dbProductService.driverClassName = com.mysql.jdbc.Driver spring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true spring.dbProductService.username = root spring.dbProductService.password = root spring.dbProductService.testOnBorrow = true spring.dbProductService.testWhileIdle = true spring.dbProductService.timeBetweenEvictionRunsMillis = 60000 spring.dbProductService.minEvictableIdleTimeMillis = 30000 spring.dbProductService.validationQuery = SELECT 1 spring.dbProductService.max-active = 15 spring.dbProductService.max-idle = 10 spring.dbProductService.max-wait = 8000 spring.dbUserService.driverClassName = com.mysql.jdbc.Driver spring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = true spring.dbUserService.username = root spring.dbUserService.password = root spring.dbUserService.testOnBorrow = true spring.dbUserService.testWhileIdle = true spring.dbUserService.timeBetweenEvictionRunsMillis = 60000 spring.dbUserService.minEvictableIdleTimeMillis = 30000 spring.dbUserService.validationQuery = SELECT 1 spring.dbUserService.max-active = 15 spring.dbUserService.max-idle = 10 spring.dbUserService.max-wait = 8000 Yaml users should add the following properties in your application.yml file. spring: dbProductService: driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true" password: "root" username: "root" testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 dbUserService: driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true" password: "root" username: "root" testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 Now, create a Configuration class to create a DataSource and JdbcTemplate for multiple data sources. import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class DatabaseConfig { @Bean(name = "dbProductService") @ConfigurationProperties(prefix = "spring.dbProductService") @Primary public DataSource createProductServiceDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "dbUserService") @ConfigurationProperties(prefix = "spring.dbUserService") public DataSource createUserServiceDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "jdbcProductService") @Autowired public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier("dbProductService") DataSource productServiceDS) { return new JdbcTemplate(productServiceDS); } @Bean(name = "jdbcUserService") @Autowired public JdbcTemplate createJdbcTemplate_UserService(@Qualifier("dbUserService") DataSource userServiceDS) { return new JdbcTemplate(userServiceDS); } } Then, auto wire the JDBCTemplate object by using @Qualifier annotation. @Qualifier("jdbcProductService") @Autowired JdbcTemplate jdbcTemplate; @Qualifier("jdbcUserService") @Autowired JdbcTemplate jdbcTemplate; 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3299, "s": 3025, "text": "Spring Boot provides a very good support to create a DataSource for Database. We need not write any extra code to create a DataSource in Spring Boot. Just adding the dependencies and doing the configuration details is enough to create a DataSource and connect the Database." }, { "code": null, "e": 3396, "s": 3299, "text": "In this chapter, we are going to use Spring Boot JDBC driver connection to connect the database." }, { "code": null, "e": 3491, "s": 3396, "text": "First, we need to add the Spring Boot Starter JDBC dependency in our build configuration file." }, { "code": null, "e": 3559, "s": 3491, "text": "Maven users can add the following dependencies in the pom.xml file." }, { "code": null, "e": 3686, "s": 3559, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-jdbc</artifactId>\n</dependency>" }, { "code": null, "e": 3760, "s": 3686, "text": "Gradle users can add the following dependencies in the build.gradle file." }, { "code": null, "e": 3822, "s": 3760, "text": "compile('org.springframework.boot:spring-boot-starter-jdbc')\n" }, { "code": null, "e": 3925, "s": 3822, "text": "To connect the H2 database, we need to add the H2 database dependency in our build configuration file." }, { "code": null, "e": 3989, "s": 3925, "text": "For Maven users, add the below dependency in your pom.xml file." }, { "code": null, "e": 4084, "s": 3989, "text": "<dependency>\n <groupId>com.h2database</groupId>\n <artifactId>h2</artifactId>\n</dependency>" }, { "code": null, "e": 4154, "s": 4084, "text": "For Gradle users, add the below dependency in your build.gradle file." }, { "code": null, "e": 4184, "s": 4154, "text": "compile('com.h2database:h2')\n" }, { "code": null, "e": 4317, "s": 4184, "text": "We need to create the schema.sql file and data.sql file under the classpath src/main/resources directory to connect the H2 database." }, { "code": null, "e": 4353, "s": 4317, "text": "The schema.sql file is given below." }, { "code": null, "e": 4423, "s": 4353, "text": "CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25));\n" }, { "code": null, "e": 4457, "s": 4423, "text": "The data.sql file is given below." }, { "code": null, "e": 4575, "s": 4457, "text": "INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,'Honey');\nINSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,'Almond');\n" }, { "code": null, "e": 4677, "s": 4575, "text": "To connect the MySQL database, we need to add the MySQL dependency into our build configuration file." }, { "code": null, "e": 4745, "s": 4677, "text": "For Maven users, add the following dependency in your pom.xml file." }, { "code": null, "e": 4849, "s": 4745, "text": "<dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n</dependency>" }, { "code": null, "e": 4923, "s": 4849, "text": "For Gradle users, add the following dependency in your build.gradle file." }, { "code": null, "e": 4962, "s": 4923, "text": "compile('mysql:mysql-connector-java')\n" }, { "code": null, "e": 5014, "s": 4962, "text": "Now, create database and tables in MySQL as shown −" }, { "code": null, "e": 5106, "s": 5014, "text": "For properties file users, add the following properties in the application.properties file." }, { "code": null, "e": 5651, "s": 5106, "text": "spring.datasource.driverClassName = com.mysql.jdbc.Driver\nspring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true\nspring.datasource.username = root\nspring.datasource.password = root\nspring.datasource.testOnBorrow = true\nspring.datasource.testWhileIdle = true\nspring.datasource.timeBetweenEvictionRunsMillis = 60000\nspring.datasource.minEvictableIdleTimeMillis = 30000\nspring.datasource.validationQuery = SELECT 1\nspring.datasource.max-active = 15\nspring.datasource.max-idle = 10\nspring.datasource.max-wait = 8000" }, { "code": null, "e": 5725, "s": 5651, "text": "For YAML users, add the following properties in the application.yml file." }, { "code": null, "e": 6142, "s": 5725, "text": "spring:\n datasource: \n driverClassName: com.mysql.jdbc.Driver\n url: \"jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true\"\n username: \"root\"\n password: \"root\"\n testOnBorrow: true\n testWhileIdle: true\n timeBetweenEvictionRunsMillis: 60000\n minEvictableIdleTimeMillis: 30000\n validationQuery: SELECT 1\n max-active: 15\n max-idle: 10\n max-wait: 8000" }, { "code": null, "e": 6346, "s": 6142, "text": "Redis is an open source database used to store the in-memory data structure. To connect the Redis database in Spring Boot application, we need to add the Redis dependency in our build configuration file." }, { "code": null, "e": 6416, "s": 6346, "text": "Maven users should add the following dependency in your pom.xml file." }, { "code": null, "e": 6544, "s": 6416, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-redis</artifactId>\n</dependency>" }, { "code": null, "e": 6620, "s": 6544, "text": "Gradle users should add the following dependency in your build.gradle file." }, { "code": null, "e": 6688, "s": 6620, "text": "compile('org.springframework.boot:spring-boot-starter-data-redis')\n" }, { "code": null, "e": 6813, "s": 6688, "text": "For Redis connection, we need to use RedisTemplate. For RedisTemplate we need to provide the JedisConnectionFactory details." }, { "code": null, "e": 7546, "s": 6813, "text": "@Bean\nJedisConnectionFactory jedisConnectionFactory() {\n JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();\n jedisConFactory.setHostName(\"localhost\");\n jedisConFactory.setPort(6000);\n jedisConFactory.setUsePool(true);\n return jedisConFactory;\n}\n@Bean\npublic RedisTemplate<String, Object> redisTemplate() {\n RedisTemplate<String, Object> template = new RedisTemplate<>();\n template.setConnectionFactory(jedisConnectionFactory());\n template.setKeySerializer(new StringRedisSerializer());\n template.setHashKeySerializer(new StringRedisSerializer());\n template.setHashValueSerializer(new StringRedisSerializer());\n template.setValueSerializer(new StringRedisSerializer());\n return template;\n}" }, { "code": null, "e": 7625, "s": 7546, "text": "Now auto wire the RedisTemplate class and access the data from Redis database." }, { "code": null, "e": 7756, "s": 7625, "text": "@Autowired\n\nRedisTemplate<String, Object> redis;\nMap<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”);" }, { "code": null, "e": 7928, "s": 7756, "text": "To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file." }, { "code": null, "e": 8077, "s": 7928, "text": "Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object." }, { "code": null, "e": 8189, "s": 8077, "text": "@Autowired\nJdbcTemplate jdbcTemplate;\nCollection<Map<String, Object>> rows = jdbc.queryForList(\"SELECT QUERY\");" }, { "code": null, "e": 8352, "s": 8189, "text": "The @Repository annotation should be added into the class file. The @Repository annotation is used to create database repository for your Spring Boot application." }, { "code": null, "e": 8399, "s": 8352, "text": "@Repository\npublic class ProductServiceDAO {\n}" }, { "code": null, "e": 8653, "s": 8399, "text": "We can keep ‘n’ number Datasources in a single Spring Boot application. The example given here shows how to create more than 1 data source in Spring Boot application. Now, add the two data source configuration details in the application properties file." }, { "code": null, "e": 8748, "s": 8653, "text": "For properties file users, add the following properties into your application.properties file." }, { "code": null, "e": 9944, "s": 8748, "text": "spring.dbProductService.driverClassName = com.mysql.jdbc.Driver\nspring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true\nspring.dbProductService.username = root\nspring.dbProductService.password = root\nspring.dbProductService.testOnBorrow = true\nspring.dbProductService.testWhileIdle = true\nspring.dbProductService.timeBetweenEvictionRunsMillis = 60000\nspring.dbProductService.minEvictableIdleTimeMillis = 30000\nspring.dbProductService.validationQuery = SELECT 1\nspring.dbProductService.max-active = 15\nspring.dbProductService.max-idle = 10\nspring.dbProductService.max-wait = 8000\n\nspring.dbUserService.driverClassName = com.mysql.jdbc.Driver\nspring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = true\nspring.dbUserService.username = root\nspring.dbUserService.password = root\nspring.dbUserService.testOnBorrow = true\nspring.dbUserService.testWhileIdle = true\nspring.dbUserService.timeBetweenEvictionRunsMillis = 60000\nspring.dbUserService.minEvictableIdleTimeMillis = 30000\nspring.dbUserService.validationQuery = SELECT 1\nspring.dbUserService.max-active = 15\nspring.dbUserService.max-idle = 10\nspring.dbUserService.max-wait = 8000" }, { "code": null, "e": 10021, "s": 9944, "text": "Yaml users should add the following properties in your application.yml file." }, { "code": null, "e": 10857, "s": 10021, "text": "spring:\n dbProductService: \n driverClassName: com.mysql.jdbc.Driver\n url: \"jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true\"\n password: \"root\"\n username: \"root\"\n testOnBorrow: true\n testWhileIdle: true\n timeBetweenEvictionRunsMillis: 60000\n minEvictableIdleTimeMillis: 30000\n validationQuery: SELECT 1\n max-active: 15\n max-idle: 10\n max-wait: 8000\n dbUserService: \n driverClassName: com.mysql.jdbc.Driver\n url: \"jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true\"\n password: \"root\"\n username: \"root\"\n testOnBorrow: true\n testWhileIdle: true\n timeBetweenEvictionRunsMillis: 60000\n minEvictableIdleTimeMillis: 30000\n validationQuery: SELECT 1 \n max-active: 15\n max-idle: 10\n max-wait: 8000" }, { "code": null, "e": 10958, "s": 10857, "text": "Now, create a Configuration class to create a DataSource and JdbcTemplate for multiple data sources." }, { "code": null, "e": 12385, "s": 10958, "text": "import javax.sql.DataSource;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.jdbc.core.JdbcTemplate;\n\n@Configuration\npublic class DatabaseConfig {\n @Bean(name = \"dbProductService\")\n @ConfigurationProperties(prefix = \"spring.dbProductService\")\n @Primary\n public DataSource createProductServiceDataSource() {\n return DataSourceBuilder.create().build();\n }\n @Bean(name = \"dbUserService\")\n @ConfigurationProperties(prefix = \"spring.dbUserService\")\n public DataSource createUserServiceDataSource() {\n return DataSourceBuilder.create().build();\n }\n @Bean(name = \"jdbcProductService\")\n @Autowired\n public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier(\"dbProductService\") DataSource productServiceDS) {\n return new JdbcTemplate(productServiceDS);\n }\n @Bean(name = \"jdbcUserService\")\n @Autowired\n public JdbcTemplate createJdbcTemplate_UserService(@Qualifier(\"dbUserService\") DataSource userServiceDS) {\n return new JdbcTemplate(userServiceDS);\n }\n}" }, { "code": null, "e": 12457, "s": 12385, "text": "Then, auto wire the JDBCTemplate object by using @Qualifier annotation." }, { "code": null, "e": 12597, "s": 12457, "text": "@Qualifier(\"jdbcProductService\")\n@Autowired\nJdbcTemplate jdbcTemplate;\n\n@Qualifier(\"jdbcUserService\")\n@Autowired\nJdbcTemplate jdbcTemplate;" }, { "code": null, "e": 12631, "s": 12597, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 12645, "s": 12631, "text": " Karthikeya T" }, { "code": null, "e": 12678, "s": 12645, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 12693, "s": 12678, "text": " Chaand Sheikh" }, { "code": null, "e": 12728, "s": 12693, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12740, "s": 12728, "text": " Senol Atac" }, { "code": null, "e": 12775, "s": 12740, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12787, "s": 12775, "text": " Senol Atac" }, { "code": null, "e": 12822, "s": 12787, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12834, "s": 12822, "text": " Senol Atac" }, { "code": null, "e": 12867, "s": 12834, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12879, "s": 12867, "text": " Senol Atac" }, { "code": null, "e": 12886, "s": 12879, "text": " Print" }, { "code": null, "e": 12897, "s": 12886, "text": " Add Notes" } ]
TypeScript - Array every()
every() method tests whether all the elements in an array passes the test implemented by the provided function. array.every(callback[, thisObject]); callback − Function to test for each element. callback − Function to test for each element. thisObject − Object to use as this when executing callback. thisObject − Object to use as this when executing callback. Returns true if every element in this array satisfies the provided testing function. function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44].every(isBigEnough); console.log("Test Value : " + passed ); On compiling, it will generate the same code in JavaScript. Its output is as follows − Test Value : false 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2160, "s": 2048, "text": "every() method tests whether all the elements in an array passes the test implemented by the provided function." }, { "code": null, "e": 2198, "s": 2160, "text": "array.every(callback[, thisObject]);\n" }, { "code": null, "e": 2244, "s": 2198, "text": "callback − Function to test for each element." }, { "code": null, "e": 2290, "s": 2244, "text": "callback − Function to test for each element." }, { "code": null, "e": 2350, "s": 2290, "text": "thisObject − Object to use as this when executing callback." }, { "code": null, "e": 2410, "s": 2350, "text": "thisObject − Object to use as this when executing callback." }, { "code": null, "e": 2495, "s": 2410, "text": "Returns true if every element in this array satisfies the provided testing function." }, { "code": null, "e": 2679, "s": 2495, "text": "function isBigEnough(element, index, array) { \n return (element >= 10); \n} \n \nvar passed = [12, 5, 8, 130, 44].every(isBigEnough); \nconsole.log(\"Test Value : \" + passed );\n" }, { "code": null, "e": 2739, "s": 2679, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2766, "s": 2739, "text": "Its output is as follows −" }, { "code": null, "e": 2786, "s": 2766, "text": "Test Value : false\n" }, { "code": null, "e": 2819, "s": 2786, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2833, "s": 2819, "text": " Antonio Papa" }, { "code": null, "e": 2866, "s": 2833, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2880, "s": 2866, "text": " Haider Malik" }, { "code": null, "e": 2915, "s": 2880, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2935, "s": 2915, "text": " Skillbakerystudios" }, { "code": null, "e": 2968, "s": 2935, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 2982, "s": 2968, "text": " Sean Bradley" }, { "code": null, "e": 3017, "s": 2982, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3033, "s": 3017, "text": " TELCOMA Global" }, { "code": null, "e": 3066, "s": 3033, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 3086, "s": 3066, "text": " Christopher Frewin" }, { "code": null, "e": 3093, "s": 3086, "text": " Print" }, { "code": null, "e": 3104, "s": 3093, "text": " Add Notes" } ]
Spring Boot Example Tutorials | Spring Boot Hello World Example Online TutorialsPoint
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 In this tutorial, I am going to show you the most popular and trending module in Spring Framework that is Spring Boot. By this tutorials you can get to know how to write a Simple Spring Boot Example. Used Technologies : Spring 3.2.3 Spring Boot 1.5.1 Java 8 Maven 3 Here I am going to implement a basic hello world spring boot example. Project Structure : Maven Dependencies : To make our example as simple as possible, I have placed dependencies in pom.xml what just I want. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples</groupId> <artifactId>Spring_Boot_Example</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <!-- Generic properties --> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- Spring --> <spring-framework.version>3.2.3.RELEASE</spring-framework.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Create Application Class : package com.onlinetutorialspoint.spring.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } @SpringBootApplication annotation tells the spring application context, it is an spring boot application. Most of the developers can used to define the spring boot main classes with the @Configuration, @EnableAutoConfiguration and @ComponentScan annotations. Since these annotations are mandatory to every Spring application, the Spring Boot given us an annotation called @SpringBootApplication instead. Here @Configuration + @EnableAutoConfiguration + @ComponentScan = @SpringBootApplication package com.onlinetutorialspoint.spring.boot; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/") public String index() { return "Hello World Spring !"; } } Running the Spring Boot Example : On e of the biggest advantage of Spring boot application is, to run we don’t deploy the application in any server. We can run the above spring boot example as a simple Java standalone application. Run the main method in Application.java. If every thing goes well, you can find the below text in your console. Run it : Happy Learning 🙂 spring_boot_example Simple Spring Boot Example File size: 9 KB Downloads: 1204 Spring Boot Environment Properties reading based on activeprofile Spring Boot FileUpload Ajax Example SSL Spring Boot HTTPs Enabling Example Spring Boot Validation Login Form Example External Apache ActiveMQ Spring Boot Example Spring Boot In Memory Basic Authentication Security Step By Step Spring Boot Docker Deployment Example Spring Boot Hibernate Integration Example Spring Boot JPA Integration Example Spring boot exception handling rest service (CRUD) operations Spring Boot MongoDB + Spring Data Example Spring Boot MVC Example Tutorials Spring Boot How to change the Tomcat to Jetty Server How to Send Mail Spring Boot Example How to set Spring boot favicon image Spring Boot Environment Properties reading based on activeprofile Spring Boot FileUpload Ajax Example SSL Spring Boot HTTPs Enabling Example Spring Boot Validation Login Form Example External Apache ActiveMQ Spring Boot Example Spring Boot In Memory Basic Authentication Security Step By Step Spring Boot Docker Deployment Example Spring Boot Hibernate Integration Example Spring Boot JPA Integration Example Spring boot exception handling rest service (CRUD) operations Spring Boot MongoDB + Spring Data Example Spring Boot MVC Example Tutorials Spring Boot How to change the Tomcat to Jetty Server How to Send Mail Spring Boot Example How to set Spring boot favicon image Spring Boot Training March 2, 2018 at 9:36 am - Reply Looking nice information about Spring Boot Plz do keep sharing on bhanu pratap July 24, 2018 at 2:57 pm - Reply Good Article,valuable information, Best software Training institute in Bangalore vinod kumar mvn August 31, 2018 at 2:45 pm - Reply The Article is very Informative and Worth Reading For the Candidates like me. Currently, I am learning spring boot training and this Article is helpful for me to understand the things very easily. Thanks Katherine December 27, 2018 at 10:50 am - Reply Hello ChandraSekhar, I really Appreciate your work, here you given a very informative post. As a beginner to SpingBoot technology, I found some new points, which is very much usefull for me. And thiss very much helpfull for every beginner. Spring Boot Training March 2, 2018 at 9:36 am - Reply Looking nice information about Spring Boot Plz do keep sharing on Looking nice information about Spring Boot Plz do keep sharing on bhanu pratap July 24, 2018 at 2:57 pm - Reply Good Article,valuable information, Best software Training institute in Bangalore Good Article,valuable information, Best software Training institute in Bangalore vinod kumar mvn August 31, 2018 at 2:45 pm - Reply The Article is very Informative and Worth Reading For the Candidates like me. Currently, I am learning spring boot training and this Article is helpful for me to understand the things very easily. Thanks The Article is very Informative and Worth Reading For the Candidates like me. Currently, I am learning spring boot training and this Article is helpful for me to understand the things very easily. Thanks Katherine December 27, 2018 at 10:50 am - Reply Hello ChandraSekhar, I really Appreciate your work, here you given a very informative post. As a beginner to SpingBoot technology, I found some new points, which is very much usefull for me. And thiss very much helpfull for every beginner. Hello ChandraSekhar, I really Appreciate your work, here you given a very informative post. As a beginner to SpingBoot technology, I found some new points, which is very much usefull for me. And thiss very much helpfull for every beginner. Δ 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": 598, "s": 398, "text": "In this tutorial, I am going to show you the most popular and trending module in Spring Framework that is Spring Boot. By this tutorials you can get to know how to write a Simple Spring Boot Example." }, { "code": null, "e": 618, "s": 598, "text": "Used Technologies :" }, { "code": null, "e": 631, "s": 618, "text": "Spring 3.2.3" }, { "code": null, "e": 649, "s": 631, "text": "Spring Boot 1.5.1" }, { "code": null, "e": 656, "s": 649, "text": "Java 8" }, { "code": null, "e": 664, "s": 656, "text": "Maven 3" }, { "code": null, "e": 734, "s": 664, "text": "Here I am going to implement a basic hello world spring boot example." }, { "code": null, "e": 754, "s": 734, "text": "Project Structure :" }, { "code": null, "e": 775, "s": 754, "text": "Maven Dependencies :" }, { "code": null, "e": 874, "s": 775, "text": "To make our example as simple as possible, I have placed dependencies in pom.xml what just I want." }, { "code": null, "e": 2020, "s": 874, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n<modelVersion>4.0.0</modelVersion>\n<groupId>org.springframework.samples</groupId>\n<artifactId>Spring_Boot_Example</artifactId>\n<version>0.0.1-SNAPSHOT</version>\n\n<properties>\n\n<!-- Generic properties -->\n<java.version>1.8</java.version>\n<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\n<!-- Spring -->\n<spring-framework.version>3.2.3.RELEASE</spring-framework.version>\n\n</properties>\n<parent>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-parent</artifactId>\n<version>1.5.1.RELEASE</version>\n</parent>\n\n<dependencies>\n<dependency>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n</dependencies>\n<build>\n<plugins>\n<plugin>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-maven-plugin</artifactId>\n</plugin>\n</plugins>\n</build>\n</project>\n" }, { "code": null, "e": 2047, "s": 2020, "text": "Create Application Class :" }, { "code": null, "e": 2379, "s": 2047, "text": "package com.onlinetutorialspoint.spring.boot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n } \n}\n" }, { "code": null, "e": 2783, "s": 2379, "text": "@SpringBootApplication annotation tells the spring application context, it is an spring boot application. Most of the developers can used to define the spring boot main classes with the @Configuration, @EnableAutoConfiguration and @ComponentScan annotations. Since these annotations are mandatory to every Spring application, the Spring Boot given us an annotation called @SpringBootApplication instead." }, { "code": null, "e": 2872, "s": 2783, "text": "Here @Configuration + @EnableAutoConfiguration + @ComponentScan = @SpringBootApplication" }, { "code": null, "e": 3194, "s": 2872, "text": "package com.onlinetutorialspoint.spring.boot;\n\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class HelloController {\n @RequestMapping(\"/\")\n public String index() {\n return \"Hello World Spring !\";\n }\n}\n" }, { "code": null, "e": 3228, "s": 3194, "text": "Running the Spring Boot Example :" }, { "code": null, "e": 3425, "s": 3228, "text": "On e of the biggest advantage of Spring boot application is, to run we don’t deploy the application in any server. We can run the above spring boot example as a simple Java standalone application." }, { "code": null, "e": 3466, "s": 3425, "text": "Run the main method in Application.java." }, { "code": null, "e": 3537, "s": 3466, "text": "If every thing goes well, you can find the below text in your console." }, { "code": null, "e": 3547, "s": 3537, "text": "\nRun it :" }, { "code": null, "e": 3564, "s": 3547, "text": "Happy Learning 🙂" }, { "code": null, "e": 3647, "s": 3564, "text": "\n\nspring_boot_example\n\nSimple Spring Boot Example\nFile size: 9 KB\nDownloads: 1204\n" }, { "code": null, "e": 4323, "s": 3647, "text": "\nSpring Boot Environment Properties reading based on activeprofile\nSpring Boot FileUpload Ajax Example\nSSL Spring Boot HTTPs Enabling Example\nSpring Boot Validation Login Form Example\nExternal Apache ActiveMQ Spring Boot Example\nSpring Boot In Memory Basic Authentication Security\nStep By Step Spring Boot Docker Deployment Example\nSpring Boot Hibernate Integration Example\nSpring Boot JPA Integration Example\nSpring boot exception handling rest service (CRUD) operations\nSpring Boot MongoDB + Spring Data Example\nSpring Boot MVC Example Tutorials\nSpring Boot How to change the Tomcat to Jetty Server\nHow to Send Mail Spring Boot Example\nHow to set Spring boot favicon image\n" }, { "code": null, "e": 4389, "s": 4323, "text": "Spring Boot Environment Properties reading based on activeprofile" }, { "code": null, "e": 4425, "s": 4389, "text": "Spring Boot FileUpload Ajax Example" }, { "code": null, "e": 4464, "s": 4425, "text": "SSL Spring Boot HTTPs Enabling Example" }, { "code": null, "e": 4506, "s": 4464, "text": "Spring Boot Validation Login Form Example" }, { "code": null, "e": 4551, "s": 4506, "text": "External Apache ActiveMQ Spring Boot Example" }, { "code": null, "e": 4603, "s": 4551, "text": "Spring Boot In Memory Basic Authentication Security" }, { "code": null, "e": 4654, "s": 4603, "text": "Step By Step Spring Boot Docker Deployment Example" }, { "code": null, "e": 4696, "s": 4654, "text": "Spring Boot Hibernate Integration Example" }, { "code": null, "e": 4732, "s": 4696, "text": "Spring Boot JPA Integration Example" }, { "code": null, "e": 4794, "s": 4732, "text": "Spring boot exception handling rest service (CRUD) operations" }, { "code": null, "e": 4836, "s": 4794, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 4870, "s": 4836, "text": "Spring Boot MVC Example Tutorials" }, { "code": null, "e": 4923, "s": 4870, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 4960, "s": 4923, "text": "How to Send Mail Spring Boot Example" }, { "code": null, "e": 4997, "s": 4960, "text": "How to set Spring boot favicon image" }, { "code": null, "e": 5834, "s": 4997, "text": "\n\n\n\n\n\nSpring Boot Training\nMarch 2, 2018 at 9:36 am - Reply \n\nLooking nice information about Spring Boot\nPlz do keep sharing on\n\n\n\n\n\n\n\n\n\nbhanu pratap\nJuly 24, 2018 at 2:57 pm - Reply \n\nGood Article,valuable information, Best software Training institute in Bangalore \n\n\n\n\n\n\n\n\n\nvinod kumar mvn\nAugust 31, 2018 at 2:45 pm - Reply \n\nThe Article is very Informative and Worth Reading For the Candidates like me. Currently, I am learning spring boot training and this Article is helpful for me to understand the things very easily.\nThanks\n\n\n\n\n\n\n\n\n\nKatherine\nDecember 27, 2018 at 10:50 am - Reply \n\nHello ChandraSekhar,\nI really Appreciate your work, here you given a very informative post. As a beginner to SpingBoot technology, I found some new points, which is very much usefull for me. And thiss very much helpfull for every beginner.\n\n\n\n\n" }, { "code": null, "e": 5965, "s": 5834, "text": "\n\n\n\n\nSpring Boot Training\nMarch 2, 2018 at 9:36 am - Reply \n\nLooking nice information about Spring Boot\nPlz do keep sharing on\n\n\n\n" }, { "code": null, "e": 6031, "s": 5965, "text": "Looking nice information about Spring Boot\nPlz do keep sharing on" }, { "code": null, "e": 6170, "s": 6031, "text": "\n\n\n\n\nbhanu pratap\nJuly 24, 2018 at 2:57 pm - Reply \n\nGood Article,valuable information, Best software Training institute in Bangalore \n\n\n\n" }, { "code": null, "e": 6252, "s": 6170, "text": "Good Article,valuable information, Best software Training institute in Bangalore " }, { "code": null, "e": 6518, "s": 6252, "text": "\n\n\n\n\nvinod kumar mvn\nAugust 31, 2018 at 2:45 pm - Reply \n\nThe Article is very Informative and Worth Reading For the Candidates like me. Currently, I am learning spring boot training and this Article is helpful for me to understand the things very easily.\nThanks\n\n\n\n" }, { "code": null, "e": 6715, "s": 6518, "text": "The Article is very Informative and Worth Reading For the Candidates like me. Currently, I am learning spring boot training and this Article is helpful for me to understand the things very easily." }, { "code": null, "e": 6722, "s": 6715, "text": "Thanks" }, { "code": null, "e": 7021, "s": 6722, "text": "\n\n\n\n\nKatherine\nDecember 27, 2018 at 10:50 am - Reply \n\nHello ChandraSekhar,\nI really Appreciate your work, here you given a very informative post. As a beginner to SpingBoot technology, I found some new points, which is very much usefull for me. And thiss very much helpfull for every beginner.\n\n\n\n" }, { "code": null, "e": 7261, "s": 7021, "text": "Hello ChandraSekhar,\nI really Appreciate your work, here you given a very informative post. As a beginner to SpingBoot technology, I found some new points, which is very much usefull for me. And thiss very much helpfull for every beginner." }, { "code": null, "e": 7267, "s": 7265, "text": "Δ" }, { "code": null, "e": 7294, "s": 7267, "text": " Spring Boot – Hello World" }, { "code": null, "e": 7321, "s": 7294, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 7355, "s": 7321, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 7396, "s": 7355, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 7441, "s": 7396, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 7479, "s": 7441, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 7513, "s": 7479, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 7544, "s": 7513, "text": " Spring Boot – Properties File" }, { "code": null, "e": 7578, "s": 7544, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 7611, "s": 7578, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 7644, "s": 7611, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 7684, "s": 7644, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 7709, "s": 7684, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 7740, "s": 7709, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 7764, "s": 7740, "text": " Spring Boot – Actuator" }, { "code": null, "e": 7810, "s": 7764, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 7833, "s": 7810, "text": " Spring Boot – Swagger" }, { "code": null, "e": 7860, "s": 7833, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 7906, "s": 7860, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 7946, "s": 7906, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 7975, "s": 7946, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 8009, "s": 7975, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 8039, "s": 8009, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 8075, "s": 8039, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 8108, "s": 8075, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 8141, "s": 8108, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 8185, "s": 8141, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 8219, "s": 8185, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 8251, "s": 8219, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 8279, "s": 8251, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 8310, "s": 8279, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 8351, "s": 8310, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 8385, "s": 8351, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 8410, "s": 8385, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 8444, "s": 8410, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 8480, "s": 8444, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 8526, "s": 8480, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 8577, "s": 8526, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 8619, "s": 8577, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 8650, "s": 8619, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 8673, "s": 8650, "text": " Spring Boot – EhCache" }, { "code": null, "e": 8703, "s": 8673, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 8733, "s": 8703, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 8782, "s": 8733, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 8816, "s": 8782, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 8849, "s": 8816, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 8878, "s": 8849, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 8910, "s": 8878, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 8947, "s": 8910, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 8976, "s": 8947, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 9005, "s": 8976, "text": " Spring Boot – MockMvc JUnit" } ]
Top Python Libraries Used In Data Science | by Tanu N Prabhu | Towards Data Science
Let us understand what are the most important and useful python libraries that can be used in data science. Data Science, as you all know, it is the process involved in studying the data. Yes, all you got to do is study the data and get new insights from the data. Here there is no need to focus on applying from scratch or learning new algorithms, all you need to know is learn how to approach the data and solve the problem. One of the key things that you need to know is using appropriate libraries to solve a data science problem. This article is all about providing the context to the important libraries used in Data Science. Before dwelling into the topic I would like to introduce the 5 primitive steps involved in solving a data science problem. Now I have sat down and designed these steps from scratch, so there is no right or wrong answer, the correct answer depends on how you approach the data. You can find more tutorials and code for data science, python on my GitHub Repository shown below: github.com Getting the data.Cleaning the dataExploring the dataBuilding the dataPresenting the data Getting the data. Cleaning the data Exploring the data Building the data Presenting the data Now, these steps are designed based on my experience, don’t fall into the assumption that this is the universal answer, but when you sit down and think about the problem, then these steps will make a lot more sense. This is one of the most important steps for solving a data science problem because you have to think of a problem and then eventually think of solving it. One of the best ways to get the data is scraping the data from the internet or download the data set from Kaggle. Now it depends on you how and where to get the data from. I found that Kaggle is one of the best ways to get the data from. Below is the link which leads you to the official website of Kaggle, I need you guys to spend some time in using Kaggle. www.kaggle.com Alternatively, you can scrape the data from the websites, to scrape the data you need specific ways and tools to do so. Below is my article where I have shown how to scrape the data from the websites. towardsdatascience.com Some of the most important libraries that are used to get or scrape the data from the internet are as shown below: Beautiful SoupRequestsPandas Beautiful Soup Requests Pandas Beautiful Soup: It is a python library that is used to extract or get the data from HTML or the XML files. Below is the official documentation of the Beautiful Soup library, I recommend you to go through the link. www.crummy.com To manually install Beautiful Soup just type the command below, here I have given you how to manually install all the libraries too, and make sure first you have python installed, but I recommend you guys to use Google Colab to type and practice your code, because in google colab you don’t need to install any libraries, you just have to just tell “import library_name” and the Colab will automatically import the library for you. pip install beautifulsoup4 To use Beautiful Soup, you need to import it as shown below: from bs4 import BeautifulSoupSoup = BeautifulSoup(page_name.text, ‘html.parser’) Requests: The Requests library in python is used to send HTTP requests in an easy and more friendly way. There are so many methods in request library one of the most commonly used methods is the request.get() which returns the status of the URL passed whether it is a success or failure. Below is the documentation of the requests library, I recommend you go through the documentation for more details. realpython.com To manually install request type the following command: pip install requests To import the requests library you need to use: import requestspaga_name = requests.get('url_name') Pandas: Pandas is a high performance, easy-to-use and convenient data structure and an analysis tool for python programming language. Pandas provide us a data frame to store the data in a clear and concise way. Below is the official documentation of the panda's library. pandas.pydata.org To manually install pandas just type the code: pip install pandas To import pandas library all you have to do is: import pandas as pd Cleaning the data involves removing the duplicate rows, removing the outliers, finding the missing or null values, converting the object values into null values, and plotting them using graphs, these are some steps that are necessarily performed during cleaning the data. To read more about the cleaning process go through my article is shown below: towardsdatascience.com Some main libraries that are involved in the data cleaning process are as shown below: PandasNumPy Pandas NumPy Pandas: Yes we use pandas library everywhere in data science, Again I don’t have to give insight about the panda's library, you can refer to the context in the above section. NumPy: NumPy is a python library also known as Numeric python which can perform scientific computing. You all must know that python never provides an array data structure, only with the help of a numpy library you can create and perform manipulations on an array. To read the official documentation of numpy library please go through the website down below: numpy.org Also to download the numpy, just run the following command on your command line (make sure you have python installed first): python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose To import numpy in python, all you have to do is just: import numpy as np Exploratory Data Analysis or (EDA) is understanding the informational indexes by abridging their fundamental attributes regularly plotting them outwardly. In other words, you are exploring the data in a deeper and concise (clear) way. Through the procedure of EDA, we can request to characterize the issue proclamation or definition of our informational collection which is significant. To read more about the EDA process go through please my article showed down below: towardsdatascience.com Some main libraries that are used while performing EDA are as shown below: PandasSeabornMatplotlib.pyplot Pandas Seaborn Matplotlib.pyplot Pandas: Like I said pandas library is very important we use this library throughout Data Science, for more details of the pandas library go through the first section above. Seaborn: Seaborn is a python data visualization library, which provides a high-level interface for drawing graphs with the statistical information. In order to install the latest version of seaborn use: pip install seaborn I recommend you go through the official documentation of seaborn, which is shown below: seaborn.pydata.org With the help of seaborn various plots such as bar plot, scatterplot, heat maps and many more can be plotted. To import seaborn all you have to do is: import seaborn as sns Matplotlib.pyplot: Matplotlib is a 2D plotting python library, with which we can plot various plots in python across various environments. It is an alternate to seaborn, and seaborn is based on matplotlib. To install matplotlib all you have to do is: python -m pip install -U matplotlib To read the official documentation of matplotlib go through the link down below: matplotlib.org To import the matplotlib.pyplot library use the following code: import matplotlib.pyplot as plt This is one of the most important steps in data science and this is step is significantly harder than the rest of the steps because in this step you will build a machine learning model based on your problem statement and your data. Now the problem statement is very important because it is where which leads you to define a problem and think about different solutions. Many of the dataset available on the internet is based on a problem so here your problem-solving skills are very important. Also, there is no one algorithm that fits the best for your solution, you gotta think whether your data falls under regression, classification, clustering or dimension reduction all there are different categories of algorithms. To know more about building a model please go through my article down below: medium.com Most of the time, it's a really confusing task to choose the best algorithm, so what I used the SciKit learn algorithms cheat sheet with the help of this you can trace down to see which algorithm fits the best. Below is the cheat sheet from Scikit learn. The important library that is used in building a model is obvious: SciKit learn SciKit learn SciKit learn: It is an easy-to-use Python library that is used to build a machine learning model. It is built on NumPy, SciPy, and matplotlib. Below is the official documentation for the scikit learn library. scikit-learn.org In order to import scikit learn, all you have to do is: import sklearn To manually install it, use the following command: pip install -U scikit-learn This is one of the last tasks that most of them don’t want to do. This is because no one wants to publicly speak about their finding on their data. There is a way of presenting the data. This is vital because at the end of the day you should have the skill to explain your findings to people, make this really small because people are not interested in your algorithms, they are only interested in what is the outcome. So in order to do a presentation of your findings, you need to install Jupyter notebook as shown below: jupyter.org And also install one more command which helps your notebook to enable a presentation option: pip install RISE More instructions on making your notebook into a completely amazing presentation can be found in the article down here. Make sure that you follow each and every line of the tutorial. Also, you can watch a YouTube video for how to do presentations on Jupyter notebooks: So now we have reached the end of the article, you now know how, when and where to use python libraries in data science. That’s pretty much it for this article, I have tried my level best to explain all the things from scratch. If you guys have any doubts then feel free to comment it down below. For more information about data science coding, tutorial please visit my GitHub repository. Thank you guys for reading my article, I hope you enjoyed it, if not let me know what needs to be improved, I’ll correct it. Anyways see you, have a good day.
[ { "code": null, "e": 279, "s": 171, "text": "Let us understand what are the most important and useful python libraries that can be used in data science." }, { "code": null, "e": 1179, "s": 279, "text": "Data Science, as you all know, it is the process involved in studying the data. Yes, all you got to do is study the data and get new insights from the data. Here there is no need to focus on applying from scratch or learning new algorithms, all you need to know is learn how to approach the data and solve the problem. One of the key things that you need to know is using appropriate libraries to solve a data science problem. This article is all about providing the context to the important libraries used in Data Science. Before dwelling into the topic I would like to introduce the 5 primitive steps involved in solving a data science problem. Now I have sat down and designed these steps from scratch, so there is no right or wrong answer, the correct answer depends on how you approach the data. You can find more tutorials and code for data science, python on my GitHub Repository shown below:" }, { "code": null, "e": 1190, "s": 1179, "text": "github.com" }, { "code": null, "e": 1279, "s": 1190, "text": "Getting the data.Cleaning the dataExploring the dataBuilding the dataPresenting the data" }, { "code": null, "e": 1297, "s": 1279, "text": "Getting the data." }, { "code": null, "e": 1315, "s": 1297, "text": "Cleaning the data" }, { "code": null, "e": 1334, "s": 1315, "text": "Exploring the data" }, { "code": null, "e": 1352, "s": 1334, "text": "Building the data" }, { "code": null, "e": 1372, "s": 1352, "text": "Presenting the data" }, { "code": null, "e": 1588, "s": 1372, "text": "Now, these steps are designed based on my experience, don’t fall into the assumption that this is the universal answer, but when you sit down and think about the problem, then these steps will make a lot more sense." }, { "code": null, "e": 2102, "s": 1588, "text": "This is one of the most important steps for solving a data science problem because you have to think of a problem and then eventually think of solving it. One of the best ways to get the data is scraping the data from the internet or download the data set from Kaggle. Now it depends on you how and where to get the data from. I found that Kaggle is one of the best ways to get the data from. Below is the link which leads you to the official website of Kaggle, I need you guys to spend some time in using Kaggle." }, { "code": null, "e": 2117, "s": 2102, "text": "www.kaggle.com" }, { "code": null, "e": 2318, "s": 2117, "text": "Alternatively, you can scrape the data from the websites, to scrape the data you need specific ways and tools to do so. Below is my article where I have shown how to scrape the data from the websites." }, { "code": null, "e": 2341, "s": 2318, "text": "towardsdatascience.com" }, { "code": null, "e": 2456, "s": 2341, "text": "Some of the most important libraries that are used to get or scrape the data from the internet are as shown below:" }, { "code": null, "e": 2485, "s": 2456, "text": "Beautiful SoupRequestsPandas" }, { "code": null, "e": 2500, "s": 2485, "text": "Beautiful Soup" }, { "code": null, "e": 2509, "s": 2500, "text": "Requests" }, { "code": null, "e": 2516, "s": 2509, "text": "Pandas" }, { "code": null, "e": 2730, "s": 2516, "text": "Beautiful Soup: It is a python library that is used to extract or get the data from HTML or the XML files. Below is the official documentation of the Beautiful Soup library, I recommend you to go through the link." }, { "code": null, "e": 2745, "s": 2730, "text": "www.crummy.com" }, { "code": null, "e": 3177, "s": 2745, "text": "To manually install Beautiful Soup just type the command below, here I have given you how to manually install all the libraries too, and make sure first you have python installed, but I recommend you guys to use Google Colab to type and practice your code, because in google colab you don’t need to install any libraries, you just have to just tell “import library_name” and the Colab will automatically import the library for you." }, { "code": null, "e": 3204, "s": 3177, "text": "pip install beautifulsoup4" }, { "code": null, "e": 3265, "s": 3204, "text": "To use Beautiful Soup, you need to import it as shown below:" }, { "code": null, "e": 3347, "s": 3265, "text": "from bs4 import BeautifulSoupSoup = BeautifulSoup(page_name.text, ‘html.parser’) " }, { "code": null, "e": 3750, "s": 3347, "text": "Requests: The Requests library in python is used to send HTTP requests in an easy and more friendly way. There are so many methods in request library one of the most commonly used methods is the request.get() which returns the status of the URL passed whether it is a success or failure. Below is the documentation of the requests library, I recommend you go through the documentation for more details." }, { "code": null, "e": 3765, "s": 3750, "text": "realpython.com" }, { "code": null, "e": 3821, "s": 3765, "text": "To manually install request type the following command:" }, { "code": null, "e": 3842, "s": 3821, "text": "pip install requests" }, { "code": null, "e": 3890, "s": 3842, "text": "To import the requests library you need to use:" }, { "code": null, "e": 3942, "s": 3890, "text": "import requestspaga_name = requests.get('url_name')" }, { "code": null, "e": 4213, "s": 3942, "text": "Pandas: Pandas is a high performance, easy-to-use and convenient data structure and an analysis tool for python programming language. Pandas provide us a data frame to store the data in a clear and concise way. Below is the official documentation of the panda's library." }, { "code": null, "e": 4231, "s": 4213, "text": "pandas.pydata.org" }, { "code": null, "e": 4278, "s": 4231, "text": "To manually install pandas just type the code:" }, { "code": null, "e": 4298, "s": 4278, "text": "pip install pandas " }, { "code": null, "e": 4346, "s": 4298, "text": "To import pandas library all you have to do is:" }, { "code": null, "e": 4366, "s": 4346, "text": "import pandas as pd" }, { "code": null, "e": 4716, "s": 4366, "text": "Cleaning the data involves removing the duplicate rows, removing the outliers, finding the missing or null values, converting the object values into null values, and plotting them using graphs, these are some steps that are necessarily performed during cleaning the data. To read more about the cleaning process go through my article is shown below:" }, { "code": null, "e": 4739, "s": 4716, "text": "towardsdatascience.com" }, { "code": null, "e": 4826, "s": 4739, "text": "Some main libraries that are involved in the data cleaning process are as shown below:" }, { "code": null, "e": 4838, "s": 4826, "text": "PandasNumPy" }, { "code": null, "e": 4845, "s": 4838, "text": "Pandas" }, { "code": null, "e": 4851, "s": 4845, "text": "NumPy" }, { "code": null, "e": 5026, "s": 4851, "text": "Pandas: Yes we use pandas library everywhere in data science, Again I don’t have to give insight about the panda's library, you can refer to the context in the above section." }, { "code": null, "e": 5384, "s": 5026, "text": "NumPy: NumPy is a python library also known as Numeric python which can perform scientific computing. You all must know that python never provides an array data structure, only with the help of a numpy library you can create and perform manipulations on an array. To read the official documentation of numpy library please go through the website down below:" }, { "code": null, "e": 5394, "s": 5384, "text": "numpy.org" }, { "code": null, "e": 5519, "s": 5394, "text": "Also to download the numpy, just run the following command on your command line (make sure you have python installed first):" }, { "code": null, "e": 5605, "s": 5519, "text": "python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose" }, { "code": null, "e": 5660, "s": 5605, "text": "To import numpy in python, all you have to do is just:" }, { "code": null, "e": 5679, "s": 5660, "text": "import numpy as np" }, { "code": null, "e": 6149, "s": 5679, "text": "Exploratory Data Analysis or (EDA) is understanding the informational indexes by abridging their fundamental attributes regularly plotting them outwardly. In other words, you are exploring the data in a deeper and concise (clear) way. Through the procedure of EDA, we can request to characterize the issue proclamation or definition of our informational collection which is significant. To read more about the EDA process go through please my article showed down below:" }, { "code": null, "e": 6172, "s": 6149, "text": "towardsdatascience.com" }, { "code": null, "e": 6247, "s": 6172, "text": "Some main libraries that are used while performing EDA are as shown below:" }, { "code": null, "e": 6278, "s": 6247, "text": "PandasSeabornMatplotlib.pyplot" }, { "code": null, "e": 6285, "s": 6278, "text": "Pandas" }, { "code": null, "e": 6293, "s": 6285, "text": "Seaborn" }, { "code": null, "e": 6311, "s": 6293, "text": "Matplotlib.pyplot" }, { "code": null, "e": 6484, "s": 6311, "text": "Pandas: Like I said pandas library is very important we use this library throughout Data Science, for more details of the pandas library go through the first section above." }, { "code": null, "e": 6687, "s": 6484, "text": "Seaborn: Seaborn is a python data visualization library, which provides a high-level interface for drawing graphs with the statistical information. In order to install the latest version of seaborn use:" }, { "code": null, "e": 6707, "s": 6687, "text": "pip install seaborn" }, { "code": null, "e": 6795, "s": 6707, "text": "I recommend you go through the official documentation of seaborn, which is shown below:" }, { "code": null, "e": 6814, "s": 6795, "text": "seaborn.pydata.org" }, { "code": null, "e": 6965, "s": 6814, "text": "With the help of seaborn various plots such as bar plot, scatterplot, heat maps and many more can be plotted. To import seaborn all you have to do is:" }, { "code": null, "e": 6987, "s": 6965, "text": "import seaborn as sns" }, { "code": null, "e": 7238, "s": 6987, "text": "Matplotlib.pyplot: Matplotlib is a 2D plotting python library, with which we can plot various plots in python across various environments. It is an alternate to seaborn, and seaborn is based on matplotlib. To install matplotlib all you have to do is:" }, { "code": null, "e": 7274, "s": 7238, "text": "python -m pip install -U matplotlib" }, { "code": null, "e": 7355, "s": 7274, "text": "To read the official documentation of matplotlib go through the link down below:" }, { "code": null, "e": 7370, "s": 7355, "text": "matplotlib.org" }, { "code": null, "e": 7434, "s": 7370, "text": "To import the matplotlib.pyplot library use the following code:" }, { "code": null, "e": 7466, "s": 7434, "text": "import matplotlib.pyplot as plt" }, { "code": null, "e": 8264, "s": 7466, "text": "This is one of the most important steps in data science and this is step is significantly harder than the rest of the steps because in this step you will build a machine learning model based on your problem statement and your data. Now the problem statement is very important because it is where which leads you to define a problem and think about different solutions. Many of the dataset available on the internet is based on a problem so here your problem-solving skills are very important. Also, there is no one algorithm that fits the best for your solution, you gotta think whether your data falls under regression, classification, clustering or dimension reduction all there are different categories of algorithms. To know more about building a model please go through my article down below:" }, { "code": null, "e": 8275, "s": 8264, "text": "medium.com" }, { "code": null, "e": 8530, "s": 8275, "text": "Most of the time, it's a really confusing task to choose the best algorithm, so what I used the SciKit learn algorithms cheat sheet with the help of this you can trace down to see which algorithm fits the best. Below is the cheat sheet from Scikit learn." }, { "code": null, "e": 8597, "s": 8530, "text": "The important library that is used in building a model is obvious:" }, { "code": null, "e": 8610, "s": 8597, "text": "SciKit learn" }, { "code": null, "e": 8623, "s": 8610, "text": "SciKit learn" }, { "code": null, "e": 8832, "s": 8623, "text": "SciKit learn: It is an easy-to-use Python library that is used to build a machine learning model. It is built on NumPy, SciPy, and matplotlib. Below is the official documentation for the scikit learn library." }, { "code": null, "e": 8849, "s": 8832, "text": "scikit-learn.org" }, { "code": null, "e": 8905, "s": 8849, "text": "In order to import scikit learn, all you have to do is:" }, { "code": null, "e": 8920, "s": 8905, "text": "import sklearn" }, { "code": null, "e": 8971, "s": 8920, "text": "To manually install it, use the following command:" }, { "code": null, "e": 8999, "s": 8971, "text": "pip install -U scikit-learn" }, { "code": null, "e": 9522, "s": 8999, "text": "This is one of the last tasks that most of them don’t want to do. This is because no one wants to publicly speak about their finding on their data. There is a way of presenting the data. This is vital because at the end of the day you should have the skill to explain your findings to people, make this really small because people are not interested in your algorithms, they are only interested in what is the outcome. So in order to do a presentation of your findings, you need to install Jupyter notebook as shown below:" }, { "code": null, "e": 9534, "s": 9522, "text": "jupyter.org" }, { "code": null, "e": 9627, "s": 9534, "text": "And also install one more command which helps your notebook to enable a presentation option:" }, { "code": null, "e": 9644, "s": 9627, "text": "pip install RISE" }, { "code": null, "e": 9913, "s": 9644, "text": "More instructions on making your notebook into a completely amazing presentation can be found in the article down here. Make sure that you follow each and every line of the tutorial. Also, you can watch a YouTube video for how to do presentations on Jupyter notebooks:" } ]
Maximum prefix sum for a given range | Practice | GeeksforGeeks
Given an array of N integers and Q queries, each query having a range from index L to R. Find the maximum prefix-sum for the range L to R. Note: Assume 0 based indexing. Example 1: Input: a[ ] = {-1, 2, 3, -5} Q = 2 L1 = 0, R1 = 3 L2 = 1, R2 = 3 Output: 4 5 Explanation: The range (0, 3) in the 1st query is {-1, 2, 3, -5}, hence, the max prefix-sum will be -1 + 2 + 3 = 4. The range (1, 3) in the 2nd query is {2, 3, -5}, hence, the max prefix-sum will be 2 + 3 = 5. Your Task: You don't need to read input or print anything. Your task is to complete the function maxPrefixes() which takes the array A[], its size N, array L[] and R[] and their size Q as input parameters and returns a vector storing the required answer for every query. Expected Time Complexity: O(N*Q) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N, A[i] ≤ 104 1 ≤ Q ≤ 104 0 ≤ L[i] ≤ R[i] < N 0 gaurav119087902 weeks ago for 0 to 3 range why it isn't 5 ? 0 harshrajvanshi16 months ago people using python do have feelings bruh.....please dont hurt us with ur faulty drivers every time :'( +1 shaanrattan127 months ago vector<int> maxPrefixes(int a[], int L[], int R[], int n, int Q) { vector<int> res; //prefix array int pfx[n], ind = 0; pfx[0]=a[0]; for(int i=1;i<n;i++) pfx[i] = pfx[i-1]+a[i]; while(Q--){ int l = L[ind], r = R[ind], maximum = pfx[l]; ind++; for(int i=l+1;i<=r;i++) maximum = max(maximum, pfx[i]); if(l==0) res.push_back(maximum); else res.push_back(maximum-pfx[l-1]); } return res; } 0 prakash kumar singh9 months ago prakash kumar singh can anyone help me with this code? what's the error here? vector<int> maxPrefixes(int a[], int L[], int R[], int n, int Q) { int prefixSum[n]; prefixSum[0]=a[0]; vector<int> vec; for(int i=1;i<n;i++){ prefixsum[i]="prefixSum[i-1]+a[i];" }="" for(int="" i="0;i&lt;Q;i++){" if(l[i]!="0){" vec.push_back(prefixsum[r[i]]-prefixsum[l[i]-1])="" }="" else{="" vec.push_back(prefixsum[r[i]]);="" }="" }="" return="" vec;=""> 0 aditya anand1 year ago aditya anand Why python has more driver faults, C'mon python folkes.please fix this errorprint(Solution().*maxPrefixes(a, l, r, n, q)) 0 sachin chandela1 year ago sachin chandela Simple Java Solution ;https://uploads.disquscdn.c... 0 Shubhankit Bansal2 years ago Shubhankit Bansal https://ide.geeksforgeeks.o... This code work properly with execution time: 0.15 0 G Vishal2 years ago G Vishal java using segment tree https://ide.geeksforgeeks.o... https://uploads.disquscdn.c... https://uploads.disquscdn.c... 0 G Vishal2 years ago G Vishal @GeeksForGeeks what is wrong with you i wrote entire python code to get tle whyhttps://ide.geeksforgeeks.o... https://uploads.disquscdn.c... 0 Bicky2 years ago Bicky simple cpp soln 0.1s 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": 408, "s": 238, "text": "Given an array of N integers and Q queries, each query having a range from index L to R. Find the maximum prefix-sum for the range L to R.\nNote: Assume 0 based indexing." }, { "code": null, "e": 419, "s": 408, "text": "Example 1:" }, { "code": null, "e": 711, "s": 419, "text": "Input: \na[ ] = {-1, 2, 3, -5} \nQ = 2\nL1 = 0, R1 = 3\nL2 = 1, R2 = 3\nOutput:\n4 5\nExplanation:\nThe range (0, 3) in the 1st query is {-1, 2, 3, -5}, hence, \nthe max prefix-sum will be -1 + 2 + 3 = 4. The range (1, 3) \nin the 2nd query is {2, 3, -5}, hence, the max prefix-sum \nwill be 2 + 3 = 5." }, { "code": null, "e": 984, "s": 711, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function maxPrefixes() which takes the array A[], its size N, array L[] and R[] and their size Q as input parameters and returns a vector storing the required answer for every query." }, { "code": null, "e": 1048, "s": 984, "text": "Expected Time Complexity: O(N*Q)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1112, "s": 1048, "text": "Constraints: \n1 ≤ N, A[i] ≤ 104\n1 ≤ Q ≤ 104\n0 ≤ L[i] ≤ R[i] < N" }, { "code": null, "e": 1114, "s": 1112, "text": "0" }, { "code": null, "e": 1140, "s": 1114, "text": "gaurav119087902 weeks ago" }, { "code": null, "e": 1174, "s": 1140, "text": "for 0 to 3 range why it isn't 5 ?" }, { "code": null, "e": 1178, "s": 1176, "text": "0" }, { "code": null, "e": 1206, "s": 1178, "text": "harshrajvanshi16 months ago" }, { "code": null, "e": 1311, "s": 1206, "text": "people using python do have feelings bruh.....please dont hurt us with ur faulty drivers every time :'( " }, { "code": null, "e": 1314, "s": 1311, "text": "+1" }, { "code": null, "e": 1340, "s": 1314, "text": "shaanrattan127 months ago" }, { "code": null, "e": 1864, "s": 1340, "text": "vector<int> maxPrefixes(int a[], int L[], int R[], int n, int Q) {\n vector<int> res;\n //prefix array\n int pfx[n], ind = 0;\n pfx[0]=a[0];\n for(int i=1;i<n;i++) pfx[i] = pfx[i-1]+a[i]; \n \n while(Q--){\n int l = L[ind], r = R[ind], maximum = pfx[l];\n ind++;\n for(int i=l+1;i<=r;i++) maximum = max(maximum, pfx[i]);\n if(l==0) res.push_back(maximum);\n else res.push_back(maximum-pfx[l-1]);\n }\n return res;\n }" }, { "code": null, "e": 1866, "s": 1864, "text": "0" }, { "code": null, "e": 1898, "s": 1866, "text": "prakash kumar singh9 months ago" }, { "code": null, "e": 1918, "s": 1898, "text": "prakash kumar singh" }, { "code": null, "e": 1976, "s": 1918, "text": "can anyone help me with this code? what's the error here?" }, { "code": null, "e": 2363, "s": 1976, "text": "vector<int> maxPrefixes(int a[], int L[], int R[], int n, int Q) { int prefixSum[n]; prefixSum[0]=a[0]; vector<int> vec; for(int i=1;i<n;i++){ prefixsum[i]=\"prefixSum[i-1]+a[i];\" }=\"\" for(int=\"\" i=\"0;i&lt;Q;i++){\" if(l[i]!=\"0){\" vec.push_back(prefixsum[r[i]]-prefixsum[l[i]-1])=\"\" }=\"\" else{=\"\" vec.push_back(prefixsum[r[i]]);=\"\" }=\"\" }=\"\" return=\"\" vec;=\"\">" }, { "code": null, "e": 2365, "s": 2363, "text": "0" }, { "code": null, "e": 2388, "s": 2365, "text": "aditya anand1 year ago" }, { "code": null, "e": 2401, "s": 2388, "text": "aditya anand" }, { "code": null, "e": 2523, "s": 2401, "text": "Why python has more driver faults, C'mon python folkes.please fix this errorprint(Solution().*maxPrefixes(a, l, r, n, q))" }, { "code": null, "e": 2525, "s": 2523, "text": "0" }, { "code": null, "e": 2551, "s": 2525, "text": "sachin chandela1 year ago" }, { "code": null, "e": 2567, "s": 2551, "text": "sachin chandela" }, { "code": null, "e": 2620, "s": 2567, "text": "Simple Java Solution ;https://uploads.disquscdn.c..." }, { "code": null, "e": 2622, "s": 2620, "text": "0" }, { "code": null, "e": 2651, "s": 2622, "text": "Shubhankit Bansal2 years ago" }, { "code": null, "e": 2669, "s": 2651, "text": "Shubhankit Bansal" }, { "code": null, "e": 2700, "s": 2669, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 2750, "s": 2700, "text": "This code work properly with execution time: 0.15" }, { "code": null, "e": 2752, "s": 2750, "text": "0" }, { "code": null, "e": 2772, "s": 2752, "text": "G Vishal2 years ago" }, { "code": null, "e": 2781, "s": 2772, "text": "G Vishal" }, { "code": null, "e": 2898, "s": 2781, "text": "java using segment tree https://ide.geeksforgeeks.o... https://uploads.disquscdn.c... https://uploads.disquscdn.c..." }, { "code": null, "e": 2900, "s": 2898, "text": "0" }, { "code": null, "e": 2920, "s": 2900, "text": "G Vishal2 years ago" }, { "code": null, "e": 2929, "s": 2920, "text": "G Vishal" }, { "code": null, "e": 3070, "s": 2929, "text": "@GeeksForGeeks what is wrong with you i wrote entire python code to get tle whyhttps://ide.geeksforgeeks.o... https://uploads.disquscdn.c..." }, { "code": null, "e": 3072, "s": 3070, "text": "0" }, { "code": null, "e": 3089, "s": 3072, "text": "Bicky2 years ago" }, { "code": null, "e": 3095, "s": 3089, "text": "Bicky" }, { "code": null, "e": 3116, "s": 3095, "text": "simple cpp soln 0.1s" }, { "code": null, "e": 3147, "s": 3116, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3293, "s": 3147, "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": 3329, "s": 3293, "text": " Login to access your submissions. " }, { "code": null, "e": 3339, "s": 3329, "text": "\nProblem\n" }, { "code": null, "e": 3349, "s": 3339, "text": "\nContest\n" }, { "code": null, "e": 3412, "s": 3349, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3560, "s": 3412, "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": 3768, "s": 3560, "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": 3874, "s": 3768, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Django model data to JSON data in 2 lines
In this article, we are going to learn a handy trick to convert Django model data directly to JSON data. Sometimes, we need to return model data in JSON format; it can also be used in making API or just showing simple data to our frontend in JSON format. JSON is easy to access so it is really handful. Create a Django project and an app. In settings.py, add the app name in INSTALLED_APPS. In urls.py of the Project main directory, add the following lines − from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('modeltojson.urls')) ] Here we added our app's urls.py. In the App's urls.py, add the following lines − from django.urls import path from . import views urlpatterns = [ path('',views.home,name="home") ] Here we rendered our home view, which is simple. In models.py, add the following lines − from django.db import models # Create your models here. class EmployeeData(models.Model): name=models.CharField(max_length=100) Salary=models.CharField(max_length=100) department=models.CharField(max_length=100) Here, we created our model and add some dummy data for testing and trying. In admin.py, add the following lines − from django.contrib import admin from .models import EmployeeData # Register your models here. admin.site.register(EmployeeData) Here, we simply registered our EmployeeData model in admin page. In views.py, add the following lines from django.http import JsonResponse from .models import EmployeeData # Create your views here. def home(request): data=list(EmployeeData.objects.values()) return JsonResponse(data,safe=False) Here, we created a list of all key-values using .value() function of our model data and then we rendered it as a JSON response. Now it is all done, don't forget to add some random data. [ { "id": 1, "name": "Ross Taylor", "Salary": "1 lakh", "department": "Technical" }, { "id": 2, "name": "Rohit Sharma", "Salary": "2 lakh", "department": "Sales" }, { "id": 3, "name": "Steve Smith", "Salary": "3 lakh", "department": "Sales" } ]
[ { "code": null, "e": 1365, "s": 1062, "text": "In this article, we are going to learn a handy trick to convert Django model data directly to JSON data. Sometimes, we need to return model data in JSON format; it can also be used in making API or just showing simple data to our frontend in JSON format. JSON is easy to access so it is really handful." }, { "code": null, "e": 1401, "s": 1365, "text": "Create a Django project and an app." }, { "code": null, "e": 1453, "s": 1401, "text": "In settings.py, add the app name in INSTALLED_APPS." }, { "code": null, "e": 1521, "s": 1453, "text": "In urls.py of the Project main directory, add the following lines −" }, { "code": null, "e": 1686, "s": 1521, "text": "from django.contrib import admin\nfrom django.urls import path,include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',include('modeltojson.urls'))\n]" }, { "code": null, "e": 1719, "s": 1686, "text": "Here we added our app's urls.py." }, { "code": null, "e": 1767, "s": 1719, "text": "In the App's urls.py, add the following lines −" }, { "code": null, "e": 1869, "s": 1767, "text": "from django.urls import path\nfrom . import views\nurlpatterns = [\n path('',views.home,name=\"home\")\n]" }, { "code": null, "e": 1918, "s": 1869, "text": "Here we rendered our home view, which is simple." }, { "code": null, "e": 1958, "s": 1918, "text": "In models.py, add the following lines −" }, { "code": null, "e": 2180, "s": 1958, "text": "from django.db import models\n\n# Create your models here.\nclass EmployeeData(models.Model):\n name=models.CharField(max_length=100)\n Salary=models.CharField(max_length=100)\n department=models.CharField(max_length=100)" }, { "code": null, "e": 2255, "s": 2180, "text": "Here, we created our model and add some dummy data for testing and trying." }, { "code": null, "e": 2294, "s": 2255, "text": "In admin.py, add the following lines −" }, { "code": null, "e": 2424, "s": 2294, "text": "from django.contrib import admin\nfrom .models import EmployeeData\n\n# Register your models here.\nadmin.site.register(EmployeeData)" }, { "code": null, "e": 2489, "s": 2424, "text": "Here, we simply registered our EmployeeData model in admin page." }, { "code": null, "e": 2526, "s": 2489, "text": "In views.py, add the following lines" }, { "code": null, "e": 2725, "s": 2526, "text": "from django.http import JsonResponse\nfrom .models import EmployeeData\n# Create your views here.\ndef home(request):\n data=list(EmployeeData.objects.values())\n return JsonResponse(data,safe=False)" }, { "code": null, "e": 2853, "s": 2725, "text": "Here, we created a list of all key-values using .value() function of our model data and then we rendered it as a JSON response." }, { "code": null, "e": 2911, "s": 2853, "text": "Now it is all done, don't forget to add some random data." }, { "code": null, "e": 3246, "s": 2911, "text": "[\n {\n \"id\": 1,\n \"name\": \"Ross Taylor\",\n \"Salary\": \"1 lakh\",\n \"department\": \"Technical\"\n },\n {\n \"id\": 2,\n \"name\": \"Rohit Sharma\",\n \"Salary\": \"2 lakh\",\n \"department\": \"Sales\"\n },\n {\n \"id\": 3,\n \"name\": \"Steve Smith\",\n \"Salary\": \"3 lakh\",\n \"department\": \"Sales\"\n }\n]" } ]
XSLT <template>
<xsl:template> defines a way to reuse templates in order to generate the desired output for nodes of a particular type/context. Following is the syntax declaration of <xsl:template> element. <xsl:template name = Qname match = Pattern priority = number mode = QName > </xsl:template> name Name of the element on which template is to be applied. match Pattern which signifies the element(s) on which template is to be applied. priority Priority number of a template. Matching template with low priority is not considered in from in front of high priority template. mode Allows element to be processed multiple times to produce a different result each time. Parent elements xsl:stylesheet, xsl:transform Child elements xsl:apply-imports,xsl:apply-templates,xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:param, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements This template rule has a pattern that identifies <student> elements and produces an output in a tabular format. students.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> students_imports.xsl <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "class/student"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> Print Add Notes Bookmark this page
[ { "code": null, "e": 1887, "s": 1759, "text": "<xsl:template> defines a way to reuse templates in order to generate the desired output for nodes of a particular type/context." }, { "code": null, "e": 1950, "s": 1887, "text": "Following is the syntax declaration of <xsl:template> element." }, { "code": null, "e": 2059, "s": 1950, "text": "<xsl:template \n name = Qname \n match = Pattern \n priority = number \n mode = QName >\n</xsl:template>\n" }, { "code": null, "e": 2064, "s": 2059, "text": "name" }, { "code": null, "e": 2120, "s": 2064, "text": "Name of the element on which template is to be applied." }, { "code": null, "e": 2126, "s": 2120, "text": "match" }, { "code": null, "e": 2201, "s": 2126, "text": "Pattern which signifies the element(s) on which template is to be applied." }, { "code": null, "e": 2210, "s": 2201, "text": "priority" }, { "code": null, "e": 2339, "s": 2210, "text": "Priority number of a template. Matching template with low priority is not considered in from in front of high priority template." }, { "code": null, "e": 2344, "s": 2339, "text": "mode" }, { "code": null, "e": 2431, "s": 2344, "text": "Allows element to be processed multiple times to produce a different result each time." }, { "code": null, "e": 2447, "s": 2431, "text": "Parent elements" }, { "code": null, "e": 2477, "s": 2447, "text": "xsl:stylesheet, xsl:transform" }, { "code": null, "e": 2492, "s": 2477, "text": "Child elements" }, { "code": null, "e": 2779, "s": 2492, "text": "xsl:apply-imports,xsl:apply-templates,xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:param, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements" }, { "code": null, "e": 2891, "s": 2779, "text": "This template rule has a pattern that identifies <student> elements and produces an output in a tabular format." }, { "code": null, "e": 2904, "s": 2891, "text": "students.xml" }, { "code": null, "e": 3527, "s": 2904, "text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>" }, { "code": null, "e": 3548, "s": 3527, "text": "students_imports.xsl" }, { "code": null, "e": 4626, "s": 3548, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<xsl:stylesheet version = \"1.0\" \n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n\t\n <xsl:template match = \"/\"> \n <html> \n <body> \n <h2>Students</h2> \n <table border = \"1\"> \n <tr bgcolor = \"#9acd32\"> \n <th>Roll No</th> \n <th>First Name</th> \n <th>Last Name</th> \n <th>Nick Name</th> \n <th>Marks</th> \n </tr>\n\t\t\t\t\t\n <xsl:for-each select = \"class/student\"> \n <tr> \n <td><xsl:value-of select = \"@rollno\"/></td> \n <td><xsl:value-of select = \"firstname\"/></td> \n <td><xsl:value-of select = \"lastname\"/></td> \n <td><xsl:value-of select = \"nickname\"/></td> \n <td><xsl:value-of select = \"marks\"/></td>\n </tr> \n </xsl:for-each> \n </table> \n </body> \n </html> \n </xsl:template> \n</xsl:stylesheet>" }, { "code": null, "e": 4633, "s": 4626, "text": " Print" }, { "code": null, "e": 4644, "s": 4633, "text": " Add Notes" } ]
CSS3 - Colors
CSS3 has Supported additional color properties as follows − RGBA colors HSL colors HSLA colors Opacity RGBA stands for Red Green Blue Alpha.It is an extension of CSS2,Alpha specifies the opacity of a color and parameter number is a numerical between 0.0 to 1.0. A Sample syntax of RGBA as shown below − #d1 {background-color: rgba(255, 0, 0, 0.5);} #d2 {background-color: rgba(0, 255, 0, 0.5);} #d3 {background-color: rgba(0, 0, 255, 0.5);} HSL stands for hue, saturation, lightness.Here Huge is a degree on the color wheel, saturation and lightness are percentage values between 0 to 100%. A Sample syntax of HSL as shown below − #g1 {background-color: hsl(120, 100%, 50%);} #g2 {background-color: hsl(120, 100%, 75%);} #g3 {background-color: hsl(120, 100%, 25%);} HSLA stands for hue, saturation, lightness and alpha. Alpha value specifies the opacity as shown RGBA. A Sample syntax of HSLA as shown below − #g1 {background-color: hsla(120, 100%, 50%, 0.3);} #g2 {background-color: hsla(120, 100%, 75%, 0.3);} #g3 {background-color: hsla(120, 100%, 25%, 0.3);} opacity is a thinner paints need black added to increase opacity. A sample syntax of opacity is as shown below − #g1 {background-color:rgb(255,0,0);opacity:0.6;} #g2 {background-color:rgb(0,255,0);opacity:0.6;} #g3 {background-color:rgb(0,0,255);opacity:0.6;} The following example shows rgba color property. <html> <head> <style> #p1 {background-color:rgba(255,0,0,0.3);} #p2 {background-color:rgba(0,255,0,0.3);} #p3 {background-color:rgba(0,0,255,0.3);} </style> </head> <body> <p>RGBA colors:</p> <p id = "p1">Red</p> <p id = "p2">Green</p> <p id = "p3">Blue</p> </body> </html> It will produce the following result − RGBA colors: Red Green Blue The following example shows HSL color property. <html> <head> <style> #g1 {background-color:hsl(120, 100%, 50%);} #g2 {background-color:hsl(120,100%,75%);} #g3 {background-color:hsl(120,100%,25%);} </style> </head> <body> <p>HSL colors:</p> <p id = "g1">Green</p> <p id = "g2">Normal Green</p> <p id = "g3">Dark Green</p> </body> </html> It will produce the following result − HSL colors: Green Normal Green Dark Green The following example shows HSLA color property. <html> <head> <style> #d1 {background-color:hsla(120,100%,50%,0.3);} #d2 {background-color:hsla(120,100%,75%,0.3);} #d3 {background-color:hsla(120,100%,25%,0.3);} </style> </head> <body> <p>HSLA colors:</p> <p id = "d1">Less opacity green</p> <p id = "d2">Green</p> <p id = "d3">Green</p> </body> </html> It will produce the following result − HSLA colors: Less opacity green Green Green The following example shows Opacity property. <html> <head> <style> #m1 {background-color:rgb(255,0,0);opacity:0.6;} #m2 {background-color:rgb(0,255,0);opacity:0.6;} #m3 {background-color:rgb(0,0,255);opacity:0.6;} </style> </head> <body> <p>HSLA colors:</p> <p id = "m1">Red</p> <p id = "m2">Green</p> <p id = "m3">Blue</p> </body> </html> It will produce the following result − HSLA colors: Red Green Blue 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2686, "s": 2626, "text": "CSS3 has Supported additional color properties as follows −" }, { "code": null, "e": 2698, "s": 2686, "text": "RGBA colors" }, { "code": null, "e": 2709, "s": 2698, "text": "HSL colors" }, { "code": null, "e": 2721, "s": 2709, "text": "HSLA colors" }, { "code": null, "e": 2729, "s": 2721, "text": "Opacity" }, { "code": null, "e": 2929, "s": 2729, "text": "RGBA stands for Red Green Blue Alpha.It is an extension of CSS2,Alpha specifies the opacity of a color and parameter number is a numerical between 0.0 to 1.0. A Sample syntax of RGBA as shown below −" }, { "code": null, "e": 3071, "s": 2929, "text": "#d1 {background-color: rgba(255, 0, 0, 0.5);} \n#d2 {background-color: rgba(0, 255, 0, 0.5);} \n#d3 {background-color: rgba(0, 0, 255, 0.5);}\n" }, { "code": null, "e": 3261, "s": 3071, "text": "HSL stands for hue, saturation, lightness.Here Huge is a degree on the color wheel, saturation and lightness are percentage values between 0 to 100%. A Sample syntax of HSL as shown below −" }, { "code": null, "e": 3401, "s": 3261, "text": "#g1 {background-color: hsl(120, 100%, 50%);} \n#g2 {background-color: hsl(120, 100%, 75%);} \n#g3 {background-color: hsl(120, 100%, 25%);}\n" }, { "code": null, "e": 3545, "s": 3401, "text": "HSLA stands for hue, saturation, lightness and alpha. Alpha value specifies the opacity as shown RGBA. A Sample syntax of HSLA as shown below −" }, { "code": null, "e": 3705, "s": 3545, "text": "#g1 {background-color: hsla(120, 100%, 50%, 0.3);} \n#g2 {background-color: hsla(120, 100%, 75%, 0.3);} \n#g3 {background-color: hsla(120, 100%, 25%, 0.3);} \n" }, { "code": null, "e": 3818, "s": 3705, "text": "opacity is a thinner paints need black added to increase opacity. A sample syntax of opacity is as shown below −" }, { "code": null, "e": 3971, "s": 3818, "text": "#g1 {background-color:rgb(255,0,0);opacity:0.6;} \n#g2 {background-color:rgb(0,255,0);opacity:0.6;} \n#g3 {background-color:rgb(0,0,255);opacity:0.6;} \n" }, { "code": null, "e": 4020, "s": 3971, "text": "The following example shows rgba color property." }, { "code": null, "e": 4370, "s": 4020, "text": "<html>\n <head>\n <style>\n #p1 {background-color:rgba(255,0,0,0.3);}\n #p2 {background-color:rgba(0,255,0,0.3);}\n #p3 {background-color:rgba(0,0,255,0.3);}\n </style>\n </head>\n\n <body>\n <p>RGBA colors:</p>\n <p id = \"p1\">Red</p>\n <p id = \"p2\">Green</p>\n <p id = \"p3\">Blue</p>\n </body>\n</html>" }, { "code": null, "e": 4409, "s": 4370, "text": "It will produce the following result −" }, { "code": null, "e": 4422, "s": 4409, "text": "RGBA colors:" }, { "code": null, "e": 4426, "s": 4422, "text": "Red" }, { "code": null, "e": 4432, "s": 4426, "text": "Green" }, { "code": null, "e": 4437, "s": 4432, "text": "Blue" }, { "code": null, "e": 4485, "s": 4437, "text": "The following example shows HSL color property." }, { "code": null, "e": 4851, "s": 4485, "text": "<html>\n <head>\n <style>\n #g1 {background-color:hsl(120, 100%, 50%);}\n #g2 {background-color:hsl(120,100%,75%);}\n #g3 {background-color:hsl(120,100%,25%);}\n </style>\n </head>\n\n <body>\n <p>HSL colors:</p>\n <p id = \"g1\">Green</p>\n <p id = \"g2\">Normal Green</p>\n <p id = \"g3\">Dark Green</p>\n </body>\n</html>" }, { "code": null, "e": 4890, "s": 4851, "text": "It will produce the following result −" }, { "code": null, "e": 4902, "s": 4890, "text": "HSL colors:" }, { "code": null, "e": 4908, "s": 4902, "text": "Green" }, { "code": null, "e": 4921, "s": 4908, "text": "Normal Green" }, { "code": null, "e": 4932, "s": 4921, "text": "Dark Green" }, { "code": null, "e": 4981, "s": 4932, "text": "The following example shows HSLA color property." }, { "code": null, "e": 5362, "s": 4981, "text": "<html>\n <head>\n <style>\n #d1 {background-color:hsla(120,100%,50%,0.3);}\n #d2 {background-color:hsla(120,100%,75%,0.3);}\n #d3 {background-color:hsla(120,100%,25%,0.3);}\n </style>\n </head>\n\n <body>\n <p>HSLA colors:</p>\n <p id = \"d1\">Less opacity green</p>\n <p id = \"d2\">Green</p>\n <p id = \"d3\">Green</p>\n </body>\n</html>" }, { "code": null, "e": 5401, "s": 5362, "text": "It will produce the following result −" }, { "code": null, "e": 5414, "s": 5401, "text": "HSLA colors:" }, { "code": null, "e": 5433, "s": 5414, "text": "Less opacity green" }, { "code": null, "e": 5439, "s": 5433, "text": "Green" }, { "code": null, "e": 5445, "s": 5439, "text": "Green" }, { "code": null, "e": 5491, "s": 5445, "text": "The following example shows Opacity property." }, { "code": null, "e": 5864, "s": 5491, "text": "<html>\n <head>\n <style>\n #m1 {background-color:rgb(255,0,0);opacity:0.6;} \n #m2 {background-color:rgb(0,255,0);opacity:0.6;} \n #m3 {background-color:rgb(0,0,255);opacity:0.6;}\n </style>\n </head>\n\n <body>\n <p>HSLA colors:</p>\n <p id = \"m1\">Red</p>\n <p id = \"m2\">Green</p>\n <p id = \"m3\">Blue</p>\n </body>\n</html>" }, { "code": null, "e": 5903, "s": 5864, "text": "It will produce the following result −" }, { "code": null, "e": 5916, "s": 5903, "text": "HSLA colors:" }, { "code": null, "e": 5920, "s": 5916, "text": "Red" }, { "code": null, "e": 5926, "s": 5920, "text": "Green" }, { "code": null, "e": 5931, "s": 5926, "text": "Blue" }, { "code": null, "e": 5966, "s": 5931, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5980, "s": 5966, "text": " Anadi Sharma" }, { "code": null, "e": 6015, "s": 5980, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6032, "s": 6015, "text": " Frahaan Hussain" }, { "code": null, "e": 6067, "s": 6032, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6098, "s": 6067, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6133, "s": 6098, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6164, "s": 6133, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6199, "s": 6164, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6230, "s": 6199, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6263, "s": 6230, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 6294, "s": 6263, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6301, "s": 6294, "text": " Print" }, { "code": null, "e": 6312, "s": 6301, "text": " Add Notes" } ]
Organizing Tournament Problem - GeeksforGeeks
12 Aug, 2021 Given a positive integer N representing the count of players playing the game. The game is played between two teams such that each team consists of at least one player but the total count of players in the game must be N. The game lasts in exactly 30 minutes, the task is to check if all players will play the game against each other or not If the game can be played up to T hours and it is allowed to play the game more than 1 times. If found to be true then print “Possible”. Otherwise, print “Not Possible”. Examples: Input: N = 3, T = 1 Output: Possible Explanation: In 1st half hours Players { p1, p2 } played the game against { p3 }. In 2d half hours Players { p2, P3 } played the game against { p1 } Since all players played the game against each other within T(=1) hours. Therefore, the required output is “Possible”. Input: N = 4, T = 0.5 Output: Not Possible Explanation: In 1st half hours Players { p1, p2 } played the game against { p3, p4 }. Since player p1 did not play the game against p2 within T(=0.5) hours. Therefore, the required output is “Not Possible”. Approach: The problem can be solved using Greedy technique. Following are the observations: In each game, if one of the two teams has only one player then the game must be played N – 1 times. In each game, If one of the team have N / 2 players and other team have (N + 1) / 2 then the game must be played (N + 1) / 2 times. Follow the steps below to solve the problem: If total time to play the game N-1 times is less than or equal to T, then print “Possible”. If total time to play the game (N + 1) / 2 times is less than or equal to T, then print “Possible”. Otherwise, print “Not Possible”. 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 find the N players// the game against each other or notstring calculate(int N, int T){ // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return "-1"; } // Converting hours into minutes int minutes = T * 60; // Calculating maximum games that // can be played. int max_match = N - 1; // Time required for conducting // maximum games int max_time = max_match * 30; // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return "Possible"; } // Calculating minimum games int min_match = N / 2; min_match = N - min_match; // Time required for conducting // minimum games int min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return "Possible"; } // Return not possible if time // is less than required time return "Not Possible";} // Driver Code // Total count of playersint main(){ int N = 6, T = 2; // function call cout << calculate(N, T); return 0;} // This code is contributed by Parth Manchanda // Java program for the above approachimport java.io.*; class GFG { // Function to find the N players// the game against each other or notstatic String calculate(int N, int T){ // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return "-1"; } // Converting hours into minutes int minutes = T * 60; // Calculating maximum games that // can be played. int max_match = N - 1; // Time required for conducting // maximum games int max_time = max_match * 30; // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return "Possible"; } // Calculating minimum games int min_match = N / 2; min_match = N - min_match; // Time required for conducting // minimum games int min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return "Possible"; } // Return not possible if time // is less than required time return "Not Possible";} // Driver codepublic static void main(String[] args){ int N = 6, T = 2; // function call System.out.println(calculate(N, T));}} // This code is contributed by sanjoy_62. # Python program for the above problem # Function to find the N players# the game against each other or notdef calculate(N, T): # Base Case if N <= 1 or T <= 0: # Return -1 if not valid return -1 # Converting hours into minutes minutes = T * 60 # Calculating maximum games that # can be played. max_match = N - 1 # Time required for conducting # maximum games max_time = max_match * 30 # Checking if it is possible # to conduct maximum games if max_time <= minutes: # Return possible return "Possible" # Calculating minimum games min_match = N//2 min_match = N - min_match # Time required for conducting # minimum games min_time = min_match * 30 # Checking if it is possible # to conduct minimum games if min_time <= minutes: # Return possible return "Possible" # Return not possible if time # is less than required time return "Not Possible" # Driver Codeif __name__ == "__main__": # Total count of players N = 6 # Given hours T = 2 # Function call ans = calculate(N, T) # Print ans print(ans) // C# program for the above approachusing System; class GFG{ // Function to find the N players// the game against each other or notstatic string calculate(int N, int T){ // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return "-1"; } // Converting hours into minutes int minutes = T * 60; // Calculating maximum games that // can be played. int max_match = N - 1; // Time required for conducting // maximum games int max_time = max_match * 30; // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return "Possible"; } // Calculating minimum games int min_match = N / 2; min_match = N - min_match; // Time required for conducting // minimum games int min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return "Possible"; } // Return not possible if time // is less than required time return "Not Possible";} // Driver Codepublic static void Main(String[] args){ int N = 6, T = 2; // function call Console.WriteLine(calculate(N, T));}} // This code is contributed by splevel62. <script> // JavaScript Program for the above approach // Function to find the N players // the game against each other or not function calculate(N, T) { // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return -1; } // Converting hours into minutes let minutes = T * 60; // Calculating maximum games that // can be played. let max_match = N - 1 // Time required for conducting // maximum games max_time = max_match * 30 // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return "Possible"; } // Calculating minimum games min_match = Math.floor(N / 2); min_match = N - min_match // Time required for conducting // minimum games min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return "Possible"; // Return not possible if time // is less than required time return "Not Possible"; } } // Driver Code // Total count of players let N = 6 // Given hours let T = 2 // Function call let ans = calculate(N, T) // Print ans document.write(ans); // This code is contributed by Potta Lokesh </script> Possible Time Complexity: O(1)Auxiliary Space: O(1) lokeshpotta20 parthmanchanda81 splevel62 sanjoy_62 Codenation Greedy Algorithms interview-preparation Mathematical Codenation 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. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) Generate all permutation of a set in Python How to check if a given point lies inside or outside a polygon? Merge two sorted arrays with O(1) extra space Singular Value Decomposition (SVD) Program to multiply two matrices
[ { "code": null, "e": 26073, "s": 26045, "text": "\n12 Aug, 2021" }, { "code": null, "e": 26584, "s": 26073, "text": "Given a positive integer N representing the count of players playing the game. The game is played between two teams such that each team consists of at least one player but the total count of players in the game must be N. The game lasts in exactly 30 minutes, the task is to check if all players will play the game against each other or not If the game can be played up to T hours and it is allowed to play the game more than 1 times. If found to be true then print “Possible”. Otherwise, print “Not Possible”." }, { "code": null, "e": 26594, "s": 26584, "text": "Examples:" }, { "code": null, "e": 26899, "s": 26594, "text": "Input: N = 3, T = 1 Output: Possible Explanation: In 1st half hours Players { p1, p2 } played the game against { p3 }. In 2d half hours Players { p2, P3 } played the game against { p1 } Since all players played the game against each other within T(=1) hours. Therefore, the required output is “Possible”." }, { "code": null, "e": 27149, "s": 26899, "text": "Input: N = 4, T = 0.5 Output: Not Possible Explanation: In 1st half hours Players { p1, p2 } played the game against { p3, p4 }. Since player p1 did not play the game against p2 within T(=0.5) hours. Therefore, the required output is “Not Possible”." }, { "code": null, "e": 27241, "s": 27149, "text": "Approach: The problem can be solved using Greedy technique. Following are the observations:" }, { "code": null, "e": 27341, "s": 27241, "text": "In each game, if one of the two teams has only one player then the game must be played N – 1 times." }, { "code": null, "e": 27473, "s": 27341, "text": "In each game, If one of the team have N / 2 players and other team have (N + 1) / 2 then the game must be played (N + 1) / 2 times." }, { "code": null, "e": 27518, "s": 27473, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27610, "s": 27518, "text": "If total time to play the game N-1 times is less than or equal to T, then print “Possible”." }, { "code": null, "e": 27710, "s": 27610, "text": "If total time to play the game (N + 1) / 2 times is less than or equal to T, then print “Possible”." }, { "code": null, "e": 27743, "s": 27710, "text": "Otherwise, print “Not Possible”." }, { "code": null, "e": 27794, "s": 27743, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27798, "s": 27794, "text": "C++" }, { "code": null, "e": 27803, "s": 27798, "text": "Java" }, { "code": null, "e": 27811, "s": 27803, "text": "Python3" }, { "code": null, "e": 27814, "s": 27811, "text": "C#" }, { "code": null, "e": 27825, "s": 27814, "text": "Javascript" }, { "code": "// C++ Program for the above approach#include <iostream>using namespace std; // Function to find the N players// the game against each other or notstring calculate(int N, int T){ // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return \"-1\"; } // Converting hours into minutes int minutes = T * 60; // Calculating maximum games that // can be played. int max_match = N - 1; // Time required for conducting // maximum games int max_time = max_match * 30; // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return \"Possible\"; } // Calculating minimum games int min_match = N / 2; min_match = N - min_match; // Time required for conducting // minimum games int min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return \"Possible\"; } // Return not possible if time // is less than required time return \"Not Possible\";} // Driver Code // Total count of playersint main(){ int N = 6, T = 2; // function call cout << calculate(N, T); return 0;} // This code is contributed by Parth Manchanda", "e": 29112, "s": 27825, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { // Function to find the N players// the game against each other or notstatic String calculate(int N, int T){ // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return \"-1\"; } // Converting hours into minutes int minutes = T * 60; // Calculating maximum games that // can be played. int max_match = N - 1; // Time required for conducting // maximum games int max_time = max_match * 30; // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return \"Possible\"; } // Calculating minimum games int min_match = N / 2; min_match = N - min_match; // Time required for conducting // minimum games int min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return \"Possible\"; } // Return not possible if time // is less than required time return \"Not Possible\";} // Driver codepublic static void main(String[] args){ int N = 6, T = 2; // function call System.out.println(calculate(N, T));}} // This code is contributed by sanjoy_62.", "e": 30395, "s": 29112, "text": null }, { "code": "# Python program for the above problem # Function to find the N players# the game against each other or notdef calculate(N, T): # Base Case if N <= 1 or T <= 0: # Return -1 if not valid return -1 # Converting hours into minutes minutes = T * 60 # Calculating maximum games that # can be played. max_match = N - 1 # Time required for conducting # maximum games max_time = max_match * 30 # Checking if it is possible # to conduct maximum games if max_time <= minutes: # Return possible return \"Possible\" # Calculating minimum games min_match = N//2 min_match = N - min_match # Time required for conducting # minimum games min_time = min_match * 30 # Checking if it is possible # to conduct minimum games if min_time <= minutes: # Return possible return \"Possible\" # Return not possible if time # is less than required time return \"Not Possible\" # Driver Codeif __name__ == \"__main__\": # Total count of players N = 6 # Given hours T = 2 # Function call ans = calculate(N, T) # Print ans print(ans)", "e": 31566, "s": 30395, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the N players// the game against each other or notstatic string calculate(int N, int T){ // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return \"-1\"; } // Converting hours into minutes int minutes = T * 60; // Calculating maximum games that // can be played. int max_match = N - 1; // Time required for conducting // maximum games int max_time = max_match * 30; // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return \"Possible\"; } // Calculating minimum games int min_match = N / 2; min_match = N - min_match; // Time required for conducting // minimum games int min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return \"Possible\"; } // Return not possible if time // is less than required time return \"Not Possible\";} // Driver Codepublic static void Main(String[] args){ int N = 6, T = 2; // function call Console.WriteLine(calculate(N, T));}} // This code is contributed by splevel62.", "e": 32839, "s": 31566, "text": null }, { "code": "<script> // JavaScript Program for the above approach // Function to find the N players // the game against each other or not function calculate(N, T) { // Base Case if (N <= 1 || T <= 0) { // Return -1 if not valid return -1; } // Converting hours into minutes let minutes = T * 60; // Calculating maximum games that // can be played. let max_match = N - 1 // Time required for conducting // maximum games max_time = max_match * 30 // Checking if it is possible // to conduct maximum games if (max_time <= minutes) { // Return possible return \"Possible\"; } // Calculating minimum games min_match = Math.floor(N / 2); min_match = N - min_match // Time required for conducting // minimum games min_time = min_match * 30; // Checking if it is possible // to conduct minimum games if (min_time <= minutes) { // Return possible return \"Possible\"; // Return not possible if time // is less than required time return \"Not Possible\"; } } // Driver Code // Total count of players let N = 6 // Given hours let T = 2 // Function call let ans = calculate(N, T) // Print ans document.write(ans); // This code is contributed by Potta Lokesh </script>", "e": 34518, "s": 32839, "text": null }, { "code": null, "e": 34527, "s": 34518, "text": "Possible" }, { "code": null, "e": 34572, "s": 34529, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 34586, "s": 34572, "text": "lokeshpotta20" }, { "code": null, "e": 34603, "s": 34586, "text": "parthmanchanda81" }, { "code": null, "e": 34613, "s": 34603, "text": "splevel62" }, { "code": null, "e": 34623, "s": 34613, "text": "sanjoy_62" }, { "code": null, "e": 34634, "s": 34623, "text": "Codenation" }, { "code": null, "e": 34652, "s": 34634, "text": "Greedy Algorithms" }, { "code": null, "e": 34674, "s": 34652, "text": "interview-preparation" }, { "code": null, "e": 34687, "s": 34674, "text": "Mathematical" }, { "code": null, "e": 34698, "s": 34687, "text": "Codenation" }, { "code": null, "e": 34711, "s": 34698, "text": "Mathematical" }, { "code": null, "e": 34809, "s": 34711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34853, "s": 34809, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34884, "s": 34853, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34909, "s": 34884, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34941, "s": 34909, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34983, "s": 34941, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 35027, "s": 34983, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 35091, "s": 35027, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 35137, "s": 35091, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 35172, "s": 35137, "text": "Singular Value Decomposition (SVD)" } ]
plotly.express.line() function in Python - GeeksforGeeks
20 Jul, 2020 Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use. This function is used to create a line plot. It can also be created using the pandas dataframe where each row of data_frame is represented as vertex of a polyline mark in 2D space. Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None) Parameters: data_frame: DataFrame or array-like or dict needs to be passed for column names. x, y: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x and y axis in cartesian coordinates respectively. color: This parameters assign color to marks. line_group: This parameter is used to group rows of data_frame into lines. line_dash: This parameter is used to assign dash-patterns to lines. hover_name: Values from this column or array_like appear in bold in the hover tooltip. hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. Example 1: Python3 import plotly.express as px df = px.data.tips() plot = px.line(df, x = 'day', y = 'time')plot.show() Output: Example 2: Using color argument Python3 import plotly.express as px df = px.data.tips() plot = px.line(df, x = 'time', y = 'total_bill', color = 'sex')plot.show() Output: Example 3: Using the line_group argument Python3 import plotly.express as px df = px.data.tips() plot = px.line(df, x = 'time', y = 'total_bill', color = 'sex', line_group = 'day') plot.show() Output: Python Plotly express-class Python-Plotly 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() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26301, "s": 26273, "text": "\n20 Jul, 2020" }, { "code": null, "e": 26495, "s": 26301, "text": "Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use." }, { "code": null, "e": 26676, "s": 26495, "text": "This function is used to create a line plot. It can also be created using the pandas dataframe where each row of data_frame is represented as vertex of a polyline mark in 2D space." }, { "code": null, "e": 26868, "s": 26676, "text": "Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None)" }, { "code": null, "e": 26880, "s": 26868, "text": "Parameters:" }, { "code": null, "e": 26961, "s": 26880, "text": "data_frame: DataFrame or array-like or dict needs to be passed for column names." }, { "code": null, "e": 27196, "s": 26961, "text": "x, y: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x and y axis in cartesian coordinates respectively. " }, { "code": null, "e": 27242, "s": 27196, "text": "color: This parameters assign color to marks." }, { "code": null, "e": 27317, "s": 27242, "text": "line_group: This parameter is used to group rows of data_frame into lines." }, { "code": null, "e": 27385, "s": 27317, "text": "line_dash: This parameter is used to assign dash-patterns to lines." }, { "code": null, "e": 27473, "s": 27385, "text": "hover_name: Values from this column or array_like appear in bold in the hover tooltip." }, { "code": null, "e": 27725, "s": 27473, "text": "hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip." }, { "code": null, "e": 27736, "s": 27725, "text": "Example 1:" }, { "code": null, "e": 27744, "s": 27736, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() plot = px.line(df, x = 'day', y = 'time')plot.show()", "e": 27847, "s": 27744, "text": null }, { "code": null, "e": 27855, "s": 27847, "text": "Output:" }, { "code": null, "e": 27887, "s": 27855, "text": "Example 2: Using color argument" }, { "code": null, "e": 27895, "s": 27887, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() plot = px.line(df, x = 'time', y = 'total_bill', color = 'sex')plot.show()", "e": 28049, "s": 27895, "text": null }, { "code": null, "e": 28057, "s": 28049, "text": "Output:" }, { "code": null, "e": 28098, "s": 28057, "text": "Example 3: Using the line_group argument" }, { "code": null, "e": 28106, "s": 28098, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() plot = px.line(df, x = 'time', y = 'total_bill', color = 'sex', line_group = 'day') plot.show()", "e": 28296, "s": 28106, "text": null }, { "code": null, "e": 28304, "s": 28296, "text": "Output:" }, { "code": null, "e": 28332, "s": 28304, "text": "Python Plotly express-class" }, { "code": null, "e": 28346, "s": 28332, "text": "Python-Plotly" }, { "code": null, "e": 28353, "s": 28346, "text": "Python" }, { "code": null, "e": 28451, "s": 28353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28469, "s": 28451, "text": "Python Dictionary" }, { "code": null, "e": 28504, "s": 28469, "text": "Read a file line by line in Python" }, { "code": null, "e": 28536, "s": 28504, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28558, "s": 28536, "text": "Enumerate() in Python" }, { "code": null, "e": 28600, "s": 28558, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28630, "s": 28600, "text": "Iterate over a list in Python" }, { "code": null, "e": 28656, "s": 28630, "text": "Python String | replace()" }, { "code": null, "e": 28700, "s": 28656, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28729, "s": 28700, "text": "*args and **kwargs in Python" } ]
C Program for focal length of a lens
Given two floating values; image distance and object distance from a lens; the task is to print the focal length of the lens. What is focal length? Focal length of an optical system is the distance between the center of lens or curved mirror and its focus. Let’s understand with the help of figure given below − In the above figure i is the object, and F is the image of the object which is formed and f is the focal length of the image. So to find the focal length of the image from the lens the formula is − 1F= 1O+1I Where, F is the focal length. O is the total distance of the lens and the object. I is the total distance between lens and the image formed by the lens. Input: image_distance=5, object_distance=10 Output: Focal length of a lens is: 3.333333 Explanation: 1/5 + 1/10 = 3/10🡺 F = 10/3 = 3.33333333 Input: image_distance = 7, object_distance = 10 Output: Focal length of a lens is: 4.1176470 Approach we are using to solve the above problem − Take the input of the image_disance and object_distance. Find the sum 1/image_distance and 1/object_distance and return the result divided by 1. Print the result. Start Step 1-> In function float focal_length(float image_distance, float object_distance) Return 1 / ((1 / image_distance) + (1 / object_distance)) Step 2-> In function int main() Declare and initialize the first input image_distance = 5 Declare and initialize the second input object_distance = 10 Print the results obtained from calling the function focal_length(image_distance, object_distance) Stop Live Demo #include <stdio.h> // Function to find the focal length of a lens float focal_length(float image_distance, float object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } // main function int main() { // distance between the lens and the image float image_distance = 5; // distance between the lens and the object float object_distance = 10; printf("Focal length of a lens is: %f\n", focal_length(image_distance, object_distance)); return 0; } Focal length of a lens is: 3.333333
[ { "code": null, "e": 1188, "s": 1062, "text": "Given two floating values; image distance and object distance from a lens; the task is to print the focal length of the lens." }, { "code": null, "e": 1210, "s": 1188, "text": "What is focal length?" }, { "code": null, "e": 1319, "s": 1210, "text": "Focal length of an optical system is the distance between the center of lens or curved mirror and its focus." }, { "code": null, "e": 1374, "s": 1319, "text": "Let’s understand with the help of figure given below −" }, { "code": null, "e": 1500, "s": 1374, "text": "In the above figure i is the object, and F is the image of the object which is formed and f is the focal length of the image." }, { "code": null, "e": 1572, "s": 1500, "text": "So to find the focal length of the image from the lens the formula is −" }, { "code": null, "e": 1582, "s": 1572, "text": "1F= 1O+1I" }, { "code": null, "e": 1612, "s": 1582, "text": "Where, F is the focal length." }, { "code": null, "e": 1664, "s": 1612, "text": "O is the total distance of the lens and the object." }, { "code": null, "e": 1735, "s": 1664, "text": "I is the total distance between lens and the image formed by the lens." }, { "code": null, "e": 1971, "s": 1735, "text": "Input: image_distance=5, object_distance=10\nOutput: Focal length of a lens is: 3.333333\nExplanation: 1/5 + 1/10 = 3/10🡺 F = 10/3 = 3.33333333\n\nInput: image_distance = 7, object_distance = 10\nOutput: Focal length of a lens is: 4.1176470" }, { "code": null, "e": 2022, "s": 1971, "text": "Approach we are using to solve the above problem −" }, { "code": null, "e": 2079, "s": 2022, "text": "Take the input of the image_disance and object_distance." }, { "code": null, "e": 2167, "s": 2079, "text": "Find the sum 1/image_distance and 1/object_distance and return the result divided by 1." }, { "code": null, "e": 2185, "s": 2167, "text": "Print the result." }, { "code": null, "e": 2602, "s": 2185, "text": "Start\nStep 1-> In function float focal_length(float image_distance, float object_distance)\n Return 1 / ((1 / image_distance) + (1 / object_distance))\n\nStep 2-> In function int main()\n Declare and initialize the first input image_distance = 5\n Declare and initialize the second input object_distance = 10\n Print the results obtained from calling the function focal_length(image_distance, object_distance)\nStop" }, { "code": null, "e": 2613, "s": 2602, "text": " Live Demo" }, { "code": null, "e": 3100, "s": 2613, "text": "#include <stdio.h>\n// Function to find the focal length of a lens\nfloat focal_length(float image_distance, float object_distance) {\n return 1 / ((1 / image_distance) + (1 / object_distance));\n}\n// main function\nint main() {\n // distance between the lens and the image\n float image_distance = 5;\n // distance between the lens and the object\n float object_distance = 10;\n printf(\"Focal length of a lens is: %f\\n\", focal_length(image_distance, object_distance));\n return 0;\n}" }, { "code": null, "e": 3136, "s": 3100, "text": "Focal length of a lens is: 3.333333" } ]
C/C++ Program to find sum of elements in a given array - GeeksforGeeks
28 Aug, 2018 Given an array of integers, find sum of its elements. Examples : Input : arr[] = {1, 2, 3} Output : 6 1 + 2 + 3 = 6 Input : arr[] = {15, 12, 13, 10} Output : 50 /* CPP Program to find sum of elements in a given array */#include <bits/stdc++.h> // function to return sum of elements// in an array of size nint sum(int arr[], int n){ int sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum;} int main(){ int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); printf("Sum of given array is %d", sum(arr, n)); return 0;} Please refer complete article on Program to find sum of elements in a given array for more details! CBSE - Class 11 school-programming C Programs C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Handling multiple clients on server with multithreading using Socket Programming in C/C++ C++ Program for QuickSort Sorting a Map by value in C++ STL Shallow Copy and Deep Copy in C++ delete keyword in C++ Passing a function as a parameter in C++
[ { "code": null, "e": 26200, "s": 26172, "text": "\n28 Aug, 2018" }, { "code": null, "e": 26254, "s": 26200, "text": "Given an array of integers, find sum of its elements." }, { "code": null, "e": 26265, "s": 26254, "text": "Examples :" }, { "code": null, "e": 26363, "s": 26265, "text": "Input : arr[] = {1, 2, 3}\nOutput : 6\n1 + 2 + 3 = 6\n\nInput : arr[] = {15, 12, 13, 10}\nOutput : 50\n" }, { "code": "/* CPP Program to find sum of elements in a given array */#include <bits/stdc++.h> // function to return sum of elements// in an array of size nint sum(int arr[], int n){ int sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum;} int main(){ int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Sum of given array is %d\", sum(arr, n)); return 0;}", "e": 26851, "s": 26363, "text": null }, { "code": null, "e": 26951, "s": 26851, "text": "Please refer complete article on Program to find sum of elements in a given array for more details!" }, { "code": null, "e": 26967, "s": 26951, "text": "CBSE - Class 11" }, { "code": null, "e": 26986, "s": 26967, "text": "school-programming" }, { "code": null, "e": 26997, "s": 26986, "text": "C Programs" }, { "code": null, "e": 27010, "s": 26997, "text": "C++ Programs" }, { "code": null, "e": 27108, "s": 27010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27149, "s": 27108, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27180, "s": 27149, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27221, "s": 27180, "text": "C program to find the length of a string" }, { "code": null, "e": 27255, "s": 27221, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 27345, "s": 27255, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 27371, "s": 27345, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27405, "s": 27371, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 27439, "s": 27405, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 27461, "s": 27439, "text": "delete keyword in C++" } ]
Different Media Types in CSS
CSS Media Types are the device types on which the document is rendered and specific styles can be defined for every media type. Following are the Media Types in CSS3 and Media Queries 4 − NOTE −Several media types (such as aural, braille, embossed, handheld, projection, ttv and tv) are deprecated in Media Queries 4 and shouldn't be used. The aural type has been replaced by speech media type. Let’s see an example for styling screen and print media types − Live Demo <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" media="screen" href="screen.css"> <link rel="stylesheet" type="text/css" media="print" href="print.css"> </head> <body> <div></div> </body> </html> div { height: 50px; width: 100px; border-radius: 20%; border: 2px solid blueviolet; box-shadow: 22px 12px 3px 3px lightblue; position: absolute; left: 30%; top: 20px; } CSS document (print.css): div { height: 50px; width: 100px; border-radius: 20%; border: 2px solid #dc3545; box-shadow: 22px 12px 3px 3px #dc3545; position: absolute; left: 30%; top: 20px; } When document is visible in a screen mediatype − When document is visible in a print mediatype − Let’s see another example for styling screen and print media types − Live Demo <!DOCTYPE html> <html> <head> <style type="text/css"> @import url(screen.css) screen; @import url(print.css) print; </style> </head> <body> <p> Vivamus commodo, dolor eu porttitor sagittis, orci nisl consectetur ipsum, vel volutpat nibh lectus at erat. Cras scelerisque faucibus tellus aliquam commodo.Donec sem urna, facilisis at ipsum id, viverra sollicitudin est. Nam rhoncus sollicitudin lorem, a accumsan purus varius eget. </p> <p class="two">In ultrices lectus nisi. Nulla varius ex ut tortor congue viverra. Sed sodales vehicula leo, vitae interdum elit vehicula nec. Donec turpis nunc, iaculis et nisi sit amet, feugiat lacinia metus. </p> <p>Suspendisse eget ligula et risus lobortis ornare id at elit. Suspendisse potenti. Vivamus pellentesque eleifend pellentesque. Vestibulum neque ante, iaculis a sagittis et, fermentum at metus.</p> </body> </html> p { color: navy; font-style: italic; } .two { color: #c303c3; font-size: 20px; } body { background-color: honeydew;} CSS document (print.css): p { color: red; font-style: italic;} .two { color: #989898; font-size: 40px; } When document is visible in a screen mediatype − When document is visible in a print mediatype −
[ { "code": null, "e": 1190, "s": 1062, "text": "CSS Media Types are the device types on which the document is rendered and specific styles can be defined for every media type." }, { "code": null, "e": 1250, "s": 1190, "text": "Following are the Media Types in CSS3 and Media Queries 4 −" }, { "code": null, "e": 1457, "s": 1250, "text": "NOTE −Several media types (such as aural, braille, embossed, handheld, projection, ttv and tv) are deprecated in Media Queries 4 and shouldn't be used. The aural type has been replaced by speech media type." }, { "code": null, "e": 1521, "s": 1457, "text": "Let’s see an example for styling screen and print media types −" }, { "code": null, "e": 1532, "s": 1521, "text": " Live Demo" }, { "code": null, "e": 1749, "s": 1532, "text": "<!DOCTYPE html>\n<html>\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"screen.css\">\n<link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n</head>\n<body>\n<div></div>\n</body>\n</html>" }, { "code": null, "e": 2156, "s": 1749, "text": "div {\n height: 50px;\n width: 100px;\n border-radius: 20%;\n border: 2px solid blueviolet;\n box-shadow: 22px 12px 3px 3px lightblue;\n position: absolute;\n left: 30%;\n top: 20px;\n}\nCSS document (print.css):\ndiv {\n height: 50px;\n width: 100px;\n border-radius: 20%;\n border: 2px solid #dc3545;\n box-shadow: 22px 12px 3px 3px #dc3545;\n position: absolute;\n left: 30%;\n top: 20px;\n}" }, { "code": null, "e": 2205, "s": 2156, "text": "When document is visible in a screen mediatype −" }, { "code": null, "e": 2253, "s": 2205, "text": "When document is visible in a print mediatype −" }, { "code": null, "e": 2322, "s": 2253, "text": "Let’s see another example for styling screen and print media types −" }, { "code": null, "e": 2333, "s": 2322, "text": " Live Demo" }, { "code": null, "e": 3197, "s": 2333, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style type=\"text/css\">\n@import url(screen.css) screen;\n@import url(print.css) print;\n</style>\n</head>\n<body>\n<p> Vivamus commodo, dolor eu porttitor sagittis, orci nisl consectetur ipsum, vel volutpat nibh lectus at erat. Cras scelerisque faucibus tellus aliquam commodo.Donec sem urna, facilisis at ipsum id, viverra sollicitudin est. Nam rhoncus sollicitudin lorem, a accumsan purus varius eget. </p>\n<p class=\"two\">In ultrices lectus nisi. Nulla varius ex ut tortor congue viverra. Sed sodales vehicula leo, vitae interdum elit vehicula nec. Donec turpis nunc, iaculis et nisi sit amet, feugiat lacinia metus. </p>\n<p>Suspendisse eget ligula et risus lobortis ornare id at elit. Suspendisse potenti. Vivamus pellentesque eleifend pellentesque. Vestibulum neque ante, iaculis a sagittis et, fermentum at metus.</p>\n</body>\n</html>" }, { "code": null, "e": 3419, "s": 3197, "text": "p { color: navy; font-style: italic; }\n.two { color: #c303c3; font-size: 20px; }\nbody { background-color: honeydew;}\nCSS document (print.css):\np { color: red; font-style: italic;}\n.two { color: #989898; font-size: 40px; }" }, { "code": null, "e": 3468, "s": 3419, "text": "When document is visible in a screen mediatype −" }, { "code": null, "e": 3516, "s": 3468, "text": "When document is visible in a print mediatype −" } ]
Difference Between NFD, NFC, NFKD, and NFKC Explained with Python Code | by Xu LIANG | Towards Data Science
Recently I am working on an NLP task in Japanese, one problem is to convert special characters to a normalized form. So I have done a little research and write this post for anyone who has the same need. Japanese contains different forms of the character, for example, Latin has two forms, full-width form, and half-width. In the above example, we can see the full-width form is very ugly and is also hard to utilizing for the following processing. So we need to convert it to a normalized form. Use NFKC method. >>> from unicodedata import normalize>>> s = "株式会社KADOKAWA Future Publishing">>> normalize('NFKC', s)株式会社KADOKAWA Future Publishing There are 4 kinds of Unicode normalization forms. This article give a very detailed explanation. But I will explain the difference with a simple and easy understanding way. First, we could see the below result for an intuitive understanding. アイウエオ ==(NFC)==> アイウエオアイウエオ ==(NFD)==> アイウエオアイウエオ ==(NFKC)==> アイウエオアイウエオ ==(NFKD)==> アイウエオパピプペポ ==(NFC)==> パピプペポパピプペポ ==(NFD)==> パピプペポパピプペポ ==(NFKC)==> パピプペポパピプペポ ==(NFKD)==> パピプペポパピプペポ ==(NFC)==> パピプペポパピプペポ ==(NFD)==> パピプペポパピプペポ ==(NFKC)==> パピプペポパピプペポ ==(NFKD)==> パピプペポabcABC ==(NFC)==> abcABCabcABC ==(NFD)==> abcABCabcABC ==(NFKC)==> abcABCabcABC ==(NFKD)==> abcABC123 ==(NFC)==> 123123 ==(NFD)==> 123123 ==(NFKC)==> 123123 ==(NFKD)==> 123+-.~)} ==(NFC)==> +-.~)}+-.~)} ==(NFD)==> +-.~)}+-.~)} ==(NFKC)==> +-.~)}+-.~)} ==(NFKD)==> +-.~)} There are two classification methods for these 4 forms. # 1 original form changed or not- A(not changed): NFC & NFD- B(changed): NFKC & NFKD# 2 the length of original length changed or not- A(not changed): NFC & NFKC- B(changed): NFD & NFKD abcABC ==(NFC)==> abcABCabcABC ==(NFD)==> abcABCabcABC ==(NFKC)==> abcABCabcABC ==(NFKD)==> abcABC# 1 original form changed or not- A(not changed): NFC & NFD- B(changed): NFKC & NFKD The first classification method is based on whether the original form is changed or not. More specifically, A group does not contain K but B group contains K. What does K means? D = Decomposition C = CompositionK = Compatibility K means compatibility, which is used to distinguish with the original form. Because K changes the original form, so the length is also changed. >>> s= '...'>>> normalize('NFKC', s)'...'>>> len(s)1>>> len(normalize('NFC', s))1>>> len(normalize('NFKC', s))3>>> len(normalize('NFD', s))1>>> len(normalize('NFKD', s))3 パピプペポ ==(NFC)==> パピプペポパピプペポ ==(NFD)==> パピプペポパピプペポ ==(NFKC)==> パピプペポパピプペポ ==(NFKD)==> パピプペポ# 2 the length of original length changed or not- A(not changed): NFC & NFKC- B(changed): NFD & NFKD This second classification method is based on whether the length of the original form is changed or not. A group contains C(Composition), which won’t change the length. B group contains D(Decomposition), which will change the length. You might be wondering why the length is change? Please see the test below. >>> from unicodedata import normalize>>> s = "パピプペポ">>> len(s)5>>> len(normalize('NFC', s))5>>> len(normalize('NFKC', s))5>>> len(normalize('NFD', s))10>>> len(normalize('NFKD', s))10 We can find the “decomposition” method doubles the length. This is because the NFD & NFKD decompose each Unicode character into two Unicode characters. For example, ポ(U+30DD) = ホ(U+30DB) + Dot(U+309A) . So the length change from 5 to 10. NFC & NFKC compose separated Unicode characters together, so the length is not changed. You can use the unicodedata library to get different forms. >>> from unicodedata import normalize>>> s = "パピプペポ">>> len(s)5>>> len(normalize('NFC', s))5>>> len(normalize('NFKC', s))5>>> len(normalize('NFD', s))10>>> len(normalize('NFKD', s))10 Length Usually, we can use either of NFKC or NFKD to get the normalized form. The length won’t make trouble only if your NLP task is length sensitive. I usually use the NFKC method. Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu
[ { "code": null, "e": 376, "s": 172, "text": "Recently I am working on an NLP task in Japanese, one problem is to convert special characters to a normalized form. So I have done a little research and write this post for anyone who has the same need." }, { "code": null, "e": 495, "s": 376, "text": "Japanese contains different forms of the character, for example, Latin has two forms, full-width form, and half-width." }, { "code": null, "e": 668, "s": 495, "text": "In the above example, we can see the full-width form is very ugly and is also hard to utilizing for the following processing. So we need to convert it to a normalized form." }, { "code": null, "e": 685, "s": 668, "text": "Use NFKC method." }, { "code": null, "e": 817, "s": 685, "text": ">>> from unicodedata import normalize>>> s = \"株式会社KADOKAWA Future Publishing\">>> normalize('NFKC', s)株式会社KADOKAWA Future Publishing" }, { "code": null, "e": 990, "s": 817, "text": "There are 4 kinds of Unicode normalization forms. This article give a very detailed explanation. But I will explain the difference with a simple and easy understanding way." }, { "code": null, "e": 1059, "s": 990, "text": "First, we could see the below result for an intuitive understanding." }, { "code": null, "e": 1680, "s": 1059, "text": "アイウエオ ==(NFC)==> アイウエオアイウエオ ==(NFD)==> アイウエオアイウエオ ==(NFKC)==> アイウエオアイウエオ ==(NFKD)==> アイウエオパピプペポ ==(NFC)==> パピプペポパピプペポ ==(NFD)==> パピプペポパピプペポ ==(NFKC)==> パピプペポパピプペポ ==(NFKD)==> パピプペポパピプペポ ==(NFC)==> パピプペポパピプペポ ==(NFD)==> パピプペポパピプペポ ==(NFKC)==> パピプペポパピプペポ ==(NFKD)==> パピプペポabcABC ==(NFC)==> abcABCabcABC ==(NFD)==> abcABCabcABC ==(NFKC)==> abcABCabcABC ==(NFKD)==> abcABC123 ==(NFC)==> 123123 ==(NFD)==> 123123 ==(NFKC)==> 123123 ==(NFKD)==> 123+-.~)} ==(NFC)==> +-.~)}+-.~)} ==(NFD)==> +-.~)}+-.~)} ==(NFKC)==> +-.~)}+-.~)} ==(NFKD)==> +-.~)}" }, { "code": null, "e": 1736, "s": 1680, "text": "There are two classification methods for these 4 forms." }, { "code": null, "e": 1921, "s": 1736, "text": "# 1 original form changed or not- A(not changed): NFC & NFD- B(changed): NFKC & NFKD# 2 the length of original length changed or not- A(not changed): NFC & NFKC- B(changed): NFD & NFKD" }, { "code": null, "e": 2104, "s": 1921, "text": "abcABC ==(NFC)==> abcABCabcABC ==(NFD)==> abcABCabcABC ==(NFKC)==> abcABCabcABC ==(NFKD)==> abcABC# 1 original form changed or not- A(not changed): NFC & NFD- B(changed): NFKC & NFKD" }, { "code": null, "e": 2282, "s": 2104, "text": "The first classification method is based on whether the original form is changed or not. More specifically, A group does not contain K but B group contains K. What does K means?" }, { "code": null, "e": 2333, "s": 2282, "text": "D = Decomposition C = CompositionK = Compatibility" }, { "code": null, "e": 2477, "s": 2333, "text": "K means compatibility, which is used to distinguish with the original form. Because K changes the original form, so the length is also changed." }, { "code": null, "e": 2648, "s": 2477, "text": ">>> s= '...'>>> normalize('NFKC', s)'...'>>> len(s)1>>> len(normalize('NFC', s))1>>> len(normalize('NFKC', s))3>>> len(normalize('NFD', s))1>>> len(normalize('NFKD', s))3" }, { "code": null, "e": 2879, "s": 2648, "text": "パピプペポ ==(NFC)==> パピプペポパピプペポ ==(NFD)==> パピプペポパピプペポ ==(NFKC)==> パピプペポパピプペポ ==(NFKD)==> パピプペポ# 2 the length of original length changed or not- A(not changed): NFC & NFKC- B(changed): NFD & NFKD" }, { "code": null, "e": 3113, "s": 2879, "text": "This second classification method is based on whether the length of the original form is changed or not. A group contains C(Composition), which won’t change the length. B group contains D(Decomposition), which will change the length." }, { "code": null, "e": 3189, "s": 3113, "text": "You might be wondering why the length is change? Please see the test below." }, { "code": null, "e": 3378, "s": 3189, "text": ">>> from unicodedata import normalize>>> s = \"パピプペポ\">>> len(s)5>>> len(normalize('NFC', s))5>>> len(normalize('NFKC', s))5>>> len(normalize('NFD', s))10>>> len(normalize('NFKD', s))10" }, { "code": null, "e": 3437, "s": 3378, "text": "We can find the “decomposition” method doubles the length." }, { "code": null, "e": 3705, "s": 3437, "text": "This is because the NFD & NFKD decompose each Unicode character into two Unicode characters. For example, ポ(U+30DD) = ホ(U+30DB) + Dot(U+309A) . So the length change from 5 to 10. NFC & NFKC compose separated Unicode characters together, so the length is not changed." }, { "code": null, "e": 3765, "s": 3705, "text": "You can use the unicodedata library to get different forms." }, { "code": null, "e": 3954, "s": 3765, "text": ">>> from unicodedata import normalize>>> s = \"パピプペポ\">>> len(s)5>>> len(normalize('NFC', s))5>>> len(normalize('NFKC', s))5>>> len(normalize('NFD', s))10>>> len(normalize('NFKD', s))10" }, { "code": null, "e": 3961, "s": 3954, "text": "Length" }, { "code": null, "e": 4136, "s": 3961, "text": "Usually, we can use either of NFKC or NFKD to get the normalized form. The length won’t make trouble only if your NLP task is length sensitive. I usually use the NFKC method." } ]
Create a Pivot Table with multiple columns – Python Pandas
We can create a Pivot Table with multiple columns. To create a Pivot Table, use the pandas.pivot_table to create a spreadsheet-style pivot table as a DataFrame. At first, import the required library − import pandas as pd Create a DataFrame with Team records − dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}}) Create a Pivot Table with multiple columns. We have set more than more than two columns − pd.pivot_table(dataFrame, index = ["Team ID", "Team Name", "Team Rank"]) Following is the code − import pandas as pd # create DataFrame with Team records dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}}) print("\n... Pivot ...") # multiple columns print(pd.pivot_table(dataFrame, index = ["Team ID", "Team Name", "Team Rank"])) This will produce the following output − ... Pivot ... Team Points Team ID Team Name Team Rank 2 Sri Lanka Three 80 5 India One 95 6 Bangladesh Six 42 7 England Five 55 9 Australia Two 93 11 South Africa Four 60
[ { "code": null, "e": 1223, "s": 1062, "text": "We can create a Pivot Table with multiple columns. To create a Pivot Table, use the pandas.pivot_table to create a spreadsheet-style pivot table as a DataFrame." }, { "code": null, "e": 1263, "s": 1223, "text": "At first, import the required library −" }, { "code": null, "e": 1283, "s": 1263, "text": "import pandas as pd" }, { "code": null, "e": 1322, "s": 1283, "text": "Create a DataFrame with Team records −" }, { "code": null, "e": 1644, "s": 1322, "text": "dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})" }, { "code": null, "e": 1734, "s": 1644, "text": "Create a Pivot Table with multiple columns. We have set more than more than two columns −" }, { "code": null, "e": 1807, "s": 1734, "text": "pd.pivot_table(dataFrame, index = [\"Team ID\", \"Team Name\", \"Team Rank\"])" }, { "code": null, "e": 1831, "s": 1807, "text": "Following is the code −" }, { "code": null, "e": 2337, "s": 1831, "text": "import pandas as pd\n\n# create DataFrame with Team records\ndataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})\n\nprint(\"\\n... Pivot ...\")\n\n# multiple columns\nprint(pd.pivot_table(dataFrame, index = [\"Team ID\", \"Team Name\", \"Team Rank\"]))" }, { "code": null, "e": 2378, "s": 2337, "text": "This will produce the following output −" }, { "code": null, "e": 2746, "s": 2378, "text": "... Pivot ...\n Team Points\nTeam ID Team Name Team Rank\n2 Sri Lanka Three 80\n5 India One 95\n6 Bangladesh Six 42\n7 England Five 55\n9 Australia Two 93\n11 South Africa Four 60" } ]
Machine Learning For Genomics. How to transform your genomics data to... | by Anuradha Wickramarachchi | Towards Data Science
Machine learning has become popular. However, it is not a common use case in the field of Bioinformatics and Computational Biology. There are very few tools that use machine learning techniques. Most of the tools are developed on top of deterministic approaches and algorithms. In this article, I will present how we can arrange our data so that they would be used effectively in a machine learning model. There are many scenarios in genomics that we might use machine learning. The major areas of Clustering and Classification can be used in Genomics for various tasks. A few of them are as follows: Binning of Metagenomics ContigsIdentification of Plasmids and ChromosomesClustering reads into chromosomes for better assemblyClustering of reads as a preprocessor for assembly of reads Binning of Metagenomics Contigs Identification of Plasmids and Chromosomes Clustering reads into chromosomes for better assembly Clustering of reads as a preprocessor for assembly of reads Classifying shorter sequences into classes (phylum, genus, species, etc)Phylogenetic inference of the sequencesDetection of Plasmids and ChromosomesFinding coding regionsChromosome prediction in human genomics Classifying shorter sequences into classes (phylum, genus, species, etc) Phylogenetic inference of the sequences Detection of Plasmids and Chromosomes Finding coding regions Chromosome prediction in human genomics The list could possibly extend a lot further, though I have listed a few areas which I have had the experience in. Out of the two steps, transformation and model selection, I would consider the first to be of higher importance. This is because without a solid base for the data representation we might not get the maximum out of the model. However, having clean and information-rich data could perform reasonably better even if our model seems to be poor. We could consider data under two categories. Sequential Data refers to data where the ordering of the data fed to the model corresponds to the actual order of data in the dataset. Let's have a look at the following example. Prediction of Protein Coding RegionsIn this scenario, we will be looking at consecutive nucleotide bases and their order. Otherwise, it would not make sense. In such a scenario, we could transform data as sentences having consecutive trimer words.Taxonomic Label PredictionIn this scenario, we need to have a higher precision as oligonucleotide frequencies could be very similar among species and have a very low uniqueness between certain species. Therefore, we would be looking at creating k-mer sentences of k values above 5 or 7 as sentences. Prediction of Protein Coding RegionsIn this scenario, we will be looking at consecutive nucleotide bases and their order. Otherwise, it would not make sense. In such a scenario, we could transform data as sentences having consecutive trimer words. Taxonomic Label PredictionIn this scenario, we need to have a higher precision as oligonucleotide frequencies could be very similar among species and have a very low uniqueness between certain species. Therefore, we would be looking at creating k-mer sentences of k values above 5 or 7 as sentences. Let us consider the following example. I will be using the two species Pseudomonas aeruginosa (CP007224.1) and Lactobacillus fermentum (AP008937.1) to demonstrate the transformation into k-mer word sentences (First 50 bases shown). Pseudomonas aeruginosaTTTAAAGAGACCGGCGATTCTAGTGAAATCGAACGGGCAGGTCAATTTCCLactobacillus fermentumTTGACTGAGCTCGATTCTCTTTGGGAAGCGATCCAAAATTCATTCCGTAA Now, we can transform this as trimer words to like the following output. Pseudomonas aeruginosaTTT TTA TAA AAA AAG AGA GAG AGA GAC ACC CCG CGG GGC GCG CGA GAT ATT TTC TCT CTA TAG AGT GTG TGA GAA AAA AAT ATC TCG CGA GAA AAC ACG CGG GGG GGC GCA CAG AGG GGT GTC TCA CAA AAT ATT TTT TTC TCCLactobacillus fermentumTTG TGA GAC ACT CTG TGA GAG AGC GCT CTC TCG CGA GAT ATT TTC TCT CTC TCT CTT TTT TTG TGG GGG GGA GAA AAG AGC GCG CGA GAT ATC TCC CCA CAA AAA AAA AAT ATT TTC TCA CAT ATT TTC TCC CCG CGT GTA TAA Now that we have sentences of words, the processing becomes similar to that of sentiment analysis. The key idea is to preserve the sentence length, which you could decide based on the average length of sequences. Since the order of k-mers matter in the above scenario, we can easily use a Recurrent Neural Network (RNN) or a Long Short Term Memory model (LSTM). This is because of their ability to keep the order of items as a temporal relationship. However, in the above scenario, you must use tokenization followed by a word embedding layer. Be sure to pickle the encoders and tokenizers to a file (serialise) so that you’d have the encoder for predictions later on. Here kmer_strings are the sentences I created and classes are the designated label. tokenizer = Tokenizer()tokenizer.fit_on_texts(kmer_strings)vocab_size = len(tokenizer.word_index) + 1encoded_docs = tokenizer.texts_to_sequences(kmer_strings)binarizer = preprocessing.LabelBinarizer()labels_encoded = binarizer.fit_transform(classes) Following is one model that I used for a sequence classification a few days ago using the Keras Sequential API. I am embedding the words into 5 dimensions from the initial 32 dimensions (there are 32 unique trimers merging the reverse complements to the lower strand). model = Sequential()model.add(Embedding(vocab_size, 5))model.add(Bidirectional(LSTM(5)))model.add(Dense(30, activation = 'relu'))model.add(Dropout(0.2))model.add(Dense(20, activation = 'relu'))model.add(Dropout(0.2))model.add(Dense(2, activation = 'softmax')) If your classification is multi-label, you would need to use sigmoid activation function in-place of the softmax function. For scenarios where relatedness between similar sequences is more important than the unique identifiability of sequences, we tend to use unordered data. These are usually represented in the form of oligonucleotide frequency vectors. For example, the normalized frequencies for Pseudomonas aeruginosa (CP007224.1) and Lactobacillus fermentum (AP008937.1) would look like follows. We can see that they follow drastically different patterns. Note that we have lost the actual order of trimers but left with a representation to identify the two species uniquely. However, at k=3 you are very likely to have collisions between closely related species. This is an interesting article on how to cluster based on these patterns; towardsdatascience.com And the following article might help on how to use DBSCAN pretty effectively. towardsdatascience.com Now that you have seen the data, you could use a model similar to the following to do classification. model = Sequential()model.add(Dense(30, activation = 'relu', input_shape=(32,)))model.add(Dropout(0.2))model.add(Dense(20, activation = 'relu'))model.add(Dropout(0.2))model.add(Dense(2, activation = 'softmax'))model.compile(loss='binary_crossentropy', optimizer='adam') Note that your input dimension will increase in powers of 4 as you decide on longer k-mers for this. Furthermore, it would take a very long time to compute such long vectors too. You might want to read on the following article that explains how to do that using a small script that you can use very easily. medium.com Now that you have seen how one might use genomic sequences of variable lengths in a machine learning model, let me show few tools that actually do this. PlasClass (published 2020, PLOS)Uses logistic regression on k-mer frequency vectors to detect whether they originate from a plasmid sequence or a chromosomal segment. This is a binary classification based tool.PlasFlow (published 2018, Nucleic Acid Research)This tool predicts the phylum level classification and predicts whether a given contig is a plasmid or a chromosome. Uses a neural network on top of k-mer frequency vectors.MetaBCC-LR (published, 2020, Bioinformatics)Uses t-distributed Stochastic Neighbour Embedding (t-SNE) to dimension reduce genomic long reads to perform binning of metagenomic reads’ trimer vectors. PlasClass (published 2020, PLOS)Uses logistic regression on k-mer frequency vectors to detect whether they originate from a plasmid sequence or a chromosomal segment. This is a binary classification based tool. PlasFlow (published 2018, Nucleic Acid Research)This tool predicts the phylum level classification and predicts whether a given contig is a plasmid or a chromosome. Uses a neural network on top of k-mer frequency vectors. MetaBCC-LR (published, 2020, Bioinformatics)Uses t-distributed Stochastic Neighbour Embedding (t-SNE) to dimension reduce genomic long reads to perform binning of metagenomic reads’ trimer vectors. There are many more tools in different areas of research other than these few (which I used and the 3rd one I authored). LSTMs are used in gene prediction and coding region detection. However, there is tremendous potential in the area for machine learning techniques to show off. I hope you had some useful reading. Cheers!
[ { "code": null, "e": 577, "s": 171, "text": "Machine learning has become popular. However, it is not a common use case in the field of Bioinformatics and Computational Biology. There are very few tools that use machine learning techniques. Most of the tools are developed on top of deterministic approaches and algorithms. In this article, I will present how we can arrange our data so that they would be used effectively in a machine learning model." }, { "code": null, "e": 772, "s": 577, "text": "There are many scenarios in genomics that we might use machine learning. The major areas of Clustering and Classification can be used in Genomics for various tasks. A few of them are as follows:" }, { "code": null, "e": 958, "s": 772, "text": "Binning of Metagenomics ContigsIdentification of Plasmids and ChromosomesClustering reads into chromosomes for better assemblyClustering of reads as a preprocessor for assembly of reads" }, { "code": null, "e": 990, "s": 958, "text": "Binning of Metagenomics Contigs" }, { "code": null, "e": 1033, "s": 990, "text": "Identification of Plasmids and Chromosomes" }, { "code": null, "e": 1087, "s": 1033, "text": "Clustering reads into chromosomes for better assembly" }, { "code": null, "e": 1147, "s": 1087, "text": "Clustering of reads as a preprocessor for assembly of reads" }, { "code": null, "e": 1357, "s": 1147, "text": "Classifying shorter sequences into classes (phylum, genus, species, etc)Phylogenetic inference of the sequencesDetection of Plasmids and ChromosomesFinding coding regionsChromosome prediction in human genomics" }, { "code": null, "e": 1430, "s": 1357, "text": "Classifying shorter sequences into classes (phylum, genus, species, etc)" }, { "code": null, "e": 1470, "s": 1430, "text": "Phylogenetic inference of the sequences" }, { "code": null, "e": 1508, "s": 1470, "text": "Detection of Plasmids and Chromosomes" }, { "code": null, "e": 1531, "s": 1508, "text": "Finding coding regions" }, { "code": null, "e": 1571, "s": 1531, "text": "Chromosome prediction in human genomics" }, { "code": null, "e": 1686, "s": 1571, "text": "The list could possibly extend a lot further, though I have listed a few areas which I have had the experience in." }, { "code": null, "e": 2072, "s": 1686, "text": "Out of the two steps, transformation and model selection, I would consider the first to be of higher importance. This is because without a solid base for the data representation we might not get the maximum out of the model. However, having clean and information-rich data could perform reasonably better even if our model seems to be poor. We could consider data under two categories." }, { "code": null, "e": 2251, "s": 2072, "text": "Sequential Data refers to data where the ordering of the data fed to the model corresponds to the actual order of data in the dataset. Let's have a look at the following example." }, { "code": null, "e": 2798, "s": 2251, "text": "Prediction of Protein Coding RegionsIn this scenario, we will be looking at consecutive nucleotide bases and their order. Otherwise, it would not make sense. In such a scenario, we could transform data as sentences having consecutive trimer words.Taxonomic Label PredictionIn this scenario, we need to have a higher precision as oligonucleotide frequencies could be very similar among species and have a very low uniqueness between certain species. Therefore, we would be looking at creating k-mer sentences of k values above 5 or 7 as sentences." }, { "code": null, "e": 3046, "s": 2798, "text": "Prediction of Protein Coding RegionsIn this scenario, we will be looking at consecutive nucleotide bases and their order. Otherwise, it would not make sense. In such a scenario, we could transform data as sentences having consecutive trimer words." }, { "code": null, "e": 3346, "s": 3046, "text": "Taxonomic Label PredictionIn this scenario, we need to have a higher precision as oligonucleotide frequencies could be very similar among species and have a very low uniqueness between certain species. Therefore, we would be looking at creating k-mer sentences of k values above 5 or 7 as sentences." }, { "code": null, "e": 3578, "s": 3346, "text": "Let us consider the following example. I will be using the two species Pseudomonas aeruginosa (CP007224.1) and Lactobacillus fermentum (AP008937.1) to demonstrate the transformation into k-mer word sentences (First 50 bases shown)." }, { "code": null, "e": 3724, "s": 3578, "text": "Pseudomonas aeruginosaTTTAAAGAGACCGGCGATTCTAGTGAAATCGAACGGGCAGGTCAATTTCCLactobacillus fermentumTTGACTGAGCTCGATTCTCTTTGGGAAGCGATCCAAAATTCATTCCGTAA" }, { "code": null, "e": 3797, "s": 3724, "text": "Now, we can transform this as trimer words to like the following output." }, { "code": null, "e": 4225, "s": 3797, "text": "Pseudomonas aeruginosaTTT TTA TAA AAA AAG AGA GAG AGA GAC ACC CCG CGG GGC GCG CGA GAT ATT TTC TCT CTA TAG AGT GTG TGA GAA AAA AAT ATC TCG CGA GAA AAC ACG CGG GGG GGC GCA CAG AGG GGT GTC TCA CAA AAT ATT TTT TTC TCCLactobacillus fermentumTTG TGA GAC ACT CTG TGA GAG AGC GCT CTC TCG CGA GAT ATT TTC TCT CTC TCT CTT TTT TTG TGG GGG GGA GAA AAG AGC GCG CGA GAT ATC TCC CCA CAA AAA AAA AAT ATT TTC TCA CAT ATT TTC TCC CCG CGT GTA TAA" }, { "code": null, "e": 4438, "s": 4225, "text": "Now that we have sentences of words, the processing becomes similar to that of sentiment analysis. The key idea is to preserve the sentence length, which you could decide based on the average length of sequences." }, { "code": null, "e": 4675, "s": 4438, "text": "Since the order of k-mers matter in the above scenario, we can easily use a Recurrent Neural Network (RNN) or a Long Short Term Memory model (LSTM). This is because of their ability to keep the order of items as a temporal relationship." }, { "code": null, "e": 4978, "s": 4675, "text": "However, in the above scenario, you must use tokenization followed by a word embedding layer. Be sure to pickle the encoders and tokenizers to a file (serialise) so that you’d have the encoder for predictions later on. Here kmer_strings are the sentences I created and classes are the designated label." }, { "code": null, "e": 5228, "s": 4978, "text": "tokenizer = Tokenizer()tokenizer.fit_on_texts(kmer_strings)vocab_size = len(tokenizer.word_index) + 1encoded_docs = tokenizer.texts_to_sequences(kmer_strings)binarizer = preprocessing.LabelBinarizer()labels_encoded = binarizer.fit_transform(classes)" }, { "code": null, "e": 5497, "s": 5228, "text": "Following is one model that I used for a sequence classification a few days ago using the Keras Sequential API. I am embedding the words into 5 dimensions from the initial 32 dimensions (there are 32 unique trimers merging the reverse complements to the lower strand)." }, { "code": null, "e": 5757, "s": 5497, "text": "model = Sequential()model.add(Embedding(vocab_size, 5))model.add(Bidirectional(LSTM(5)))model.add(Dense(30, activation = 'relu'))model.add(Dropout(0.2))model.add(Dense(20, activation = 'relu'))model.add(Dropout(0.2))model.add(Dense(2, activation = 'softmax'))" }, { "code": null, "e": 5880, "s": 5757, "text": "If your classification is multi-label, you would need to use sigmoid activation function in-place of the softmax function." }, { "code": null, "e": 6259, "s": 5880, "text": "For scenarios where relatedness between similar sequences is more important than the unique identifiability of sequences, we tend to use unordered data. These are usually represented in the form of oligonucleotide frequency vectors. For example, the normalized frequencies for Pseudomonas aeruginosa (CP007224.1) and Lactobacillus fermentum (AP008937.1) would look like follows." }, { "code": null, "e": 6601, "s": 6259, "text": "We can see that they follow drastically different patterns. Note that we have lost the actual order of trimers but left with a representation to identify the two species uniquely. However, at k=3 you are very likely to have collisions between closely related species. This is an interesting article on how to cluster based on these patterns;" }, { "code": null, "e": 6624, "s": 6601, "text": "towardsdatascience.com" }, { "code": null, "e": 6702, "s": 6624, "text": "And the following article might help on how to use DBSCAN pretty effectively." }, { "code": null, "e": 6725, "s": 6702, "text": "towardsdatascience.com" }, { "code": null, "e": 6827, "s": 6725, "text": "Now that you have seen the data, you could use a model similar to the following to do classification." }, { "code": null, "e": 7097, "s": 6827, "text": "model = Sequential()model.add(Dense(30, activation = 'relu', input_shape=(32,)))model.add(Dropout(0.2))model.add(Dense(20, activation = 'relu'))model.add(Dropout(0.2))model.add(Dense(2, activation = 'softmax'))model.compile(loss='binary_crossentropy', optimizer='adam')" }, { "code": null, "e": 7404, "s": 7097, "text": "Note that your input dimension will increase in powers of 4 as you decide on longer k-mers for this. Furthermore, it would take a very long time to compute such long vectors too. You might want to read on the following article that explains how to do that using a small script that you can use very easily." }, { "code": null, "e": 7415, "s": 7404, "text": "medium.com" }, { "code": null, "e": 7568, "s": 7415, "text": "Now that you have seen how one might use genomic sequences of variable lengths in a machine learning model, let me show few tools that actually do this." }, { "code": null, "e": 8197, "s": 7568, "text": "PlasClass (published 2020, PLOS)Uses logistic regression on k-mer frequency vectors to detect whether they originate from a plasmid sequence or a chromosomal segment. This is a binary classification based tool.PlasFlow (published 2018, Nucleic Acid Research)This tool predicts the phylum level classification and predicts whether a given contig is a plasmid or a chromosome. Uses a neural network on top of k-mer frequency vectors.MetaBCC-LR (published, 2020, Bioinformatics)Uses t-distributed Stochastic Neighbour Embedding (t-SNE) to dimension reduce genomic long reads to perform binning of metagenomic reads’ trimer vectors." }, { "code": null, "e": 8408, "s": 8197, "text": "PlasClass (published 2020, PLOS)Uses logistic regression on k-mer frequency vectors to detect whether they originate from a plasmid sequence or a chromosomal segment. This is a binary classification based tool." }, { "code": null, "e": 8630, "s": 8408, "text": "PlasFlow (published 2018, Nucleic Acid Research)This tool predicts the phylum level classification and predicts whether a given contig is a plasmid or a chromosome. Uses a neural network on top of k-mer frequency vectors." }, { "code": null, "e": 8828, "s": 8630, "text": "MetaBCC-LR (published, 2020, Bioinformatics)Uses t-distributed Stochastic Neighbour Embedding (t-SNE) to dimension reduce genomic long reads to perform binning of metagenomic reads’ trimer vectors." }, { "code": null, "e": 9012, "s": 8828, "text": "There are many more tools in different areas of research other than these few (which I used and the 3rd one I authored). LSTMs are used in gene prediction and coding region detection." }, { "code": null, "e": 9108, "s": 9012, "text": "However, there is tremendous potential in the area for machine learning techniques to show off." } ]
Pygame - surface.blit() function - GeeksforGeeks
23 May, 2021 surface.blit() function draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not affect the blit. Syntax : blit(source, dest, area=None, special_flags=0) -> Rect Parameters: Source – Draws a source Surface onto this Surface dest – The draw can be positioned with the dest argument. area -A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit Python3 # import pygame moduleimport pygame pygame.init() # widthwidth = 680 # heightheight = 480 #store he screen sizez = [width,height] # store the colorwhite = (255, 255, 255)screen_display = pygame.display # Set caption of screenscreen_display.set_caption('GEEKSFORGEEKS') # setting the size of the windowsurface = screen_display.set_mode(z) # set the image which to be displayed on screenpython = pygame.image.load('bg.jpg') # set window truewindow = Truewhile window: for event in pygame.event.get(): if event.type == pygame.QUIT: window = False # display white on screen other than image surface.fill(white) # draw on image onto another surface.blit(python,(50, 50)) screen_display.update() pygame.quit() Output: Picked Python-PyGame 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 Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n23 May, 2021" }, { "code": null, "e": 25958, "s": 25561, "text": "surface.blit() function draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not affect the blit." }, { "code": null, "e": 26022, "s": 25958, "text": "Syntax : blit(source, dest, area=None, special_flags=0) -> Rect" }, { "code": null, "e": 26034, "s": 26022, "text": "Parameters:" }, { "code": null, "e": 26084, "s": 26034, "text": "Source – Draws a source Surface onto this Surface" }, { "code": null, "e": 26142, "s": 26084, "text": "dest – The draw can be positioned with the dest argument." }, { "code": null, "e": 26275, "s": 26142, "text": "area -A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit" }, { "code": null, "e": 26283, "s": 26275, "text": "Python3" }, { "code": "# import pygame moduleimport pygame pygame.init() # widthwidth = 680 # heightheight = 480 #store he screen sizez = [width,height] # store the colorwhite = (255, 255, 255)screen_display = pygame.display # Set caption of screenscreen_display.set_caption('GEEKSFORGEEKS') # setting the size of the windowsurface = screen_display.set_mode(z) # set the image which to be displayed on screenpython = pygame.image.load('bg.jpg') # set window truewindow = Truewhile window: for event in pygame.event.get(): if event.type == pygame.QUIT: window = False # display white on screen other than image surface.fill(white) # draw on image onto another surface.blit(python,(50, 50)) screen_display.update() pygame.quit()", "e": 27058, "s": 26283, "text": null }, { "code": null, "e": 27066, "s": 27058, "text": "Output:" }, { "code": null, "e": 27073, "s": 27066, "text": "Picked" }, { "code": null, "e": 27087, "s": 27073, "text": "Python-PyGame" }, { "code": null, "e": 27094, "s": 27087, "text": "Python" }, { "code": null, "e": 27192, "s": 27094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27224, "s": 27192, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27266, "s": 27224, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27308, "s": 27266, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27335, "s": 27308, "text": "Python Classes and Objects" }, { "code": null, "e": 27391, "s": 27335, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27413, "s": 27391, "text": "Defaultdict in Python" }, { "code": null, "e": 27452, "s": 27413, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27483, "s": 27452, "text": "Python | os.path.join() method" }, { "code": null, "e": 27512, "s": 27483, "text": "Create a directory in Python" } ]
Node.js Automatic restart Node.js server with nodemon - GeeksforGeeks
14 Oct, 2021 We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this restart process automatically when changes occur in the project file. Installing nodemon: nodemon should be installed globally in our system: Windows system: npm i nodemon -g Linux system: sudo npm i nodemon -g Now, let’s check that nodemon has been installed properly to the system by typing the following command in terminal or command prompt: nodemon -v It will show the version of nodemon as shown in the below screenshot. Starting node server with nodemon: nodemon [Your node application] Now, when we make changes to our nodejs application, the server automatically restarts by nodemon as shown in the below screenshot. In this way with nodemon server automatically restarts. JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js
[ { "code": null, "e": 26287, "s": 26259, "text": "\n14 Oct, 2021" }, { "code": null, "e": 26351, "s": 26287, "text": "We generally type following command for starting NodeJs server:" }, { "code": null, "e": 26366, "s": 26351, "text": "node server.js" }, { "code": null, "e": 26525, "s": 26366, "text": "In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again." }, { "code": null, "e": 26540, "s": 26525, "text": "node server.js" }, { "code": null, "e": 26594, "s": 26540, "text": "It is a very hectic task for the development process." }, { "code": null, "e": 26703, "s": 26594, "text": "Nodemon is a package for handling this restart process automatically when changes occur in the project file." }, { "code": null, "e": 26775, "s": 26703, "text": "Installing nodemon: nodemon should be installed globally in our system:" }, { "code": null, "e": 26846, "s": 26775, "text": "Windows system: npm i nodemon -g\nLinux system: sudo npm i nodemon -g \n" }, { "code": null, "e": 26981, "s": 26846, "text": "Now, let’s check that nodemon has been installed properly to the system by typing the following command in terminal or command prompt:" }, { "code": null, "e": 26992, "s": 26981, "text": "nodemon -v" }, { "code": null, "e": 27062, "s": 26992, "text": "It will show the version of nodemon as shown in the below screenshot." }, { "code": null, "e": 27097, "s": 27062, "text": "Starting node server with nodemon:" }, { "code": null, "e": 27129, "s": 27097, "text": "nodemon [Your node application]" }, { "code": null, "e": 27261, "s": 27129, "text": "Now, when we make changes to our nodejs application, the server automatically restarts by nodemon as shown in the below screenshot." }, { "code": null, "e": 27317, "s": 27261, "text": "In this way with nodemon server automatically restarts." }, { "code": null, "e": 27328, "s": 27317, "text": "JavaScript" }, { "code": null, "e": 27336, "s": 27328, "text": "Node.js" }, { "code": null, "e": 27353, "s": 27336, "text": "Web Technologies" }, { "code": null, "e": 27451, "s": 27353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27491, "s": 27451, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27536, "s": 27491, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27597, "s": 27536, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27669, "s": 27597, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27715, "s": 27669, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27748, "s": 27715, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27778, "s": 27748, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27807, "s": 27778, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27864, "s": 27807, "text": "How to install the previous version of node.js and npm ?" } ]
pthread_self() in C with Example - GeeksforGeeks
28 Oct, 2019 Prerequisite : Multithreading in C Syntax :- pthread_t pthread_self(void);The pthread_self() function returns the ID of the thread in which it is invoked. // C program to demonstrate working of pthread_self()#include <stdio.h>#include <stdlib.h>#include <pthread.h>void* calls(void* ptr){ // using pthread_self() get current thread id printf("In function \nthread id = %d\n", pthread_self()); pthread_exit(NULL); return NULL;} int main(){ pthread_t thread; // declare thread pthread_create(&thread, NULL, calls, NULL); printf("In main \nthread id = %d\n", thread); pthread_join(thread, NULL); return 0;} Output: In function thread id = 1 In main thread id = 1 This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. shubham_singh C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ Different methods to reverse a string in C/C++ Structures in C Exception Handling in C++ Memory Layout of C Programs
[ { "code": null, "e": 25893, "s": 25865, "text": "\n28 Oct, 2019" }, { "code": null, "e": 25928, "s": 25893, "text": "Prerequisite : Multithreading in C" }, { "code": null, "e": 26048, "s": 25928, "text": "Syntax :- pthread_t pthread_self(void);The pthread_self() function returns the ID of the thread in which it is invoked." }, { "code": "// C program to demonstrate working of pthread_self()#include <stdio.h>#include <stdlib.h>#include <pthread.h>void* calls(void* ptr){ // using pthread_self() get current thread id printf(\"In function \\nthread id = %d\\n\", pthread_self()); pthread_exit(NULL); return NULL;} int main(){ pthread_t thread; // declare thread pthread_create(&thread, NULL, calls, NULL); printf(\"In main \\nthread id = %d\\n\", thread); pthread_join(thread, NULL); return 0;}", "e": 26527, "s": 26048, "text": null }, { "code": null, "e": 26535, "s": 26527, "text": "Output:" }, { "code": null, "e": 26584, "s": 26535, "text": "In function\nthread id = 1\nIn main\nthread id = 1\n" }, { "code": null, "e": 26888, "s": 26584, "text": "This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27013, "s": 26888, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27027, "s": 27013, "text": "shubham_singh" }, { "code": null, "e": 27038, "s": 27027, "text": "C Language" }, { "code": null, "e": 27136, "s": 27038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27158, "s": 27136, "text": "Function Pointer in C" }, { "code": null, "e": 27175, "s": 27158, "text": "Substring in C++" }, { "code": null, "e": 27187, "s": 27175, "text": "fork() in C" }, { "code": null, "e": 27212, "s": 27187, "text": "std::string class in C++" }, { "code": null, "e": 27239, "s": 27212, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 27271, "s": 27239, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27318, "s": 27271, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 27334, "s": 27318, "text": "Structures in C" }, { "code": null, "e": 27360, "s": 27334, "text": "Exception Handling in C++" } ]
Introduction to Iterators in C++ - GeeksforGeeks
28 Apr, 2022 An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them. Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of an iterator is a pointer. A pointer can point to elements in an array and can iterate through them using the increment operator (++). But, all iterators do not have similar functionality as that of pointers. Depending upon the functionality of iterators they can be classified into five categories, as shown in the diagram below with the outer one being the most powerful one and consequently the inner one is the least powerful in terms of functionality. Now each one of these iterators are not supported by all the containers in STL, different containers support different iterators, like vectors support Random-access iterators, while lists support bidirectional iterators. The whole list is as given below: Types of iterators: Based upon the functionality of the iterators, they can be classified into five major categories: Input Iterators: They are the weakest of all the iterators and have very limited functionality. They can only be used in a single-pass algorithms, i.e., those algorithms which process the container sequentially, such that no element is accessed more than once.Output Iterators: Just like input iterators, they are also very limited in their functionality and can only be used in single-pass algorithm, but not for accessing elements, but for being assigned elements.Forward Iterator: They are higher in the hierarchy than input and output iterators, and contain all the features present in these two iterators. But, as the name suggests, they also can only move in a forward direction and that too one step at a time.Bidirectional Iterators: They have all the features of forward iterators along with the fact that they overcome the drawback of forward iterators, as they can move in both the directions, that is why their name is bidirectional.Random-Access Iterators: They are the most powerful iterators. They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container. They are the ones whose functionality are same as pointers. Input Iterators: They are the weakest of all the iterators and have very limited functionality. They can only be used in a single-pass algorithms, i.e., those algorithms which process the container sequentially, such that no element is accessed more than once. Output Iterators: Just like input iterators, they are also very limited in their functionality and can only be used in single-pass algorithm, but not for accessing elements, but for being assigned elements. Forward Iterator: They are higher in the hierarchy than input and output iterators, and contain all the features present in these two iterators. But, as the name suggests, they also can only move in a forward direction and that too one step at a time. Bidirectional Iterators: They have all the features of forward iterators along with the fact that they overcome the drawback of forward iterators, as they can move in both the directions, that is why their name is bidirectional. Random-Access Iterators: They are the most powerful iterators. They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container. They are the ones whose functionality are same as pointers. The following diagram shows the difference in their functionality with respect to various operations that they can perform. Benefits of Iterators There are certainly quite a few ways which show that iterators are extremely useful to us and encourage us to use it profoundly. Some of the benefits of using iterators are as listed below: Convenience in programming: It is better to use iterators to iterate through the contents of containers as if we will not use an iterator and access elements using [ ] operator, then we need to be always worried about the size of the container, whereas with iterators we can simply use member function end() and iterate through the contents without having to keep anything in mind. CPP // C++ program to demonstrate iterators #include <iostream>#include <vector>using namespace std;int main(){ // Declaring a vector vector<int> v = { 1, 2, 3 }; // Declaring an iterator vector<int>::iterator i; int j; cout << "Without iterators = "; // Accessing the elements without using iterators for (j = 0; j < 3; ++j) { cout << v[j] << " "; } cout << "\nWith iterators = "; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << " "; } // Adding one more element to vector v.push_back(4); cout << "\nWithout iterators = "; // Accessing the elements without using iterators for (j = 0; j < 4; ++j) { cout << v[j] << " "; } cout << "\nWith iterators = "; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << " "; } return 0;} Output: Without iterators = 1 2 3 With iterators = 1 2 3 Without iterators = 1 2 3 4 With iterators = 1 2 3 4 Explanation: As can be seen in the above code that without using iterators we need to keep track of the total elements in the container. In the beginning there were only three elements, but after one more element was inserted into it, accordingly the for loop also had to be amended, but using iterators, both the time the for loop remained the same. So, iterator eased our task. Code reusability: Now consider if we make v a list in place of vector in the above program and if we were not using iterators to access the elements and only using [ ] operator, then in that case this way of accessing was of no use for list (as they don’t support random-access iterators). However, if we were using iterators for vectors to access the elements, then just changing the vector to list in the declaration of the iterator would have served the purpose, without doing anything else So, iterators support reusability of code, as they can be used to access elements of any container. Dynamic processing of the container: Iterators provide us the ability to dynamically add or remove elements from the container as and when we want with ease. CPP // C++ program to demonstrate iterators #include <iostream>#include <vector>using namespace std;int main(){ // Declaring a vector vector<int> v = { 1, 2, 3 }; // Declaring an iterator vector<int>::iterator i; int j; // Inserting element using iterators for (i = v.begin(); i != v.end(); ++i) { if (i == v.begin()) { i = v.insert(i, 5); // inserting 5 at the beginning of v } } // v contains 5 1 2 3 // Deleting a element using iterators for (i = v.begin(); i != v.end(); ++i) { if (i == v.begin() + 1) { i = v.erase(i); // i now points to the element after the // deleted element } } // v contains 5 2 3 // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << " "; } return 0;} Output: 5 2 3 Explanation: As seen in the above code, we can easily and dynamically add and remove elements from the container using iterator, however, doing the same without using them would have been very tedious as it would require shifting the elements every time before insertion and after deletion. This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. 19bcs1298 simmytarika5 cpp-iterator STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++ Copy Constructor in C++ Substring in C++ Polymorphism in C++
[ { "code": null, "e": 25623, "s": 25595, "text": "\n28 Apr, 2022" }, { "code": null, "e": 26552, "s": 25623, "text": "An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them. Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of an iterator is a pointer. A pointer can point to elements in an array and can iterate through them using the increment operator (++). But, all iterators do not have similar functionality as that of pointers. Depending upon the functionality of iterators they can be classified into five categories, as shown in the diagram below with the outer one being the most powerful one and consequently the inner one is the least powerful in terms of functionality." }, { "code": null, "e": 26929, "s": 26555, "text": "Now each one of these iterators are not supported by all the containers in STL, different containers support different iterators, like vectors support Random-access iterators, while lists support bidirectional iterators. The whole list is as given below: Types of iterators: Based upon the functionality of the iterators, they can be classified into five major categories:" }, { "code": null, "e": 28125, "s": 26929, "text": "Input Iterators: They are the weakest of all the iterators and have very limited functionality. They can only be used in a single-pass algorithms, i.e., those algorithms which process the container sequentially, such that no element is accessed more than once.Output Iterators: Just like input iterators, they are also very limited in their functionality and can only be used in single-pass algorithm, but not for accessing elements, but for being assigned elements.Forward Iterator: They are higher in the hierarchy than input and output iterators, and contain all the features present in these two iterators. But, as the name suggests, they also can only move in a forward direction and that too one step at a time.Bidirectional Iterators: They have all the features of forward iterators along with the fact that they overcome the drawback of forward iterators, as they can move in both the directions, that is why their name is bidirectional.Random-Access Iterators: They are the most powerful iterators. They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container. They are the ones whose functionality are same as pointers." }, { "code": null, "e": 28386, "s": 28125, "text": "Input Iterators: They are the weakest of all the iterators and have very limited functionality. They can only be used in a single-pass algorithms, i.e., those algorithms which process the container sequentially, such that no element is accessed more than once." }, { "code": null, "e": 28593, "s": 28386, "text": "Output Iterators: Just like input iterators, they are also very limited in their functionality and can only be used in single-pass algorithm, but not for accessing elements, but for being assigned elements." }, { "code": null, "e": 28845, "s": 28593, "text": "Forward Iterator: They are higher in the hierarchy than input and output iterators, and contain all the features present in these two iterators. But, as the name suggests, they also can only move in a forward direction and that too one step at a time." }, { "code": null, "e": 29074, "s": 28845, "text": "Bidirectional Iterators: They have all the features of forward iterators along with the fact that they overcome the drawback of forward iterators, as they can move in both the directions, that is why their name is bidirectional." }, { "code": null, "e": 29325, "s": 29074, "text": "Random-Access Iterators: They are the most powerful iterators. They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container. They are the ones whose functionality are same as pointers." }, { "code": null, "e": 29450, "s": 29325, "text": "The following diagram shows the difference in their functionality with respect to various operations that they can perform. " }, { "code": null, "e": 29472, "s": 29450, "text": "Benefits of Iterators" }, { "code": null, "e": 29662, "s": 29472, "text": "There are certainly quite a few ways which show that iterators are extremely useful to us and encourage us to use it profoundly. Some of the benefits of using iterators are as listed below:" }, { "code": null, "e": 30045, "s": 29662, "text": "Convenience in programming: It is better to use iterators to iterate through the contents of containers as if we will not use an iterator and access elements using [ ] operator, then we need to be always worried about the size of the container, whereas with iterators we can simply use member function end() and iterate through the contents without having to keep anything in mind. " }, { "code": null, "e": 30049, "s": 30045, "text": "CPP" }, { "code": "// C++ program to demonstrate iterators #include <iostream>#include <vector>using namespace std;int main(){ // Declaring a vector vector<int> v = { 1, 2, 3 }; // Declaring an iterator vector<int>::iterator i; int j; cout << \"Without iterators = \"; // Accessing the elements without using iterators for (j = 0; j < 3; ++j) { cout << v[j] << \" \"; } cout << \"\\nWith iterators = \"; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << \" \"; } // Adding one more element to vector v.push_back(4); cout << \"\\nWithout iterators = \"; // Accessing the elements without using iterators for (j = 0; j < 4; ++j) { cout << v[j] << \" \"; } cout << \"\\nWith iterators = \"; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << \" \"; } return 0;}", "e": 31003, "s": 30049, "text": null }, { "code": null, "e": 31011, "s": 31003, "text": "Output:" }, { "code": null, "e": 31113, "s": 31011, "text": "Without iterators = 1 2 3\nWith iterators = 1 2 3\nWithout iterators = 1 2 3 4\nWith iterators = 1 2 3 4" }, { "code": null, "e": 31493, "s": 31113, "text": "Explanation: As can be seen in the above code that without using iterators we need to keep track of the total elements in the container. In the beginning there were only three elements, but after one more element was inserted into it, accordingly the for loop also had to be amended, but using iterators, both the time the for loop remained the same. So, iterator eased our task." }, { "code": null, "e": 32087, "s": 31493, "text": "Code reusability: Now consider if we make v a list in place of vector in the above program and if we were not using iterators to access the elements and only using [ ] operator, then in that case this way of accessing was of no use for list (as they don’t support random-access iterators). However, if we were using iterators for vectors to access the elements, then just changing the vector to list in the declaration of the iterator would have served the purpose, without doing anything else So, iterators support reusability of code, as they can be used to access elements of any container." }, { "code": null, "e": 32246, "s": 32087, "text": "Dynamic processing of the container: Iterators provide us the ability to dynamically add or remove elements from the container as and when we want with ease. " }, { "code": null, "e": 32250, "s": 32246, "text": "CPP" }, { "code": "// C++ program to demonstrate iterators #include <iostream>#include <vector>using namespace std;int main(){ // Declaring a vector vector<int> v = { 1, 2, 3 }; // Declaring an iterator vector<int>::iterator i; int j; // Inserting element using iterators for (i = v.begin(); i != v.end(); ++i) { if (i == v.begin()) { i = v.insert(i, 5); // inserting 5 at the beginning of v } } // v contains 5 1 2 3 // Deleting a element using iterators for (i = v.begin(); i != v.end(); ++i) { if (i == v.begin() + 1) { i = v.erase(i); // i now points to the element after the // deleted element } } // v contains 5 2 3 // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << \" \"; } return 0;}", "e": 33126, "s": 32250, "text": null }, { "code": null, "e": 33134, "s": 33126, "text": "Output:" }, { "code": null, "e": 33140, "s": 33134, "text": "5 2 3" }, { "code": null, "e": 33431, "s": 33140, "text": "Explanation: As seen in the above code, we can easily and dynamically add and remove elements from the container using iterator, however, doing the same without using them would have been very tedious as it would require shifting the elements every time before insertion and after deletion." }, { "code": null, "e": 33855, "s": 33431, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 33865, "s": 33855, "text": "19bcs1298" }, { "code": null, "e": 33878, "s": 33865, "text": "simmytarika5" }, { "code": null, "e": 33891, "s": 33878, "text": "cpp-iterator" }, { "code": null, "e": 33895, "s": 33891, "text": "STL" }, { "code": null, "e": 33899, "s": 33895, "text": "C++" }, { "code": null, "e": 33903, "s": 33899, "text": "STL" }, { "code": null, "e": 33907, "s": 33903, "text": "CPP" }, { "code": null, "e": 34005, "s": 33907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34029, "s": 34005, "text": "C++ Classes and Objects" }, { "code": null, "e": 34053, "s": 34029, "text": "Virtual Function in C++" }, { "code": null, "e": 34084, "s": 34053, "text": "Templates in C++ with Examples" }, { "code": null, "e": 34104, "s": 34084, "text": "Constructors in C++" }, { "code": null, "e": 34132, "s": 34104, "text": "Operator Overloading in C++" }, { "code": null, "e": 34160, "s": 34132, "text": "Socket Programming in C/C++" }, { "code": null, "e": 34195, "s": 34160, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 34219, "s": 34195, "text": "Copy Constructor in C++" }, { "code": null, "e": 34236, "s": 34219, "text": "Substring in C++" } ]
StringBuffer reverse() Method in Java with Examples - GeeksforGeeks
13 Dec, 2021 The Java.lang.StringBuffer.reverse() is an inbuilt method which is used to reverse the characters in the StringBuffer. The method causes this character sequence to be replaced by the reverse of the sequence. Syntax : public StringBuffer reverse() Parameters : The method does not take any parameter .Return Value : The method returns the StringBuffer after reversing the characters. Examples : Input: StringBuffer = GeeksforGeeks Output = !skeegrofskeeG Input: StringBuffer = Hello World Output = !dlroW olleH Below programs illustrate the java.lang.StringBuffer.reverse() method: Program 1: java // Java program to illustrate the// java.lang.StringBuffer.reverse()import java.lang.*; public class Test { public static void main(String args[]) { StringBuffer sbf = new StringBuffer("Geeksforgeeks!"); System.out.println("String buffer = " + sbf); // Here it reverses the string buffer sbf.reverse(); System.out.println("String buffer after reversing = " + sbf); }} String buffer = Geeksforgeeks! String buffer after reversing = !skeegrofskeeG Program 2: java // Java program to illustrate the// java.lang.StringBuffer.reverse()import java.lang.*; public class Test { public static void main(String args[]) { StringBuffer sbf = new StringBuffer("1 2 3 4 5 6 7 8 9 10"); System.out.println("String buffer = " + sbf); // Here it reverses the string buffer sbf.reverse(); System.out.println("String buffer after reversing = " + sbf); }} String buffer = 1 2 3 4 5 6 7 8 9 10 String buffer after reversing = 01 9 8 7 6 5 4 3 2 1 akshaysingh98088 Java-Functions Java-lang package java-StringBuffer Java-Strings Java Java-Strings 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 Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25754, "s": 25726, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25972, "s": 25754, "text": "The Java.lang.StringBuffer.reverse() is an inbuilt method which is used to reverse the characters in the StringBuffer. The method causes this character sequence to be replaced by the reverse of the sequence. Syntax : " }, { "code": null, "e": 26002, "s": 25972, "text": "public StringBuffer reverse()" }, { "code": null, "e": 26151, "s": 26002, "text": "Parameters : The method does not take any parameter .Return Value : The method returns the StringBuffer after reversing the characters. Examples : " }, { "code": null, "e": 26268, "s": 26151, "text": "Input: StringBuffer = GeeksforGeeks\nOutput = !skeegrofskeeG\n\nInput: StringBuffer = Hello World\nOutput = !dlroW olleH" }, { "code": null, "e": 26352, "s": 26268, "text": "Below programs illustrate the java.lang.StringBuffer.reverse() method: Program 1: " }, { "code": null, "e": 26357, "s": 26352, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.StringBuffer.reverse()import java.lang.*; public class Test { public static void main(String args[]) { StringBuffer sbf = new StringBuffer(\"Geeksforgeeks!\"); System.out.println(\"String buffer = \" + sbf); // Here it reverses the string buffer sbf.reverse(); System.out.println(\"String buffer after reversing = \" + sbf); }}", "e": 26779, "s": 26357, "text": null }, { "code": null, "e": 26857, "s": 26779, "text": "String buffer = Geeksforgeeks!\nString buffer after reversing = !skeegrofskeeG" }, { "code": null, "e": 26871, "s": 26859, "text": "Program 2: " }, { "code": null, "e": 26876, "s": 26871, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.StringBuffer.reverse()import java.lang.*; public class Test { public static void main(String args[]) { StringBuffer sbf = new StringBuffer(\"1 2 3 4 5 6 7 8 9 10\"); System.out.println(\"String buffer = \" + sbf); // Here it reverses the string buffer sbf.reverse(); System.out.println(\"String buffer after reversing = \" + sbf); }}", "e": 27297, "s": 26876, "text": null }, { "code": null, "e": 27388, "s": 27297, "text": "String buffer = 1 2 3 4 5 6 7 8 9 10\nString buffer after reversing = 01 9 8 7 6 5 4 3 2 1" }, { "code": null, "e": 27407, "s": 27390, "text": "akshaysingh98088" }, { "code": null, "e": 27422, "s": 27407, "text": "Java-Functions" }, { "code": null, "e": 27440, "s": 27422, "text": "Java-lang package" }, { "code": null, "e": 27458, "s": 27440, "text": "java-StringBuffer" }, { "code": null, "e": 27471, "s": 27458, "text": "Java-Strings" }, { "code": null, "e": 27476, "s": 27471, "text": "Java" }, { "code": null, "e": 27489, "s": 27476, "text": "Java-Strings" }, { "code": null, "e": 27494, "s": 27489, "text": "Java" }, { "code": null, "e": 27592, "s": 27494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27643, "s": 27592, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27673, "s": 27643, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27688, "s": 27673, "text": "Stream In Java" }, { "code": null, "e": 27707, "s": 27688, "text": "Interfaces in Java" }, { "code": null, "e": 27738, "s": 27707, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27756, "s": 27738, "text": "ArrayList in Java" }, { "code": null, "e": 27788, "s": 27756, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27808, "s": 27788, "text": "Stack Class in Java" }, { "code": null, "e": 27832, "s": 27808, "text": "Singleton Class in Java" } ]
Node.js os.totalmem() Method - GeeksforGeeks
13 Oct, 2021 The os.totalmem() method is an inbuilt application programming interface of the os module which is used to get amount of total system memory in bytes. Syntax: os.totalmem() Parameters: This method does not accept any parameters. Return Value: This method returns an integer value that specifies the amount of total system memory in bytes. Below examples illustrate the use of os.totalmem() method in Node.js: Example 1: // Node.js program to demonstrate the // os.totalmem() method // Import the os moduleconst os = require('os'); // Printing os.totalmem() method valueconsole.log(os.totalmem()); Output: 8502722560 Example 2: // Node.js program to demonstrate the // os.totalmem() method // Import the os moduleconst os = require('os'); // Convert total memory to kb, mb and gbvar total_memory = os.totalmem();var total_mem_in_kb = total_memory/1024;var total_mem_in_mb = total_mem_in_kb/1024;var total_mem_in_gb = total_mem_in_mb/1024; total_mem_in_kb = Math.floor(total_mem_in_kb);total_mem_in_mb = Math.floor(total_mem_in_mb);total_mem_in_gb = Math.floor(total_mem_in_gb); total_mem_in_mb = total_mem_in_mb%1024;total_mem_in_kb = total_mem_in_kb%1024;total_memory = total_memory%1024; // Display memory sizeconsole.log("Total memory: " + total_mem_in_gb + "GB " + total_mem_in_mb + "MB " + total_mem_in_kb + "KB and " + total_memory + "Bytes"); Output: Total memory: 7GB 940MB 848KB and 0Bytes Example 3: // Node.js program to demonstrate the // os.totalmem() method // Import the os moduleconst os = require('os'); // Printing free memory out of total memoryconsole.log("Free Memory " + String(os.freemem()) + " Bytes out of " + String(os.totalmem()) + " Bytes"); Output: Free Memory 4161896448 Bytes out of 8502722560 Bytes Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/api/os.html#os_os_totalmem Node.js-os-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() 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? Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25607, "s": 25579, "text": "\n13 Oct, 2021" }, { "code": null, "e": 25758, "s": 25607, "text": "The os.totalmem() method is an inbuilt application programming interface of the os module which is used to get amount of total system memory in bytes." }, { "code": null, "e": 25766, "s": 25758, "text": "Syntax:" }, { "code": null, "e": 25780, "s": 25766, "text": "os.totalmem()" }, { "code": null, "e": 25836, "s": 25780, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 25946, "s": 25836, "text": "Return Value: This method returns an integer value that specifies the amount of total system memory in bytes." }, { "code": null, "e": 26016, "s": 25946, "text": "Below examples illustrate the use of os.totalmem() method in Node.js:" }, { "code": null, "e": 26027, "s": 26016, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // os.totalmem() method // Import the os moduleconst os = require('os'); // Printing os.totalmem() method valueconsole.log(os.totalmem());", "e": 26213, "s": 26027, "text": null }, { "code": null, "e": 26221, "s": 26213, "text": "Output:" }, { "code": null, "e": 26232, "s": 26221, "text": "8502722560" }, { "code": null, "e": 26243, "s": 26232, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // os.totalmem() method // Import the os moduleconst os = require('os'); // Convert total memory to kb, mb and gbvar total_memory = os.totalmem();var total_mem_in_kb = total_memory/1024;var total_mem_in_mb = total_mem_in_kb/1024;var total_mem_in_gb = total_mem_in_mb/1024; total_mem_in_kb = Math.floor(total_mem_in_kb);total_mem_in_mb = Math.floor(total_mem_in_mb);total_mem_in_gb = Math.floor(total_mem_in_gb); total_mem_in_mb = total_mem_in_mb%1024;total_mem_in_kb = total_mem_in_kb%1024;total_memory = total_memory%1024; // Display memory sizeconsole.log(\"Total memory: \" + total_mem_in_gb + \"GB \" + total_mem_in_mb + \"MB \" + total_mem_in_kb + \"KB and \" + total_memory + \"Bytes\");", "e": 26997, "s": 26243, "text": null }, { "code": null, "e": 27005, "s": 26997, "text": "Output:" }, { "code": null, "e": 27047, "s": 27005, "text": "Total memory: 7GB 940MB 848KB and 0Bytes\n" }, { "code": null, "e": 27058, "s": 27047, "text": "Example 3:" }, { "code": "// Node.js program to demonstrate the // os.totalmem() method // Import the os moduleconst os = require('os'); // Printing free memory out of total memoryconsole.log(\"Free Memory \" + String(os.freemem()) + \" Bytes out of \" + String(os.totalmem()) + \" Bytes\");", "e": 27330, "s": 27058, "text": null }, { "code": null, "e": 27338, "s": 27330, "text": "Output:" }, { "code": null, "e": 27392, "s": 27338, "text": "Free Memory 4161896448 Bytes out of 8502722560 Bytes\n" }, { "code": null, "e": 27473, "s": 27392, "text": "Note: The above program will compile and run by using the node index.js command." }, { "code": null, "e": 27530, "s": 27473, "text": "Reference: https://nodejs.org/api/os.html#os_os_totalmem" }, { "code": null, "e": 27548, "s": 27530, "text": "Node.js-os-module" }, { "code": null, "e": 27556, "s": 27548, "text": "Node.js" }, { "code": null, "e": 27573, "s": 27556, "text": "Web Technologies" }, { "code": null, "e": 27671, "s": 27573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27701, "s": 27671, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27730, "s": 27701, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27787, "s": 27730, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27841, "s": 27787, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27878, "s": 27841, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 27918, "s": 27878, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27963, "s": 27918, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28006, "s": 27963, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28056, "s": 28006, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Rotate an Image - GeeksforGeeks
25 Nov, 2021 The problem statement is to rotate an image clockwise 90 degrees for which here we will be using some in-built methods of BufferedImage class and Color c Classes required to perform the operation is as follows: To read and write an image file we have to import the File class. This class represents file and directory path names in general. To handle errors we use the IOException class. To hold the image we create the BufferedImage object for that we use BufferedImage class. This object is used to store an image in RAM. To perform the image read-write operation we will import the ImageIO class. This class has static methods to read and write an image. This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-dimensional shapes, text, and images on the Java(tm) platform. Example: Java // Java program to rotate image by 90 degrees clockwise // Importing classes from java.awt package for// painting graphics and imagesimport java.awt.Graphics2D;import java.awt.image.BufferedImage;// Importing input output classesimport java.io.File;import java.io.IOException;import javax.imageio.ImageIO; // Main classpublic class GFG { // Method 1 // To return rotated image public static BufferedImage rotate(BufferedImage img) { // Getting Dimensions of image int width = img.getWidth(); int height = img.getHeight(); // Creating a new buffered image BufferedImage newImage = new BufferedImage( img.getWidth(), img.getHeight(), img.getType()); // creating Graphics in buffered image Graphics2D g2 = newImage.createGraphics(); // Rotating image by degrees using toradians() // method // and setting new dimension t it g2.rotate(Math.toRadians(90), width / 2, height / 2); g2.drawImage(img, null, 0, 0); // Return rotated buffer image return newImage; } // Method 2 // Main driver method public static void main(String[] args) { // try block to check for exceptions try { // Reading original image BufferedImage originalImg = ImageIO.read( new File("D:/test/Image.jpeg")); // Getting and Printing dimensions of original // image System.out.println("Original Image Dimension: " + originalImg.getWidth() + "x" + originalImg.getHeight()); // Creating a subimage of given dimensions BufferedImage SubImg = rotate(originalImg); // Printing Dimensions of new image created // (Rotated image) System.out.println("Cropped Image Dimension: " + SubImg.getWidth() + "x" + SubImg.getHeight()); // Creating new file for rotated image File outputfile = new File("D:/test/ImageRotated.jpeg"); // Writing image in new file created ImageIO.write(SubImg, "jpg", outputfile); // Printing executed message System.out.println( "Image rotated successfully: " + outputfile.getPath()); } // Catch block to handle the exception catch (IOException e) { // Print the line number where exception // occurred e.printStackTrace(); } }} Output: After executing the program console will show dimensions and executed message and a new rotated image will be created at the path entered as shown: akshaysingh98088 ruhelaa48 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n25 Nov, 2021" }, { "code": null, "e": 25379, "s": 25225, "text": "The problem statement is to rotate an image clockwise 90 degrees for which here we will be using some in-built methods of BufferedImage class and Color c" }, { "code": null, "e": 25436, "s": 25379, "text": "Classes required to perform the operation is as follows:" }, { "code": null, "e": 25566, "s": 25436, "text": "To read and write an image file we have to import the File class. This class represents file and directory path names in general." }, { "code": null, "e": 25613, "s": 25566, "text": "To handle errors we use the IOException class." }, { "code": null, "e": 25749, "s": 25613, "text": "To hold the image we create the BufferedImage object for that we use BufferedImage class. This object is used to store an image in RAM." }, { "code": null, "e": 25883, "s": 25749, "text": "To perform the image read-write operation we will import the ImageIO class. This class has static methods to read and write an image." }, { "code": null, "e": 26157, "s": 25883, "text": "This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-dimensional shapes, text, and images on the Java(tm) platform." }, { "code": null, "e": 26166, "s": 26157, "text": "Example:" }, { "code": null, "e": 26171, "s": 26166, "text": "Java" }, { "code": "// Java program to rotate image by 90 degrees clockwise // Importing classes from java.awt package for// painting graphics and imagesimport java.awt.Graphics2D;import java.awt.image.BufferedImage;// Importing input output classesimport java.io.File;import java.io.IOException;import javax.imageio.ImageIO; // Main classpublic class GFG { // Method 1 // To return rotated image public static BufferedImage rotate(BufferedImage img) { // Getting Dimensions of image int width = img.getWidth(); int height = img.getHeight(); // Creating a new buffered image BufferedImage newImage = new BufferedImage( img.getWidth(), img.getHeight(), img.getType()); // creating Graphics in buffered image Graphics2D g2 = newImage.createGraphics(); // Rotating image by degrees using toradians() // method // and setting new dimension t it g2.rotate(Math.toRadians(90), width / 2, height / 2); g2.drawImage(img, null, 0, 0); // Return rotated buffer image return newImage; } // Method 2 // Main driver method public static void main(String[] args) { // try block to check for exceptions try { // Reading original image BufferedImage originalImg = ImageIO.read( new File(\"D:/test/Image.jpeg\")); // Getting and Printing dimensions of original // image System.out.println(\"Original Image Dimension: \" + originalImg.getWidth() + \"x\" + originalImg.getHeight()); // Creating a subimage of given dimensions BufferedImage SubImg = rotate(originalImg); // Printing Dimensions of new image created // (Rotated image) System.out.println(\"Cropped Image Dimension: \" + SubImg.getWidth() + \"x\" + SubImg.getHeight()); // Creating new file for rotated image File outputfile = new File(\"D:/test/ImageRotated.jpeg\"); // Writing image in new file created ImageIO.write(SubImg, \"jpg\", outputfile); // Printing executed message System.out.println( \"Image rotated successfully: \" + outputfile.getPath()); } // Catch block to handle the exception catch (IOException e) { // Print the line number where exception // occurred e.printStackTrace(); } }}", "e": 28782, "s": 26171, "text": null }, { "code": null, "e": 28940, "s": 28782, "text": " Output: After executing the program console will show dimensions and executed message and a new rotated image will be created at the path entered as shown: " }, { "code": null, "e": 28959, "s": 28942, "text": "akshaysingh98088" }, { "code": null, "e": 28969, "s": 28959, "text": "ruhelaa48" }, { "code": null, "e": 28974, "s": 28969, "text": "Java" }, { "code": null, "e": 28988, "s": 28974, "text": "Java Programs" }, { "code": null, "e": 28993, "s": 28988, "text": "Java" }, { "code": null, "e": 29091, "s": 28993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29106, "s": 29091, "text": "Stream In Java" }, { "code": null, "e": 29127, "s": 29106, "text": "Constructors in Java" }, { "code": null, "e": 29146, "s": 29127, "text": "Exceptions in Java" }, { "code": null, "e": 29176, "s": 29146, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29193, "s": 29176, "text": "Generics in Java" }, { "code": null, "e": 29219, "s": 29193, "text": "Java Programming Examples" }, { "code": null, "e": 29253, "s": 29219, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29300, "s": 29253, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29332, "s": 29300, "text": "How to Iterate HashMap in Java?" } ]
numpy.power() in Python - GeeksforGeeks
29 Nov, 2018 numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :Array element from first array is raised to the power of element from second element(all happens element-wise). Both arr1 and arr2 must have same shape and each element in arr1 must be raised to corresponding +ve value from arr2; otherwise it will raise a ValueError.Parameters : arr1 : [array_like]Input array or object which works as base. arr2 : [array_like]Input array or object which works as exponent. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result. **kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function. where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone. Return : An array with elements of arr1 raised to exponents in arr2 Code 1 : arr1 raised to arr2 # Python program explaining# power() functionimport numpy as np # input_arrayarr1 = [2, 2, 2, 2, 2]arr2 = [2, 3, 4, 5, 6]print ("arr1 : ", arr1)print ("arr1 : ", arr2) # output_arrayout = np.power(arr1, arr2)print ("\nOutput array : ", out) Output : arr1 : [2, 2, 2, 2, 2] arr2 : [2, 3, 4, 5, 6] Output array : [ 4 8 16 32 64] Code 2 : elements of arr1 raised to exponent 2 # Python program explaining# power() functionimport numpy as np # input_arrayarr1 = np.arange(8)exponent = 2print ("arr1 : ", arr1) # output_arrayout = np.power(arr1, exponent)print ("\nOutput array : ", out) Output : arr1 : [0 1 2 3 4 5 6 7] Output array : [ 0 1 4 9 16 25 36 49] Code 3 : Error if arr2 has -ve elements # Python program explaining# power() functionimport numpy as np # input_arrayarr1 = [2, 2, 2, 2, 2]arr2 = [2, -3, 4, -5, 6]print ("arr1 : ", arr1)print ("arr2 : ", arr2) # output_arrayout = np.power(arr1, arr2)print ("\nOutput array : ", out) Output : arr1 : [2, 2, 2, 2, 2] arr2 : [2, -3, 4, -5, 6] ValueError: Integers to negative integer powers are not allowed. References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.power.html#numpy.power. Python numpy-Mathematical 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": 25321, "s": 25293, "text": "\n29 Nov, 2018" }, { "code": null, "e": 25702, "s": 25321, "text": "numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :Array element from first array is raised to the power of element from second element(all happens element-wise). Both arr1 and arr2 must have same shape and each element in arr1 must be raised to corresponding +ve value from arr2; otherwise it will raise a ValueError.Parameters :" }, { "code": null, "e": 26303, "s": 25702, "text": "arr1 : [array_like]Input array or object which works as base.\narr2 : [array_like]Input array or object which works as exponent. \nout : [ndarray, optional]Output array with same dimensions as Input array, \n placed with result.\n**kwargs : Allows you to pass keyword variable length of argument to a function. \n It is used when we want to handle named argument in a function.\nwhere : [array_like, optional]True value means to calculate the universal \n functions(ufunc) at that position, False value means to leave the \n value in the output alone.\n" }, { "code": null, "e": 26312, "s": 26303, "text": "Return :" }, { "code": null, "e": 26372, "s": 26312, "text": "An array with elements of arr1 raised to exponents in arr2\n" }, { "code": null, "e": 26402, "s": 26372, "text": " Code 1 : arr1 raised to arr2" }, { "code": "# Python program explaining# power() functionimport numpy as np # input_arrayarr1 = [2, 2, 2, 2, 2]arr2 = [2, 3, 4, 5, 6]print (\"arr1 : \", arr1)print (\"arr1 : \", arr2) # output_arrayout = np.power(arr1, arr2)print (\"\\nOutput array : \", out)", "e": 26661, "s": 26402, "text": null }, { "code": null, "e": 26670, "s": 26661, "text": "Output :" }, { "code": null, "e": 26769, "s": 26670, "text": "arr1 : [2, 2, 2, 2, 2]\narr2 : [2, 3, 4, 5, 6]\n\nOutput array : [ 4 8 16 32 64]\n" }, { "code": null, "e": 26817, "s": 26769, "text": " Code 2 : elements of arr1 raised to exponent 2" }, { "code": "# Python program explaining# power() functionimport numpy as np # input_arrayarr1 = np.arange(8)exponent = 2print (\"arr1 : \", arr1) # output_arrayout = np.power(arr1, exponent)print (\"\\nOutput array : \", out)", "e": 27036, "s": 26817, "text": null }, { "code": null, "e": 27045, "s": 27036, "text": "Output :" }, { "code": null, "e": 27122, "s": 27045, "text": "arr1 : [0 1 2 3 4 5 6 7]\n\nOutput array : [ 0 1 4 9 16 25 36 49]" }, { "code": null, "e": 27163, "s": 27122, "text": " Code 3 : Error if arr2 has -ve elements" }, { "code": "# Python program explaining# power() functionimport numpy as np # input_arrayarr1 = [2, 2, 2, 2, 2]arr2 = [2, -3, 4, -5, 6]print (\"arr1 : \", arr1)print (\"arr2 : \", arr2) # output_arrayout = np.power(arr1, arr2)print (\"\\nOutput array : \", out)", "e": 27424, "s": 27163, "text": null }, { "code": null, "e": 27433, "s": 27424, "text": "Output :" }, { "code": null, "e": 27564, "s": 27433, "text": "arr1 : [2, 2, 2, 2, 2]\narr2 : [2, -3, 4, -5, 6]\nValueError: Integers to negative integer powers are not allowed." }, { "code": null, "e": 27666, "s": 27564, "text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.power.html#numpy.power." }, { "code": null, "e": 27701, "s": 27666, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27714, "s": 27701, "text": "Python-numpy" }, { "code": null, "e": 27721, "s": 27714, "text": "Python" }, { "code": null, "e": 27819, "s": 27721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27837, "s": 27819, "text": "Python Dictionary" }, { "code": null, "e": 27872, "s": 27837, "text": "Read a file line by line in Python" }, { "code": null, "e": 27904, "s": 27872, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27926, "s": 27904, "text": "Enumerate() in Python" }, { "code": null, "e": 27968, "s": 27926, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27998, "s": 27968, "text": "Iterate over a list in Python" }, { "code": null, "e": 28024, "s": 27998, "text": "Python String | replace()" }, { "code": null, "e": 28053, "s": 28024, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28097, "s": 28053, "text": "Reading and Writing to text files in Python" } ]
How to check whether the elements of a given NumPy array is non-zero? - GeeksforGeeks
29 Aug, 2020 In NumPy with the help of any() function, we can check whether any of the elements of a given array in NumPy is non-zero. We will pass an array in the any() function if it returns true then any of the element of the array is non zero if it returns false then all the elements of the array are zero. Syntax: numpy.any() Parameter :An array. Return :It return boolean value(True/False). Example 1: Python import numpy as np # Original arrayarray = np.array([4,6,0,0,0,4,89])print(x) # Test whether any of the elements# of a given array is non-zeroprint(np.any(array)) Output: True Example 2: Python import numpy as np # Original arrayarray = np.array([0,0,0,0,0,0])print(x) # Test whether any of the elements# of a given array is non-zeroprint(np.any(array)) Output: False Python numpy-arrayManipulation 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": 26521, "s": 26493, "text": "\n29 Aug, 2020" }, { "code": null, "e": 26820, "s": 26521, "text": "In NumPy with the help of any() function, we can check whether any of the elements of a given array in NumPy is non-zero. We will pass an array in the any() function if it returns true then any of the element of the array is non zero if it returns false then all the elements of the array are zero." }, { "code": null, "e": 26840, "s": 26820, "text": "Syntax: numpy.any()" }, { "code": null, "e": 26861, "s": 26840, "text": "Parameter :An array." }, { "code": null, "e": 26906, "s": 26861, "text": "Return :It return boolean value(True/False)." }, { "code": null, "e": 26917, "s": 26906, "text": "Example 1:" }, { "code": null, "e": 26924, "s": 26917, "text": "Python" }, { "code": "import numpy as np # Original arrayarray = np.array([4,6,0,0,0,4,89])print(x) # Test whether any of the elements# of a given array is non-zeroprint(np.any(array))", "e": 27091, "s": 26924, "text": null }, { "code": null, "e": 27099, "s": 27091, "text": "Output:" }, { "code": null, "e": 27105, "s": 27099, "text": "True\n" }, { "code": null, "e": 27116, "s": 27105, "text": "Example 2:" }, { "code": null, "e": 27123, "s": 27116, "text": "Python" }, { "code": "import numpy as np # Original arrayarray = np.array([0,0,0,0,0,0])print(x) # Test whether any of the elements# of a given array is non-zeroprint(np.any(array))", "e": 27285, "s": 27123, "text": null }, { "code": null, "e": 27293, "s": 27285, "text": "Output:" }, { "code": null, "e": 27300, "s": 27293, "text": "False\n" }, { "code": null, "e": 27331, "s": 27300, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 27344, "s": 27331, "text": "Python-numpy" }, { "code": null, "e": 27351, "s": 27344, "text": "Python" }, { "code": null, "e": 27449, "s": 27351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27467, "s": 27449, "text": "Python Dictionary" }, { "code": null, "e": 27502, "s": 27467, "text": "Read a file line by line in Python" }, { "code": null, "e": 27534, "s": 27502, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27556, "s": 27534, "text": "Enumerate() in Python" }, { "code": null, "e": 27598, "s": 27556, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27628, "s": 27598, "text": "Iterate over a list in Python" }, { "code": null, "e": 27654, "s": 27628, "text": "Python String | replace()" }, { "code": null, "e": 27683, "s": 27654, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27727, "s": 27683, "text": "Reading and Writing to text files in Python" } ]
rand() and srand() in C/C++ - GeeksforGeeks
13 May, 2022 rand () The rand() function is used in C/C++ to generate random numbers in the range [0, RAND_MAX). Note: If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs. Syntax: int rand(void): returns a pseudo-random number in the range of [0, RAND_MAX). RAND_MAX: is a constant whose default value may vary \between implementations but it is granted to be at least 32767. Say if we are generating 5 random numbers in C with the help of rand() in a loop, then every time we compile and run the program our output must be the same sequence of numbers. C #include <stdio.h>#include <stdlib.h> int main(void){ // This program will create same sequence of // random numbers on every program run for(int i = 0; i<5; i++) printf(" %d ", rand()); return 0;} NOTE: This program will create same sequence of random numbers on every program run. Output 1: 453 1276 3425 89 Output 2: 453 1276 3425 89 Output n: 453 1276 3425 89 srand() The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program start. Any other value for seed sets the generator to a different starting point. Syntax: void srand( unsigned seed ): Seeds the pseudo-random number generator used by rand() with the value seed. Note: The pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers. Standard practice is to use the result of a call to srand(time(0)) as the seed. However, time() returns a time_t value which vary everytime and hence the pseudo-random number vary for every program call. CPP // C program to generate random numbers#include <stdio.h>#include <stdlib.h>#include<time.h> // Driver programint main(void){ // This program will create different sequence of // random numbers on every program run // Use current time as seed for random generator srand(time(0)); for(int i = 0; i<4; i++) printf(" %d ", rand()); return 0;} NOTE: This program will create different sequence of random numbers on every program run. Output 1: 453 1432 325 89 Output 2: 8976 21234 45 8975 Output n: 563 9873 12321 24132 How srand() and rand() are related to each other? srand() sets the seed which is used by rand to generate “random” numbers. If you don’t call srand before your first call to rand, it’s as if you had called srand(1) to set the seed to one. In short, srand() — Set Seed for rand() Function. This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. avinashavi0941 matthewbalint C-Library CPP-Library C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 26073, "s": 26045, "text": "\n13 May, 2022" }, { "code": null, "e": 26081, "s": 26073, "text": "rand ()" }, { "code": null, "e": 26174, "s": 26081, "text": "The rand() function is used in C/C++ to generate random numbers in the range [0, RAND_MAX). " }, { "code": null, "e": 26328, "s": 26174, "text": "Note: If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs." }, { "code": null, "e": 26338, "s": 26328, "text": "Syntax: " }, { "code": null, "e": 26537, "s": 26338, "text": " int rand(void): \nreturns a pseudo-random number in the range of [0, RAND_MAX).\nRAND_MAX: is a constant whose default value may vary \n\\between implementations but it is granted to be at least 32767." }, { "code": null, "e": 26718, "s": 26539, "text": "Say if we are generating 5 random numbers in C with the help of rand() in a loop, then every time we compile and run the program our output must be the same sequence of numbers. " }, { "code": null, "e": 26720, "s": 26718, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h> int main(void){ // This program will create same sequence of // random numbers on every program run for(int i = 0; i<5; i++) printf(\" %d \", rand()); return 0;}", "e": 26946, "s": 26720, "text": null }, { "code": null, "e": 27041, "s": 26946, "text": "NOTE: This program will create same sequence of random numbers on every program run. Output 1:" }, { "code": null, "e": 27058, "s": 27041, "text": "453 1276 3425 89" }, { "code": null, "e": 27068, "s": 27058, "text": "Output 2:" }, { "code": null, "e": 27085, "s": 27068, "text": "453 1276 3425 89" }, { "code": null, "e": 27095, "s": 27085, "text": "Output n:" }, { "code": null, "e": 27112, "s": 27095, "text": "453 1276 3425 89" }, { "code": null, "e": 27122, "s": 27114, "text": "srand()" }, { "code": null, "e": 27387, "s": 27122, "text": "The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program start. Any other value for seed sets the generator to a different starting point. " }, { "code": null, "e": 27397, "s": 27387, "text": "Syntax: " }, { "code": null, "e": 27504, "s": 27397, "text": "void srand( unsigned seed ): \nSeeds the pseudo-random number generator used by rand() with the value seed." }, { "code": null, "e": 27750, "s": 27504, "text": "Note: The pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers. " }, { "code": null, "e": 27956, "s": 27750, "text": "Standard practice is to use the result of a call to srand(time(0)) as the seed. However, time() returns a time_t value which vary everytime and hence the pseudo-random number vary for every program call. " }, { "code": null, "e": 27960, "s": 27956, "text": "CPP" }, { "code": "// C program to generate random numbers#include <stdio.h>#include <stdlib.h>#include<time.h> // Driver programint main(void){ // This program will create different sequence of // random numbers on every program run // Use current time as seed for random generator srand(time(0)); for(int i = 0; i<4; i++) printf(\" %d \", rand()); return 0;}", "e": 28334, "s": 27960, "text": null }, { "code": null, "e": 28434, "s": 28334, "text": "NOTE: This program will create different sequence of random numbers on every program run. Output 1:" }, { "code": null, "e": 28450, "s": 28434, "text": "453 1432 325 89" }, { "code": null, "e": 28460, "s": 28450, "text": "Output 2:" }, { "code": null, "e": 28479, "s": 28460, "text": "8976 21234 45 8975" }, { "code": null, "e": 28489, "s": 28479, "text": "Output n:" }, { "code": null, "e": 28510, "s": 28489, "text": "563 9873 12321 24132" }, { "code": null, "e": 28562, "s": 28512, "text": "How srand() and rand() are related to each other?" }, { "code": null, "e": 29238, "s": 28562, "text": "srand() sets the seed which is used by rand to generate “random” numbers. If you don’t call srand before your first call to rand, it’s as if you had called srand(1) to set the seed to one. In short, srand() — Set Seed for rand() Function. This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 29253, "s": 29238, "text": "avinashavi0941" }, { "code": null, "e": 29267, "s": 29253, "text": "matthewbalint" }, { "code": null, "e": 29277, "s": 29267, "text": "C-Library" }, { "code": null, "e": 29289, "s": 29277, "text": "CPP-Library" }, { "code": null, "e": 29300, "s": 29289, "text": "C Language" }, { "code": null, "e": 29304, "s": 29300, "text": "C++" }, { "code": null, "e": 29308, "s": 29304, "text": "CPP" }, { "code": null, "e": 29406, "s": 29308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29428, "s": 29406, "text": "Function Pointer in C" }, { "code": null, "e": 29445, "s": 29428, "text": "Substring in C++" }, { "code": null, "e": 29457, "s": 29445, "text": "fork() in C" }, { "code": null, "e": 29482, "s": 29457, "text": "std::string class in C++" }, { "code": null, "e": 29509, "s": 29482, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 29527, "s": 29509, "text": "Vector in C++ STL" }, { "code": null, "e": 29546, "s": 29527, "text": "Inheritance in C++" }, { "code": null, "e": 29592, "s": 29546, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29635, "s": 29592, "text": "Map in C++ Standard Template Library (STL)" } ]
Python | Scipy stats.halfgennorm.isf() method - GeeksforGeeks
06 Feb, 2020 With the help of stats.halfgennorm.isf() method, we can get the value of inverse survival function which is inverse(1 – cdf) by using stats.halfgennorm.isf() method. Syntax : stats.halfgennorm.isf(x, beta)Return : Return the value of inverse survival function. Example #1 :In this example we can see that by using stats.halfgennorm.isf() method, we are able to get the value of inverse survival function by using this method. # import halfgennormfrom scipy.stats import halfgennormbeta = 1 # Using stats.halfgennorm.isf() methodgfg = halfgennorm.isf(0.3, beta) print(gfg) Output : 1.2039728043259357 Example #2 : # import halfgennormfrom scipy.stats import halfgennormbeta = 4 # Using stats.halfgennorm.isf() methodgfg = halfgennorm.isf(0.9, beta) print(gfg) Output : 0.09064147135377666 Python scipy-stats-functions Python-scipy 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 Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n06 Feb, 2020" }, { "code": null, "e": 25703, "s": 25537, "text": "With the help of stats.halfgennorm.isf() method, we can get the value of inverse survival function which is inverse(1 – cdf) by using stats.halfgennorm.isf() method." }, { "code": null, "e": 25798, "s": 25703, "text": "Syntax : stats.halfgennorm.isf(x, beta)Return : Return the value of inverse survival function." }, { "code": null, "e": 25963, "s": 25798, "text": "Example #1 :In this example we can see that by using stats.halfgennorm.isf() method, we are able to get the value of inverse survival function by using this method." }, { "code": "# import halfgennormfrom scipy.stats import halfgennormbeta = 1 # Using stats.halfgennorm.isf() methodgfg = halfgennorm.isf(0.3, beta) print(gfg)", "e": 26111, "s": 25963, "text": null }, { "code": null, "e": 26120, "s": 26111, "text": "Output :" }, { "code": null, "e": 26139, "s": 26120, "text": "1.2039728043259357" }, { "code": null, "e": 26152, "s": 26139, "text": "Example #2 :" }, { "code": "# import halfgennormfrom scipy.stats import halfgennormbeta = 4 # Using stats.halfgennorm.isf() methodgfg = halfgennorm.isf(0.9, beta) print(gfg)", "e": 26300, "s": 26152, "text": null }, { "code": null, "e": 26309, "s": 26300, "text": "Output :" }, { "code": null, "e": 26329, "s": 26309, "text": "0.09064147135377666" }, { "code": null, "e": 26358, "s": 26329, "text": "Python scipy-stats-functions" }, { "code": null, "e": 26371, "s": 26358, "text": "Python-scipy" }, { "code": null, "e": 26378, "s": 26371, "text": "Python" }, { "code": null, "e": 26476, "s": 26378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26508, "s": 26476, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26550, "s": 26508, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26592, "s": 26550, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26619, "s": 26592, "text": "Python Classes and Objects" }, { "code": null, "e": 26675, "s": 26619, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26697, "s": 26675, "text": "Defaultdict in Python" }, { "code": null, "e": 26736, "s": 26697, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26767, "s": 26736, "text": "Python | os.path.join() method" }, { "code": null, "e": 26796, "s": 26767, "text": "Create a directory in Python" } ]
Retrieving HTML From data using Flask - GeeksforGeeks
16 Jul, 2020 Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. Read this article to know more about FlaskCreate form as HTML We will create a simple HTML Form, very simple Login form <form action="{{ url_for("gfg")}}" method="post"><label for="firstname">First Name:</label><input type="text" id="firstname" name="fname" placeholder="firstname"><label for="lastname">Last Name:</label><input type="text" id="lastname" name="lname" placeholder="lastname"><button type="submit">Login</button> Its an simple HTML form using the post method the only thing is unique is action URL. URL_for is an Flask way of creating dynamic URLs where the first arguments refers to the function of that specific route in flask. In our form it will create a Dynamic route which has gfg function in the flask app Create Flask application Start your virtual environment pip install virtualenv python3 -m venv env pip install flask Now we will create the flask backend which will get user input from HTML form # importing Flask and other modulesfrom flask import Flask, request, render_template # Flask constructorapp = Flask(__name__) # A decorator used to tell the application# which URL is associated function@app.route('/', methods =["GET", "POST"])def gfg(): if request.method == "POST": # getting input with name = fname in HTML form first_name = request.form.get("fname") # getting input with name = lname in HTML form last_name = request.form.get("lname") return "Your name is "+first_name + last_name return render_template("form.html") if __name__=='__main__': app.run() Working – Almost everything is simple, We have created a simple Flask app, if we look into code importing flask and creating a home route which has both get and post methods defining a function with name gfg if requesting method is post, which is the method we specified in the form we get the input data from HTML form you can get HTML input from Form using name attribute and request.form.get() function by passing the name of that input as argumentrequest.form.get("fname") will get input from Input value which has name attribute as fname and stores in first_name variablerequest.form.get("lname") will get input from Input value which has name attribute as lname and stores in last_name variable request.form.get("fname") will get input from Input value which has name attribute as fname and stores in first_name variable request.form.get("lname") will get input from Input value which has name attribute as lname and stores in last_name variable The return value of POST method is by replacing the variables with their valuesYour name is "+first_name+last_name the default return value for the function gfg id returning home.html template you can review what-does-the-if-__name__-__main__-dofrom the article Output –Code in actionflask server runninghtml formreturning data from html template 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 ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25691, "s": 25663, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25984, "s": 25691, "text": "Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks." }, { "code": null, "e": 26046, "s": 25984, "text": "Read this article to know more about FlaskCreate form as HTML" }, { "code": null, "e": 26104, "s": 26046, "text": "We will create a simple HTML Form, very simple Login form" }, { "code": "<form action=\"{{ url_for(\"gfg\")}}\" method=\"post\"><label for=\"firstname\">First Name:</label><input type=\"text\" id=\"firstname\" name=\"fname\" placeholder=\"firstname\"><label for=\"lastname\">Last Name:</label><input type=\"text\" id=\"lastname\" name=\"lname\" placeholder=\"lastname\"><button type=\"submit\">Login</button>", "e": 26412, "s": 26104, "text": null }, { "code": null, "e": 26712, "s": 26412, "text": "Its an simple HTML form using the post method the only thing is unique is action URL. URL_for is an Flask way of creating dynamic URLs where the first arguments refers to the function of that specific route in flask. In our form it will create a Dynamic route which has gfg function in the flask app" }, { "code": null, "e": 26737, "s": 26712, "text": "Create Flask application" }, { "code": null, "e": 26768, "s": 26737, "text": "Start your virtual environment" }, { "code": null, "e": 26830, "s": 26768, "text": "pip install virtualenv\npython3 -m venv env\npip install flask\n" }, { "code": null, "e": 26908, "s": 26830, "text": "Now we will create the flask backend which will get user input from HTML form" }, { "code": "# importing Flask and other modulesfrom flask import Flask, request, render_template # Flask constructorapp = Flask(__name__) # A decorator used to tell the application# which URL is associated function@app.route('/', methods =[\"GET\", \"POST\"])def gfg(): if request.method == \"POST\": # getting input with name = fname in HTML form first_name = request.form.get(\"fname\") # getting input with name = lname in HTML form last_name = request.form.get(\"lname\") return \"Your name is \"+first_name + last_name return render_template(\"form.html\") if __name__=='__main__': app.run()", "e": 27526, "s": 26908, "text": null }, { "code": null, "e": 27536, "s": 27526, "text": "Working –" }, { "code": null, "e": 27622, "s": 27536, "text": "Almost everything is simple, We have created a simple Flask app, if we look into code" }, { "code": null, "e": 27700, "s": 27622, "text": "importing flask and creating a home route which has both get and post methods" }, { "code": null, "e": 27734, "s": 27700, "text": "defining a function with name gfg" }, { "code": null, "e": 27846, "s": 27734, "text": "if requesting method is post, which is the method we specified in the form we get the input data from HTML form" }, { "code": null, "e": 28227, "s": 27846, "text": "you can get HTML input from Form using name attribute and request.form.get() function by passing the name of that input as argumentrequest.form.get(\"fname\") will get input from Input value which has name attribute as fname and stores in first_name variablerequest.form.get(\"lname\") will get input from Input value which has name attribute as lname and stores in last_name variable" }, { "code": null, "e": 28353, "s": 28227, "text": "request.form.get(\"fname\") will get input from Input value which has name attribute as fname and stores in first_name variable" }, { "code": null, "e": 28478, "s": 28353, "text": "request.form.get(\"lname\") will get input from Input value which has name attribute as lname and stores in last_name variable" }, { "code": null, "e": 28593, "s": 28478, "text": "The return value of POST method is by replacing the variables with their valuesYour name is \"+first_name+last_name" }, { "code": null, "e": 28671, "s": 28593, "text": "the default return value for the function gfg id returning home.html template" }, { "code": null, "e": 28740, "s": 28671, "text": "you can review what-does-the-if-__name__-__main__-dofrom the article" }, { "code": null, "e": 28825, "s": 28740, "text": "Output –Code in actionflask server runninghtml formreturning data from html template" }, { "code": null, "e": 28838, "s": 28825, "text": "Python Flask" }, { "code": null, "e": 28845, "s": 28838, "text": "Python" }, { "code": null, "e": 28943, "s": 28845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28961, "s": 28943, "text": "Python Dictionary" }, { "code": null, "e": 28996, "s": 28961, "text": "Read a file line by line in Python" }, { "code": null, "e": 29028, "s": 28996, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29070, "s": 29028, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29096, "s": 29070, "text": "Python String | replace()" }, { "code": null, "e": 29125, "s": 29096, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29169, "s": 29125, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29206, "s": 29169, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29242, "s": 29206, "text": "Convert integer to string in Python" } ]
Express.js express.urlencoded() Function - GeeksforGeeks
05 May, 2021 The express.urlencoded() function is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.Syntax: express.urlencoded( [options] ) Parameter: The options parameter contains various property like extended, inflate, limit, verify etc.Return Value: It returns an Object.Installation of express module: You can visit the link to Install express module. You can install this package by using this command. You can visit the link to Install express module. You can install this package by using this command. npm install express After installing the express module, you can check your express version in command prompt using the command. After installing the express module, you can check your express version in command prompt using the command. 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. 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 Example 1: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; app.use(express.urlencoded({extended:false})); app.post('/', function (req, res) { console.log(req.body); res.end();}); 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: The project structure will look like this: Make sure you have installed express module using the following command: Make sure you have installed express module using the following command: npm install express Run index.js file using below command: Run index.js file using below command: node index.js Output: Output: Server listening on PORT 3000 Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console: Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console: Example 2: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; // Without this middleware// app.use(express.urlencoded({extended:false})); app.post('/', function (req, res) { console.log(req.body); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console: Server listening on PORT 3000 undefined Reference: Offical Documentation simmytarika5 Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 30835, "s": 30807, "text": "\n05 May, 2021" }, { "code": null, "e": 31006, "s": 30835, "text": "The express.urlencoded() function is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.Syntax: " }, { "code": null, "e": 31038, "s": 31006, "text": "express.urlencoded( [options] )" }, { "code": null, "e": 31208, "s": 31038, "text": "Parameter: The options parameter contains various property like extended, inflate, limit, verify etc.Return Value: It returns an Object.Installation of express module: " }, { "code": null, "e": 31312, "s": 31208, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 31416, "s": 31312, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 31436, "s": 31416, "text": "npm install express" }, { "code": null, "e": 31547, "s": 31436, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 31658, "s": 31547, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 31678, "s": 31658, "text": "npm version express" }, { "code": null, "e": 31815, "s": 31678, "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. " }, { "code": null, "e": 31952, "s": 31815, "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. " }, { "code": null, "e": 31966, "s": 31952, "text": "node index.js" }, { "code": null, "e": 31998, "s": 31966, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 32009, "s": 31998, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.use(express.urlencoded({extended:false})); app.post('/', function (req, res) { console.log(req.body); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 32322, "s": 32009, "text": null }, { "code": null, "e": 32350, "s": 32322, "text": "Steps to run the program: " }, { "code": null, "e": 32395, "s": 32350, "text": "The project structure will look like this: " }, { "code": null, "e": 32440, "s": 32395, "text": "The project structure will look like this: " }, { "code": null, "e": 32515, "s": 32440, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 32590, "s": 32515, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 32610, "s": 32590, "text": "npm install express" }, { "code": null, "e": 32651, "s": 32610, "text": "Run index.js file using below command: " }, { "code": null, "e": 32692, "s": 32651, "text": "Run index.js file using below command: " }, { "code": null, "e": 32706, "s": 32692, "text": "node index.js" }, { "code": null, "e": 32716, "s": 32706, "text": "Output: " }, { "code": null, "e": 32726, "s": 32716, "text": "Output: " }, { "code": null, "e": 32756, "s": 32726, "text": "Server listening on PORT 3000" }, { "code": null, "e": 32970, "s": 32756, "text": " Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console: " }, { "code": null, "e": 33185, "s": 32972, "text": "Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console: " }, { "code": null, "e": 33221, "s": 33189, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 33232, "s": 33221, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // Without this middleware// app.use(express.urlencoded({extended:false})); app.post('/', function (req, res) { console.log(req.body); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 33574, "s": 33232, "text": null }, { "code": null, "e": 33615, "s": 33574, "text": "Run index.js file using below command: " }, { "code": null, "e": 33629, "s": 33615, "text": "node index.js" }, { "code": null, "e": 33842, "s": 33629, "text": "Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console: " }, { "code": null, "e": 33882, "s": 33842, "text": "Server listening on PORT 3000\nundefined" }, { "code": null, "e": 33916, "s": 33882, "text": "Reference: Offical Documentation " }, { "code": null, "e": 33929, "s": 33916, "text": "simmytarika5" }, { "code": null, "e": 33940, "s": 33929, "text": "Express.js" }, { "code": null, "e": 33948, "s": 33940, "text": "Node.js" }, { "code": null, "e": 33965, "s": 33948, "text": "Web Technologies" }, { "code": null, "e": 34063, "s": 33965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34096, "s": 34063, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34144, "s": 34096, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34177, "s": 34144, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 34207, "s": 34177, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 34236, "s": 34207, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 34276, "s": 34236, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34309, "s": 34276, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34354, "s": 34309, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34397, "s": 34354, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Set Difference in list of dictionaries - GeeksforGeeks
26 Feb, 2019 The difference of two lists have been discussed many a times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehensionThe naive method to iterate both the list and extract the difference can be shortened to the method in which we shorten the code and increase the readability using list comprehension. # Python3 code to demonstrate # set difference in dictionary list # using list comprehension # initializing list test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ]test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using list comprehension# set difference in dictionary list res = [i for i in test_list1 if i not in test_list2] \ + [j for j in test_list2 if j not in test_list1] # printing result print ("The set difference of list is : " + str(res)) Output : The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]The set difference of list is : [{‘Shambhavi’: 2019}] Method #2 : Using itertools.filterfalse()This is a different way in which this particular task can be performed using the in built python function. The filterfalse method filters the not present element of one list with respect to other. # Python3 code to demonstrate # set difference in dictionary list # using itertools.filterfalse()import itertools # initializing list test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ]test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using itertools.filterfalse()# set difference in dictionary list res = list(itertools.filterfalse(lambda i: i in test_list1, test_list2)) \ + list(itertools.filterfalse(lambda j: j in test_list2, test_list1)) # printing result print ("The set difference of list is : " + str(res)) Output : The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]The set difference of list is : [{‘Shambhavi’: 2019}] Python dictionary-programs Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Feb, 2019" }, { "code": null, "e": 25796, "s": 25537, "text": "The difference of two lists have been discussed many a times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 26016, "s": 25796, "text": "Method #1 : Using list comprehensionThe naive method to iterate both the list and extract the difference can be shortened to the method in which we shorten the code and increase the readability using list comprehension." }, { "code": "# Python3 code to demonstrate # set difference in dictionary list # using list comprehension # initializing list test_list1 = [{\"HpY\" : 22}, {\"BirthdaY\" : 2}, ]test_list2 = [{\"HpY\" : 22}, {\"BirthdaY\" : 2}, {\"Shambhavi\" : 2019}] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using list comprehension# set difference in dictionary list res = [i for i in test_list1 if i not in test_list2] \\ + [j for j in test_list2 if j not in test_list1] # printing result print (\"The set difference of list is : \" + str(res))", "e": 26625, "s": 26016, "text": null }, { "code": null, "e": 26634, "s": 26625, "text": "Output :" }, { "code": null, "e": 26819, "s": 26634, "text": "The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]The set difference of list is : [{‘Shambhavi’: 2019}]" }, { "code": null, "e": 27058, "s": 26819, "text": " Method #2 : Using itertools.filterfalse()This is a different way in which this particular task can be performed using the in built python function. The filterfalse method filters the not present element of one list with respect to other." }, { "code": "# Python3 code to demonstrate # set difference in dictionary list # using itertools.filterfalse()import itertools # initializing list test_list1 = [{\"HpY\" : 22}, {\"BirthdaY\" : 2}, ]test_list2 = [{\"HpY\" : 22}, {\"BirthdaY\" : 2}, {\"Shambhavi\" : 2019}] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using itertools.filterfalse()# set difference in dictionary list res = list(itertools.filterfalse(lambda i: i in test_list1, test_list2)) \\ + list(itertools.filterfalse(lambda j: j in test_list2, test_list1)) # printing result print (\"The set difference of list is : \" + str(res))", "e": 27731, "s": 27058, "text": null }, { "code": null, "e": 27740, "s": 27731, "text": "Output :" }, { "code": null, "e": 27925, "s": 27740, "text": "The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]The set difference of list is : [{‘Shambhavi’: 2019}]" }, { "code": null, "e": 27952, "s": 27925, "text": "Python dictionary-programs" }, { "code": null, "e": 27973, "s": 27952, "text": "Python list-programs" }, { "code": null, "e": 27980, "s": 27973, "text": "Python" }, { "code": null, "e": 27996, "s": 27980, "text": "Python Programs" }, { "code": null, "e": 28094, "s": 27996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28126, "s": 28094, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28168, "s": 28126, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28210, "s": 28168, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28266, "s": 28210, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28293, "s": 28266, "text": "Python Classes and Objects" }, { "code": null, "e": 28315, "s": 28293, "text": "Defaultdict in Python" }, { "code": null, "e": 28354, "s": 28315, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28400, "s": 28354, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28438, "s": 28400, "text": "Python | Convert a list to dictionary" } ]
Python | Pandas dataframe.sem() - GeeksforGeeks
23 Nov, 2018 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 dataframe.sem() function return unbiased standard error of the mean over requested axis. The standard error (SE) of a statistic (usually an estimate of a parameter) is the standard deviation of its sampling distribution[1] or an estimate of that standard deviation. If the parameter or the statistic is the mean, it is called the standard error of the mean (SEM). Syntax : DataFrame.sem(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs) Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesddof : Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N represents the number of elements.numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series Return : sem : Series or DataFrame (if level specified) For link to the CSV file used in the code, click here Example #1: Use sem() function to find the standard error of the mean of the given dataframe over the index axis. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf Let’s use the dataframe.sem() function to find the standard error of the mean over the index axis. # find standard error of the mean of all the columnsdf.sem(axis = 0) Output :Notice, all the non-numeric columns and values are automatically not included in the calculation of the dataframe. We did not have to specifically input the numeric columns for the calculation of the standard error of the mean. Example #2: Use sem() function to find the standard error of the mean over the column axis. Also do not skip the NaN values in the calculation of the dataframe. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Calculate the standard error of # the mean of all the rows in dataframedf.sem(axis = 1, skipna = False) Output :When we include the NaN values then it will cause that particular row or column to be NaN Python pandas-dataFrame Python pandas-dataFrame-methods 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 Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 26059, "s": 26031, "text": "\n23 Nov, 2018" }, { "code": null, "e": 26273, "s": 26059, "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": 26644, "s": 26273, "text": "Pandas dataframe.sem() function return unbiased standard error of the mean over requested axis. The standard error (SE) of a statistic (usually an estimate of a parameter) is the standard deviation of its sampling distribution[1] or an estimate of that standard deviation. If the parameter or the statistic is the mean, it is called the standard error of the mean (SEM)." }, { "code": null, "e": 26740, "s": 26644, "text": "Syntax : DataFrame.sem(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)" }, { "code": null, "e": 27250, "s": 26740, "text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesddof : Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N represents the number of elements.numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series" }, { "code": null, "e": 27306, "s": 27250, "text": "Return : sem : Series or DataFrame (if level specified)" }, { "code": null, "e": 27360, "s": 27306, "text": "For link to the CSV file used in the code, click here" }, { "code": null, "e": 27474, "s": 27360, "text": "Example #1: Use sem() function to find the standard error of the mean of the given dataframe over the index axis." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf", "e": 27597, "s": 27474, "text": null }, { "code": null, "e": 27696, "s": 27597, "text": "Let’s use the dataframe.sem() function to find the standard error of the mean over the index axis." }, { "code": "# find standard error of the mean of all the columnsdf.sem(axis = 0)", "e": 27765, "s": 27696, "text": null }, { "code": null, "e": 28162, "s": 27765, "text": "Output :Notice, all the non-numeric columns and values are automatically not included in the calculation of the dataframe. We did not have to specifically input the numeric columns for the calculation of the standard error of the mean. Example #2: Use sem() function to find the standard error of the mean over the column axis. Also do not skip the NaN values in the calculation of the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Calculate the standard error of # the mean of all the rows in dataframedf.sem(axis = 1, skipna = False)", "e": 28367, "s": 28162, "text": null }, { "code": null, "e": 28465, "s": 28367, "text": "Output :When we include the NaN values then it will cause that particular row or column to be NaN" }, { "code": null, "e": 28489, "s": 28465, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28521, "s": 28489, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28535, "s": 28521, "text": "Python-pandas" }, { "code": null, "e": 28542, "s": 28535, "text": "Python" }, { "code": null, "e": 28640, "s": 28542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28658, "s": 28640, "text": "Python Dictionary" }, { "code": null, "e": 28690, "s": 28658, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28712, "s": 28690, "text": "Enumerate() in Python" }, { "code": null, "e": 28754, "s": 28712, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28784, "s": 28754, "text": "Iterate over a list in Python" }, { "code": null, "e": 28813, "s": 28784, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28857, "s": 28813, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28894, "s": 28857, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28930, "s": 28894, "text": "Convert integer to string in Python" } ]
Largest square formed in a matrix | Practice | GeeksforGeeks
Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s. Example 1: Input: n = 2, m = 2 mat = {{1, 1}, {1, 1}} Output: 2 Explaination: The maximum size of the square sub-matrix is 2. The matrix itself is the maximum sized sub-matrix in this case. Example 2: Input: n = 2, m = 2 mat = {{0, 0}, {0, 0}} Output: 0 Explaination: There is no 1 in the matrix. Your Task: You do not need to read input or print anything. Your task is to complete the function maxSquare() which takes n, m and mat as input parameters and returns the size of the maximum square sub-matrix of given matrix. Expected Time Complexity: O(n*m) Expected Auxiliary Space: O(n*m) Constraints: 1 ≤ n, m ≤ 50 0 ≤ mat[i][j] ≤ 1 0 vickyupadhyay361 day ago giving error in one test case while submitting, but passing for same test case in custom input int maxSquare(int n, int m, vector<vector<int>> mat){ // code here vector<vector<int>> t(n,vector<int>(m,0)); int mx=0; for(int i=n-1;i>=0;i--){ for(int j=m-1;j>=0;j--){ if(mat[i][j]==1){ if(i==n-1 || j==n-1){//last row or last column t[i][j]=1; } else{ t[i][j]=1+min(t[i][j+1],min(t[i+1][j+1],t[i+1][j])); } } mx=max(mx,t[i][j]); } } return mx; } 0 tanishqspike1143 weeks ago C++| Simple DP Logic class Solution{ public: int maxSquare(int n, int m, vector<vector<int>> mat){ vector<vector<int>> dp(n+1,vector<int>(m+1)); int ans=0; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(mat[i-1][j-1]==1) dp[i][j]=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1; ans=max(ans,dp[i][j]); } } return ans; } }; 0 sharadyaduvanshi3 weeks ago int maxSquare(int n, int m, vector<vector<int>> mat){ // code here // for(int i = 0 ; i < n; i ++) // { // for(int j = 0; j < m; j ++) // { // mat[i][j] = 1 - mat[i][j]; // } // } int **dp = new int*[n+1]; for(int i = 0 ; i< n; i ++) { dp[i] = new int[m+1]; for(int j = 0; j < m; j ++) { // if(i == n-1 || j == m-1) // dp[i][j] = mat[i][j]; // if(mat[i][j] == 0) dp[i][j] = mat[i][j]; } } for(int i = n-2 ; i>= 0; i --) { //dp[i] = new int[m+1]; for(int j = m-2; j >=0 ; j --) { if(j+1 < m && i+1<n &&mat[i][j] == 1) dp[i][j] = dp[i][j]+min(dp[i][j+1],min(dp[i+1][j],dp[i+1][j+1])); } } int ans = INT_MIN; for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { ans = max(ans,dp[i][j]); } } return ans; } 0 jainmuskan5653 weeks ago // int helpSolve(int n,int m, vector<vector<int>> mat, vector<vector<int>>& dp){ // int r= n, c= m; // // if(n>=r || m>=c){ // // return 0; // // } // // if(dp[n][m]!= -1){ // // return dp[n][m]; // // } // // int right= helpSolve(n,m+1,mat,dp); // dp[n][m+1]; // // int down= helpSolve(n+1,m,mat,dp); // dp[n+1][m]; // // int diag= helpSolve(n+1,m+1,mat,dp); // dp[n+1][m+1]; // // dp[n][m]=0; // // if(mat[n][m]==1){ // // dp[n][m]=1+min({right,down,diag}); // // } // // // int ans=INT_MIN; // // // for(int i=0;i<n;i++){ // // // for(int j=0;j<m;j++){ // // // ans=max(ans,dp[i][j]); // // // } // // // } // return dp[n][m]; // } int maxSquare(int n, int m, vector<vector<int>> mat){ vector<vector<int>>dp(n+1,vector<int>(m+1)); int r=n, c=m; for(int i=0;i<=r;i++){ for(int j=0;j<=c;j++){ if(i==0||j==0){ dp[i][j]=0; } } } for(int i=1;i<=r;i++){ for(int j=1;j<=c;j++){ if(mat[i-1][j-1]==1){ dp[i][j]= 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]}); } else if(mat[i-1][j-1]==0){ dp[i][j]=0; } } } int ans= dp[n][m]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ ans=max(ans,dp[i][j]); } } return ans; } 0 khushiaggarwal09021 month ago //Easiest approch (According to Aditya Verma approch) int maxSquare(int n, int m, vector<vector<int>> mat) { int dp[n+1][m+1]; int ans=INT_MIN; for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { if(i==0 || j==0) { dp[i][j]=0; } } } for(int i=1;i<n+1;i++) for(int j=1;j<m+1;j++) { if(mat[i-1][j-1]==1) { dp[i][j] = 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]}); } else if(mat[i-1][j-1]==0) { dp[i][j]=0; } } for(int i=1;i<n+1;i++) for(int j=1;j<m+1;j++) { if(dp[i][j]>ans) { ans=dp[i][j]; } } return ans; } 0 aasif23641 month ago class Solution{public: int maxSquare(int n, int m, vector<vector<int>> mat){ vector<vector<int>>dp(n , vector<int>(m , 0)); int res=0; for(int i=n-1 ; i>=0 ; i--){ for(int j=m-1 ; j>=0 ; j--){ if(i==n-1 and j==m-1){ dp[i][j]=mat[i][j]; } else if(i==n-1){ dp[i][j]=mat[i][j]; } else if(j==m-1){ dp[i][j]=mat[i][j]; } else if(mat[i][j]==1){ dp[i][j]=min({dp[i][j+1] , dp[i+1][j] , dp[i+1][j+1]}) + 1; } res=max(res , dp[i][j]); } } return res; }}; 0 yashgehi3982 months ago class Solution{ public: int maxSquare(int n, int m, vector<vector<int>> mat){ // code here vector<vector<int>> dp(n+1,vector<int>(m+1,0)); int size =0; for(int i{1};i<=n;i++){ for(int j{1};j<=m;j++){ if(mat[i-1][j-1] == 0) dp[i][j] =0; else dp[i][j] = 1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1])); size = max(size,dp[i][j]); } } return size; } }; 0 artistdarkangel2 months ago JAVA Solution - Time Complexity: O(n*m)Auxiliary Space: O(1) class Solution{ static int maxSquare(int n, int m, int mat[][]){ int max=0; if(n==0 || m==0) return 0; for(int i=n-1; i>=0; i--) { for(int j=m-1; j>=0; j--) { if(mat[i][j]==1) { max=1; break; } } if(max==1) break; } for(int i=n-2; i>=0; i--) { for(int j=m-2; j>=0; j--) { if(mat[i][j]==1) { mat[i][j]=Math.min(Math.min(mat[i+1][j], mat[i][j+1]),mat[i+1][j+1])+1; if(mat[i][j]>max) max=mat[i][j]; } } } return max; }} 0 sharma_nitin_262 months ago class Solution{ public: int maxSquare(int n, int m, vector<vector<int>> v){ int ans=0; int a[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ if(i==0 || j==0){ a[i][j]=v[i][j]; if(ans<a[i][j]) ans=a[i][j]; } else if(v[i][j]==1){ a[i][j]=min({a[i][j-1],a[i-1][j],a[i-1][j-1]})+1; if(ans<a[i][j]) ans=a[i][j]; } else a[i][j]=0; } return ans; } }; 0 lindan1232 months ago int maxSquare(int n, int m, vector<vector<int>> mat){ int dp[n+1][m+1]; int ans=INT_MIN; for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { if(i==0 || j==0) { dp[i][j]=0; } else if(mat[i-1][j-1]==1) { dp[i][j] = 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]}); } else if(mat[i-1][j-1]==0) { dp[i][j]=0; } ans = max(ans,dp[i][j]); } } return ans; } Time Taken : 0.0 Cpp 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": 336, "s": 238, "text": "Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s." }, { "code": null, "e": 347, "s": 336, "text": "Example 1:" }, { "code": null, "e": 535, "s": 347, "text": "Input: n = 2, m = 2\nmat = {{1, 1}, \n {1, 1}}\nOutput: 2\nExplaination: The maximum size of the square\nsub-matrix is 2. The matrix itself is the \nmaximum sized sub-matrix in this case." }, { "code": null, "e": 546, "s": 535, "text": "Example 2:" }, { "code": null, "e": 650, "s": 546, "text": "Input: n = 2, m = 2\nmat = {{0, 0}, \n {0, 0}}\nOutput: 0\nExplaination: There is no 1 in the matrix." }, { "code": null, "e": 876, "s": 650, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function maxSquare() which takes n, m and mat as input parameters and returns the size of the maximum square sub-matrix of given matrix." }, { "code": null, "e": 942, "s": 876, "text": "Expected Time Complexity: O(n*m)\nExpected Auxiliary Space: O(n*m)" }, { "code": null, "e": 988, "s": 942, "text": "Constraints:\n1 ≤ n, m ≤ 50\n0 ≤ mat[i][j] ≤ 1 " }, { "code": null, "e": 990, "s": 988, "text": "0" }, { "code": null, "e": 1015, "s": 990, "text": "vickyupadhyay361 day ago" }, { "code": null, "e": 1110, "s": 1015, "text": "giving error in one test case while submitting, but passing for same test case in custom input" }, { "code": null, "e": 1702, "s": 1110, "text": "int maxSquare(int n, int m, vector<vector<int>> mat){\n // code here\n vector<vector<int>> t(n,vector<int>(m,0));\n int mx=0;\n for(int i=n-1;i>=0;i--){\n for(int j=m-1;j>=0;j--){\n if(mat[i][j]==1){\n if(i==n-1 || j==n-1){//last row or last column\n t[i][j]=1;\n }\n else{\n t[i][j]=1+min(t[i][j+1],min(t[i+1][j+1],t[i+1][j]));\n }\n }\n mx=max(mx,t[i][j]);\n }\n }\n \n return mx;\n }" }, { "code": null, "e": 1704, "s": 1702, "text": "0" }, { "code": null, "e": 1731, "s": 1704, "text": "tanishqspike1143 weeks ago" }, { "code": null, "e": 1752, "s": 1731, "text": "C++| Simple DP Logic" }, { "code": null, "e": 2179, "s": 1752, "text": "class Solution{\npublic:\n int maxSquare(int n, int m, vector<vector<int>> mat){\n vector<vector<int>> dp(n+1,vector<int>(m+1));\n int ans=0;\n for(int i=1;i<=n;i++){\n for(int j=1;j<=m;j++){\n if(mat[i-1][j-1]==1)\n dp[i][j]=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;\n ans=max(ans,dp[i][j]);\n }\n }\n return ans;\n }\n};" }, { "code": null, "e": 2183, "s": 2181, "text": "0" }, { "code": null, "e": 2211, "s": 2183, "text": "sharadyaduvanshi3 weeks ago" }, { "code": null, "e": 3294, "s": 2211, "text": " int maxSquare(int n, int m, vector<vector<int>> mat){ // code here // for(int i = 0 ; i < n; i ++) // { // for(int j = 0; j < m; j ++) // { // mat[i][j] = 1 - mat[i][j]; // } // } int **dp = new int*[n+1]; for(int i = 0 ; i< n; i ++) { dp[i] = new int[m+1]; for(int j = 0; j < m; j ++) { // if(i == n-1 || j == m-1) // dp[i][j] = mat[i][j]; // if(mat[i][j] == 0) dp[i][j] = mat[i][j]; } } for(int i = n-2 ; i>= 0; i --) { //dp[i] = new int[m+1]; for(int j = m-2; j >=0 ; j --) { if(j+1 < m && i+1<n &&mat[i][j] == 1) dp[i][j] = dp[i][j]+min(dp[i][j+1],min(dp[i+1][j],dp[i+1][j+1])); } } int ans = INT_MIN; for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { ans = max(ans,dp[i][j]); } } return ans; }" }, { "code": null, "e": 3296, "s": 3294, "text": "0" }, { "code": null, "e": 3321, "s": 3296, "text": "jainmuskan5653 weeks ago" }, { "code": null, "e": 4878, "s": 3321, "text": "// int helpSolve(int n,int m, vector<vector<int>> mat, vector<vector<int>>& dp){ // int r= n, c= m; // // if(n>=r || m>=c){ // // return 0; // // } // // if(dp[n][m]!= -1){ // // return dp[n][m]; // // } // // int right= helpSolve(n,m+1,mat,dp); // dp[n][m+1]; // // int down= helpSolve(n+1,m,mat,dp); // dp[n+1][m]; // // int diag= helpSolve(n+1,m+1,mat,dp); // dp[n+1][m+1]; // // dp[n][m]=0; // // if(mat[n][m]==1){ // // dp[n][m]=1+min({right,down,diag}); // // } // // // int ans=INT_MIN; // // // for(int i=0;i<n;i++){ // // // for(int j=0;j<m;j++){ // // // ans=max(ans,dp[i][j]); // // // } // // // } // return dp[n][m]; // } int maxSquare(int n, int m, vector<vector<int>> mat){ vector<vector<int>>dp(n+1,vector<int>(m+1)); int r=n, c=m; for(int i=0;i<=r;i++){ for(int j=0;j<=c;j++){ if(i==0||j==0){ dp[i][j]=0; } } } for(int i=1;i<=r;i++){ for(int j=1;j<=c;j++){ if(mat[i-1][j-1]==1){ dp[i][j]= 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]}); } else if(mat[i-1][j-1]==0){ dp[i][j]=0; } } } int ans= dp[n][m]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ ans=max(ans,dp[i][j]); } } return ans; }" }, { "code": null, "e": 4880, "s": 4878, "text": "0" }, { "code": null, "e": 4910, "s": 4880, "text": "khushiaggarwal09021 month ago" }, { "code": null, "e": 4928, "s": 4910, "text": "//Easiest approch" }, { "code": null, "e": 4964, "s": 4928, "text": "(According to Aditya Verma approch)" }, { "code": null, "e": 5806, "s": 4964, "text": "int maxSquare(int n, int m, vector<vector<int>> mat) { int dp[n+1][m+1]; int ans=INT_MIN; for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { if(i==0 || j==0) { dp[i][j]=0; } } } for(int i=1;i<n+1;i++) for(int j=1;j<m+1;j++) { if(mat[i-1][j-1]==1) { dp[i][j] = 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]}); } else if(mat[i-1][j-1]==0) { dp[i][j]=0; } } for(int i=1;i<n+1;i++) for(int j=1;j<m+1;j++) { if(dp[i][j]>ans) { ans=dp[i][j]; } } return ans; }" }, { "code": null, "e": 5808, "s": 5806, "text": "0" }, { "code": null, "e": 5829, "s": 5808, "text": "aasif23641 month ago" }, { "code": null, "e": 6549, "s": 5829, "text": "class Solution{public: int maxSquare(int n, int m, vector<vector<int>> mat){ vector<vector<int>>dp(n , vector<int>(m , 0)); int res=0; for(int i=n-1 ; i>=0 ; i--){ for(int j=m-1 ; j>=0 ; j--){ if(i==n-1 and j==m-1){ dp[i][j]=mat[i][j]; } else if(i==n-1){ dp[i][j]=mat[i][j]; } else if(j==m-1){ dp[i][j]=mat[i][j]; } else if(mat[i][j]==1){ dp[i][j]=min({dp[i][j+1] , dp[i+1][j] , dp[i+1][j+1]}) + 1; } res=max(res , dp[i][j]); } } return res; }};" }, { "code": null, "e": 6551, "s": 6549, "text": "0" }, { "code": null, "e": 6575, "s": 6551, "text": "yashgehi3982 months ago" }, { "code": null, "e": 7053, "s": 6575, "text": "class Solution{\npublic:\n int maxSquare(int n, int m, vector<vector<int>> mat){\n // code here\n vector<vector<int>> dp(n+1,vector<int>(m+1,0));\n int size =0;\n for(int i{1};i<=n;i++){\n for(int j{1};j<=m;j++){\n if(mat[i-1][j-1] == 0) dp[i][j] =0;\n else dp[i][j] = 1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]));\n size = max(size,dp[i][j]);\n }\n }\n return size;\n }\n};\n" }, { "code": null, "e": 7055, "s": 7053, "text": "0" }, { "code": null, "e": 7083, "s": 7055, "text": "artistdarkangel2 months ago" }, { "code": null, "e": 7099, "s": 7083, "text": "JAVA Solution -" }, { "code": null, "e": 7144, "s": 7099, "text": "Time Complexity: O(n*m)Auxiliary Space: O(1)" }, { "code": null, "e": 7892, "s": 7144, "text": "class Solution{ static int maxSquare(int n, int m, int mat[][]){ int max=0; if(n==0 || m==0) return 0; for(int i=n-1; i>=0; i--) { for(int j=m-1; j>=0; j--) { if(mat[i][j]==1) { max=1; break; } } if(max==1) break; } for(int i=n-2; i>=0; i--) { for(int j=m-2; j>=0; j--) { if(mat[i][j]==1) { mat[i][j]=Math.min(Math.min(mat[i+1][j], mat[i][j+1]),mat[i+1][j+1])+1; if(mat[i][j]>max) max=mat[i][j]; } } } return max; }}" }, { "code": null, "e": 7896, "s": 7894, "text": "0" }, { "code": null, "e": 7924, "s": 7896, "text": "sharma_nitin_262 months ago" }, { "code": null, "e": 8571, "s": 7924, "text": "class Solution{\npublic:\n int maxSquare(int n, int m, vector<vector<int>> v){\n int ans=0;\n int a[n][m];\n \n for(int i=0;i<n;i++)\n for(int j=0;j<m;j++){\n if(i==0 || j==0){\n a[i][j]=v[i][j];\n if(ans<a[i][j])\n ans=a[i][j];\n }\n else if(v[i][j]==1){\n a[i][j]=min({a[i][j-1],a[i-1][j],a[i-1][j-1]})+1;\n if(ans<a[i][j])\n ans=a[i][j];\n }\n else\n a[i][j]=0;\n }\n return ans;\n }\n};" }, { "code": null, "e": 8573, "s": 8571, "text": "0" }, { "code": null, "e": 8595, "s": 8573, "text": "lindan1232 months ago" }, { "code": null, "e": 9245, "s": 8595, "text": "int maxSquare(int n, int m, vector<vector<int>> mat){\n int dp[n+1][m+1];\n int ans=INT_MIN;\n for(int i=0;i<=n;i++)\n {\n for(int j=0;j<=m;j++)\n {\n if(i==0 || j==0)\n {\n dp[i][j]=0;\n }\n else if(mat[i-1][j-1]==1)\n {\n dp[i][j] = 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]});\n }\n else if(mat[i-1][j-1]==0)\n {\n dp[i][j]=0;\n }\n ans = max(ans,dp[i][j]);\n }\n }\n return ans;\n }" }, { "code": null, "e": 9262, "s": 9245, "text": "Time Taken : 0.0" }, { "code": null, "e": 9266, "s": 9262, "text": "Cpp" }, { "code": null, "e": 9412, "s": 9266, "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": 9448, "s": 9412, "text": " Login to access your submissions. " }, { "code": null, "e": 9458, "s": 9448, "text": "\nProblem\n" }, { "code": null, "e": 9468, "s": 9458, "text": "\nContest\n" }, { "code": null, "e": 9531, "s": 9468, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9679, "s": 9531, "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": 9887, "s": 9679, "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": 9993, "s": 9887, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How can I test if a string starts with a capital letter using Python?
To be precise, above string four words starting with uppercase character. This, Delhi, City and India. Two string functions should be used for this purpose. Assuming that words in the string are separated by single space character, split() function gives list of words. Secondly to check if first character of each word is uppercase, use isupper() function. Following code lists words starting with capital letters. s1="This is not true that Delhi is the hottest or coldest City in India" for word in s1.split(): if word[0].isupper(): print (word) The output is: This Delhi City India
[ { "code": null, "e": 1165, "s": 1062, "text": "To be precise, above string four words starting with uppercase character. This, Delhi, City and India." }, { "code": null, "e": 1332, "s": 1165, "text": "Two string functions should be used for this purpose. Assuming that words in the string are separated by single space character, split() function gives list of words." }, { "code": null, "e": 1420, "s": 1332, "text": "Secondly to check if first character of each word is uppercase, use isupper() function." }, { "code": null, "e": 1478, "s": 1420, "text": "Following code lists words starting with capital letters." }, { "code": null, "e": 1622, "s": 1478, "text": "s1=\"This is not true that Delhi is the hottest or coldest City in India\"\nfor word in s1.split():\n if word[0].isupper():\n print (word)" }, { "code": null, "e": 1637, "s": 1622, "text": "The output is:" }, { "code": null, "e": 1659, "s": 1637, "text": "This\nDelhi\nCity\nIndia" } ]
MFC - Windows Resources
A resource is a text file that allows the compiler to manage objects such as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual Studio makes creating a resource file particularly easy by providing the necessary tools in the same environment used to program. This means, you usually do not have to use an external application to create or configure a resource file. Following are some important features related to resources. Resources are interface elements that provide information to the user. Resources are interface elements that provide information to the user. Bitmaps, icons, toolbars, and cursors are all resources. Bitmaps, icons, toolbars, and cursors are all resources. Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box. Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box. An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension. An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension. Most resources are created by selecting the desired one from the Add Resource dialog box. Most resources are created by selecting the desired one from the Add Resource dialog box. The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program. The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program. An identifier is a symbol which is a constant integer whose name usually starts with ID. It consists of two parts − a text string (symbol name) mapped to an integer value (symbol value). Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors. Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors. When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it. When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it. The name-plus-value definition is stored in the Resource.h file. The name-plus-value definition is stored in the Resource.h file. Step 1 − Let us look into our CMFCDialogDemo example from the last chapter in which we have created a dialog box and its ID is IDD_EXAMPLE_DLG. Step 2 − Go to the Solution Explorer, you will see the resource.h file under Header Files. Continue by opening this file in editor and you will see the dialog box identifier and its integer value as well. An icon is a small picture used on a window which represents an application. It is used in two main scenarios. On a Window's frame, it is displayed on the left side of the Window name on the title bar. On a Window's frame, it is displayed on the left side of the Window name on the title bar. In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window. In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window. If you look at our MFCModalDemo example, you will see that Visual studio was using a default icon for the title bar as shown in the following snapshot. You can create your own icon by following the steps given below − Step 1 − Right-click on your project and select Add → Resources, you will see the Add Resources dialog box. Step 2 − Select Icon and click New button and you will see the following icon. Step 3 − In Solution Explorer, go to Resource View and expand MFCModalDemo > Icon. You will see two icons. The IDR_MAINFRAME is the default one and IDI_ICON1 is the newly created icon. Step 4 − Right-click on the newly Created icon and select Properties. Step 5 − IDI_ICON1 is the ID of this icon, now Let us change this ID to IDR_MYICON. Step 6 − You can now change this icon in the designer as per your requirements. We will use the same icon. Step 7 − Save this icon. Step 8 − Go to the CMFCModalDemoDlg constructor in CMFCModalDemoDlg.cpp file which will look like the following code. CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/) : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) { m_hIcon = AfxGetApp() -> LoadIcon(IDR_MAINFRAME); } Step 9 − You can now see that the default icon is loaded in the constructor. Let us change it to IDR_ MYICON as shown in the following code. CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/) : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) { m_hIcon = AfxGetApp() -> LoadIcon(IDR_ MYICON); } Step 10 − When the above code is compiled and executed, you will see the new icon is displayed on the dialog box. Menus allow you to arrange commands in a logical and easy-to-find fashion. With the Menu editor, you can create and edit menus by working directly with a menu bar that closely resembles the one in your finished application. To create a menu, follow the steps given below − Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box. Step 2 − Select Menu and click New. You will see the rectangle that contains "Type Here" on the menu bar. Step 3 − Write some menu options like File, Edit, etc. as shown in the following snapshot. Step 4 − If you expand the Menu folder in Resource View, you will see the Menu identifier IDR_MENU1. Right-click on this identifier and change it to IDM_MAINMENU. Step 5 − Save all the changes. Step 6 − We need to attach this menu to our dialog box. Expand your Dialog folder in Solution Explorer and double click on the dialog box identifier. Step 7 − You will see the menu field in the Properties. Select the Menu identifier from the dropdown as shown above. Step 8 − Run this application and you will see the following dialog box which also contains menu options. A toolbar is a Windows control that allows the user to perform some actions on a form by clicking a button instead of using a menu. A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons. A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons. A toolbar can bring such common actions closer to the user. A toolbar can bring such common actions closer to the user. Toolbars usually display under the main menu. Toolbars usually display under the main menu. They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption. They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption. Toolbars can also be equipped with other types of controls. Toolbars can also be equipped with other types of controls. To create a toolbar, following are the steps. Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box. Step 2 − Select Toolbar and click New. You will see the following screen. Step 3 − Design your toolbar in the designer as shown in the following screenshot and specify the IDs as well. Step 4 − Add these two variables in CMFCModalDemoDlg class. CToolBar m_wndToolBar; BOOL butD; Step 5 − Following is the complete implementation of CMFCModalDemoDlg in CMFCModalDemoDlg.h file − class CMFCModalDemoDlg : public CDialogEx { // Construction public: CMFCModalDemoDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_MFCMODALDEMO_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; CToolBar m_wndToolBar; BOOL butD; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); }; Step 6 − Update CMFCModalDemoDlg::OnInitDialog() as shown in the following code. BOOL CMFCModalDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon if (!m_wndToolBar.Create(this) || !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1)) //if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | // WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | // CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || // !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1)) { TRACE0("Failed to Create Dialog Toolbar\n"); EndDialog(IDCANCEL); } butD = TRUE; CRect rcClientOld; // Old Client Rect CRect rcClientNew; // New Client Rect with Tollbar Added // Retrive the Old Client WindowSize // Called to reposition and resize control bars in the client area of a window // The reposQuery FLAG does not really traw the Toolbar. It only does the calculations. // And puts the new ClientRect values in rcClientNew so we can do the rest of the Math. GetClientRect(rcClientOld); RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, rcClientNew); // All of the Child Windows (Controls) now need to be moved so the Tollbar does not cover them up. // Offest to move all child controls after adding Tollbar CPoint ptOffset(rcClientNew.left - rcClientOld.left, rcClientNew.top - rcClientOld.top); CRect rcChild; CWnd* pwndChild = GetWindow(GW_CHILD); //Handle to the Dialog Controls while (pwndChild) // Cycle through all child controls { pwndChild -> GetWindowRect(rcChild); // Get the child control RECT ScreenToClient(rcChild); // Changes the Child Rect by the values of the claculated offset rcChild.OffsetRect(ptOffset); pwndChild -> MoveWindow(rcChild, FALSE); // Move the Child Control pwndChild = pwndChild -> GetNextWindow(); } CRect rcWindow; // Get the RECT of the Dialog GetWindowRect(rcWindow); // Increase width to new Client Width rcWindow.right += rcClientOld.Width() - rcClientNew.Width(); // Increase height to new Client Height rcWindow.bottom += rcClientOld.Height() - rcClientNew.Height(); // Redraw Window MoveWindow(rcWindow, FALSE); // Now we REALLY Redraw the Toolbar RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } Step 7 − Run this application. You will see the following dialog box which also contains the toolbar. An access key is a letter that allows the user to perform a menu action faster by using the keyboard instead of the mouse. This is usually faster because the user would not need to position the mouse anywhere, which reduces the time it takes to perform the action. Step 1 − To create an access key, type an ampersand "&" on the left of the menu item. Step 2 − Repeat this step for all menu options. Run this application and press Alt. You will see that the first letter of all menu options are underlined. A shortcut key is a key or a combination of keys used by advanced users to perform an action that would otherwise be done on a menu item. Most shortcuts are a combination of the Ctrl key simultaneously pressed with a letter key. For example, Ctrl + N, Ctrl + O, or Ctrl + D. To create a shortcut, on the right side of the string that makes up a menu caption, rightclick on the menu item and select properties. In the Caption field type \t followed by the desired combination as shown below for the New menu option. Repeat the step for all menu options. An Accelerator Table is a list of items where each item of the table combines an identifier, a shortcut key, and a constant number that specifies the kind of accelerator key. Just like the other resources, an accelerator table can be created manually in a .rc file. Following are the steps to create an accelerator table. Step 1 − To create an accelerator table, right-click on *.rc file in the solution explorer. Step 2 − Select Accelerator and click New. Step 3 − Click the arrow of the ID combo box and select menu Items. Step 4 − Select Ctrl from the Modifier dropdown. Step 5 − Click the Key box and type the respective Keys for both menu options. We will also add New menu item event handler to testing. Right-click on the New menu option. Step 6 − You can specify a class, message type and handler name. For now, let us leave it as it is and click Add and Edit button. Step 7 − Select Add Event Handler. Step 8 − You will now see the event added at the end of the CMFCModalDemoDlg.cpp file. void CMFCModalDemoDlg::OnFileNew() { // TODO: Add your command handler code here MessageBox(L"File > New menu option"); } Step 9 − Now Let us add a message box that will display the simple menu option message. To start accelerator table in working add the HACCEL variable and ProcessMessageFilter as shown in the following CMFCModalDemoApp. class CMFCModalDemoApp : public CWinApp { public: CMFCModalDemoApp(); // Overrides public: virtual BOOL InitInstance(); HACCEL m_hAccelTable; // Implementation DECLARE_MESSAGE_MAP() virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg); }; Step 10 − Load Accelerator and the following call in the CMFCModalDemoApp::InitInstance(). m_hAccelTable = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ACCELERATOR1)); Step 11 − Here is the implementation of ProcessMessageFilter. BOOL CMFCModalDemoApp::ProcessMessageFilter(int code, LPMSG lpMsg) { if (code >= 0 && m_pMainWnd && m_hAccelTable) { if (::TranslateAccelerator(m_pMainWnd -> m_hWnd, m_hAccelTable, lpMsg)) return TRUE; } return CWinApp::ProcessMessageFilter(code, lpMsg); } Step 12 − When the above code is compiled and executed, you will see the following output. Step 13 − Press Alt button followed by F key and then N key or Ctrl + N. You will see the following message. Print Add Notes Bookmark this page
[ { "code": null, "e": 2512, "s": 2067, "text": "A resource is a text file that allows the compiler to manage objects such as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual Studio makes creating a resource file particularly easy by providing the necessary tools in the same environment used to program. This means, you usually do not have to use an external application to create or configure a resource file. Following are some important features related to resources." }, { "code": null, "e": 2583, "s": 2512, "text": "Resources are interface elements that provide information to the user." }, { "code": null, "e": 2654, "s": 2583, "text": "Resources are interface elements that provide information to the user." }, { "code": null, "e": 2711, "s": 2654, "text": "Bitmaps, icons, toolbars, and cursors are all resources." }, { "code": null, "e": 2768, "s": 2711, "text": "Bitmaps, icons, toolbars, and cursors are all resources." }, { "code": null, "e": 2885, "s": 2768, "text": "Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box." }, { "code": null, "e": 3002, "s": 2885, "text": "Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box." }, { "code": null, "e": 3158, "s": 3002, "text": "An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension." }, { "code": null, "e": 3314, "s": 3158, "text": "An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension." }, { "code": null, "e": 3404, "s": 3314, "text": "Most resources are created by selecting the desired one from the Add Resource dialog box." }, { "code": null, "e": 3494, "s": 3404, "text": "Most resources are created by selecting the desired one from the Add Resource dialog box." }, { "code": null, "e": 3726, "s": 3494, "text": "The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program." }, { "code": null, "e": 3958, "s": 3726, "text": "The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program." }, { "code": null, "e": 4145, "s": 3958, "text": "An identifier is a symbol which is a constant integer whose name usually starts with ID. It consists of two parts − a text string (symbol name) mapped to an integer value (symbol value)." }, { "code": null, "e": 4318, "s": 4145, "text": "Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors." }, { "code": null, "e": 4491, "s": 4318, "text": "Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors." }, { "code": null, "e": 4656, "s": 4491, "text": "When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it." }, { "code": null, "e": 4821, "s": 4656, "text": "When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it." }, { "code": null, "e": 4886, "s": 4821, "text": "The name-plus-value definition is stored in the Resource.h file." }, { "code": null, "e": 4951, "s": 4886, "text": "The name-plus-value definition is stored in the Resource.h file." }, { "code": null, "e": 5095, "s": 4951, "text": "Step 1 − Let us look into our CMFCDialogDemo example from the last chapter in which we have created a dialog box and its ID is IDD_EXAMPLE_DLG." }, { "code": null, "e": 5300, "s": 5095, "text": "Step 2 − Go to the Solution Explorer, you will see the resource.h file under Header Files. Continue by opening this file in editor and you will see the dialog box identifier and its integer value as well." }, { "code": null, "e": 5411, "s": 5300, "text": "An icon is a small picture used on a window which represents an application. It is used in two main scenarios." }, { "code": null, "e": 5502, "s": 5411, "text": "On a Window's frame, it is displayed on the left side of the Window name on the title bar." }, { "code": null, "e": 5593, "s": 5502, "text": "On a Window's frame, it is displayed on the left side of the Window name on the title bar." }, { "code": null, "e": 5678, "s": 5593, "text": "In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window." }, { "code": null, "e": 5763, "s": 5678, "text": "In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window." }, { "code": null, "e": 5915, "s": 5763, "text": "If you look at our MFCModalDemo example, you will see that Visual studio was using a default icon for the title bar as shown in the following snapshot." }, { "code": null, "e": 5981, "s": 5915, "text": "You can create your own icon by following the steps given below −" }, { "code": null, "e": 6089, "s": 5981, "text": "Step 1 − Right-click on your project and select Add → Resources, you will see the Add Resources dialog box." }, { "code": null, "e": 6168, "s": 6089, "text": "Step 2 − Select Icon and click New button and you will see the following icon." }, { "code": null, "e": 6353, "s": 6168, "text": "Step 3 − In Solution Explorer, go to Resource View and expand MFCModalDemo > Icon. You will see two icons. The IDR_MAINFRAME is the default one and IDI_ICON1 is the newly created icon." }, { "code": null, "e": 6423, "s": 6353, "text": "Step 4 − Right-click on the newly Created icon and select Properties." }, { "code": null, "e": 6507, "s": 6423, "text": "Step 5 − IDI_ICON1 is the ID of this icon, now Let us change this ID to IDR_MYICON." }, { "code": null, "e": 6614, "s": 6507, "text": "Step 6 − You can now change this icon in the designer as per your requirements. We will use the same icon." }, { "code": null, "e": 6639, "s": 6614, "text": "Step 7 − Save this icon." }, { "code": null, "e": 6757, "s": 6639, "text": "Step 8 − Go to the CMFCModalDemoDlg constructor in CMFCModalDemoDlg.cpp file which will look like the following code." }, { "code": null, "e": 6925, "s": 6757, "text": "CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/)\n : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) {\n m_hIcon = AfxGetApp() -> LoadIcon(IDR_MAINFRAME);\n}" }, { "code": null, "e": 7066, "s": 6925, "text": "Step 9 − You can now see that the default icon is loaded in the constructor. Let us change it to IDR_ MYICON as shown in the following code." }, { "code": null, "e": 7232, "s": 7066, "text": "CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/)\n : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) {\n m_hIcon = AfxGetApp() -> LoadIcon(IDR_ MYICON);\n}" }, { "code": null, "e": 7346, "s": 7232, "text": "Step 10 − When the above code is compiled and executed, you will see the new icon is displayed on the dialog box." }, { "code": null, "e": 7619, "s": 7346, "text": "Menus allow you to arrange commands in a logical and easy-to-find fashion. With the Menu editor, you can create and edit menus by working directly with a menu bar that closely resembles the one in your finished application. To create a menu, follow the steps given below −" }, { "code": null, "e": 7727, "s": 7619, "text": "Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box." }, { "code": null, "e": 7833, "s": 7727, "text": "Step 2 − Select Menu and click New. You will see the rectangle that contains \"Type Here\" on the menu bar." }, { "code": null, "e": 7924, "s": 7833, "text": "Step 3 − Write some menu options like File, Edit, etc. as shown in the following snapshot." }, { "code": null, "e": 8087, "s": 7924, "text": "Step 4 − If you expand the Menu folder in Resource View, you will see the Menu identifier IDR_MENU1. Right-click on this identifier and change it to IDM_MAINMENU." }, { "code": null, "e": 8118, "s": 8087, "text": "Step 5 − Save all the changes." }, { "code": null, "e": 8268, "s": 8118, "text": "Step 6 − We need to attach this menu to our dialog box. Expand your Dialog folder in Solution Explorer and double click on the dialog box identifier." }, { "code": null, "e": 8385, "s": 8268, "text": "Step 7 − You will see the menu field in the Properties. Select the Menu identifier from the dropdown as shown above." }, { "code": null, "e": 8491, "s": 8385, "text": "Step 8 − Run this application and you will see the following dialog box which also contains menu options." }, { "code": null, "e": 8623, "s": 8491, "text": "A toolbar is a Windows control that allows the user to perform some actions on a form by clicking a button instead of using a menu." }, { "code": null, "e": 8755, "s": 8623, "text": "A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons." }, { "code": null, "e": 8887, "s": 8755, "text": "A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons." }, { "code": null, "e": 8947, "s": 8887, "text": "A toolbar can bring such common actions closer to the user." }, { "code": null, "e": 9007, "s": 8947, "text": "A toolbar can bring such common actions closer to the user." }, { "code": null, "e": 9053, "s": 9007, "text": "Toolbars usually display under the main menu." }, { "code": null, "e": 9099, "s": 9053, "text": "Toolbars usually display under the main menu." }, { "code": null, "e": 9202, "s": 9099, "text": "They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption." }, { "code": null, "e": 9305, "s": 9202, "text": "They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption." }, { "code": null, "e": 9365, "s": 9305, "text": "Toolbars can also be equipped with other types of controls." }, { "code": null, "e": 9425, "s": 9365, "text": "Toolbars can also be equipped with other types of controls." }, { "code": null, "e": 9471, "s": 9425, "text": "To create a toolbar, following are the steps." }, { "code": null, "e": 9579, "s": 9471, "text": "Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box." }, { "code": null, "e": 9653, "s": 9579, "text": "Step 2 − Select Toolbar and click New. You will see the following screen." }, { "code": null, "e": 9764, "s": 9653, "text": "Step 3 − Design your toolbar in the designer as shown in the following screenshot and specify the IDs as well." }, { "code": null, "e": 9824, "s": 9764, "text": "Step 4 − Add these two variables in CMFCModalDemoDlg class." }, { "code": null, "e": 9864, "s": 9824, "text": " CToolBar m_wndToolBar;\n BOOL butD;" }, { "code": null, "e": 9963, "s": 9864, "text": "Step 5 − Following is the complete implementation of CMFCModalDemoDlg in CMFCModalDemoDlg.h file −" }, { "code": null, "e": 10633, "s": 9963, "text": "class CMFCModalDemoDlg : public CDialogEx {\n // Construction\n public:\n CMFCModalDemoDlg(CWnd* pParent = NULL); // standard constructor\n // Dialog Data\n #ifdef AFX_DESIGN_TIME\n enum { IDD = IDD_MFCMODALDEMO_DIALOG };\n #endif\n\n protected:\n virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n \n // Implementation\n protected:\n HICON m_hIcon;\n CToolBar m_wndToolBar;\n BOOL butD;\n \n // Generated message map functions\n virtual BOOL OnInitDialog();\n afx_msg void OnPaint();\n afx_msg HCURSOR OnQueryDragIcon();\n DECLARE_MESSAGE_MAP()\n\t\n public:\n afx_msg void OnBnClickedOk();\n};" }, { "code": null, "e": 10714, "s": 10633, "text": "Step 6 − Update CMFCModalDemoDlg::OnInitDialog() as shown in the following code." }, { "code": null, "e": 13465, "s": 10714, "text": "BOOL CMFCModalDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n \n if (!m_wndToolBar.Create(this)\n || !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1))\n //if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD |\n // WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS |\n // CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||\n // !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1)) {\n TRACE0(\"Failed to Create Dialog Toolbar\\n\");\n EndDialog(IDCANCEL);\n }\n butD = TRUE;\n CRect rcClientOld; // Old Client Rect\n CRect rcClientNew; // New Client Rect with Tollbar Added\n\t\t\n // Retrive the Old Client WindowSize\n // Called to reposition and resize control bars in the client area of a window\n // The reposQuery FLAG does not really traw the Toolbar. It only does the calculations.\n // And puts the new ClientRect values in rcClientNew so we can do the rest of the Math.\n \n GetClientRect(rcClientOld);\n RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, rcClientNew);\n // All of the Child Windows (Controls) now need to be moved so the Tollbar does not cover them up.\n // Offest to move all child controls after adding Tollbar \n CPoint ptOffset(rcClientNew.left - rcClientOld.left, rcClientNew.top - rcClientOld.top); \n\t\t \n CRect rcChild;\n CWnd* pwndChild = GetWindow(GW_CHILD); //Handle to the Dialog Controls\n \n while (pwndChild) // Cycle through all child controls {\n pwndChild -> GetWindowRect(rcChild); // Get the child control RECT\n ScreenToClient(rcChild);\n \n // Changes the Child Rect by the values of the claculated offset\n rcChild.OffsetRect(ptOffset);\n pwndChild -> MoveWindow(rcChild, FALSE); // Move the Child Control\n pwndChild = pwndChild -> GetNextWindow();\n }\n \n CRect rcWindow;\n // Get the RECT of the Dialog\n GetWindowRect(rcWindow);\n \n // Increase width to new Client Width\n rcWindow.right += rcClientOld.Width() - rcClientNew.Width();\n \n // Increase height to new Client Height\n rcWindow.bottom += rcClientOld.Height() - rcClientNew.Height();\n // Redraw Window\n MoveWindow(rcWindow, FALSE);\n \n // Now we REALLY Redraw the Toolbar\n RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);\n \n // TODO: Add extra initialization here\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 13567, "s": 13465, "text": "Step 7 − Run this application. You will see the following dialog box which also contains the toolbar." }, { "code": null, "e": 13832, "s": 13567, "text": "An access key is a letter that allows the user to perform a menu action faster by using the keyboard instead of the mouse. This is usually faster because the user would not need to position the mouse anywhere, which reduces the time it takes to perform the action." }, { "code": null, "e": 13918, "s": 13832, "text": "Step 1 − To create an access key, type an ampersand \"&\" on the left of the menu item." }, { "code": null, "e": 14073, "s": 13918, "text": "Step 2 − Repeat this step for all menu options. Run this application and press Alt. You will see that the first letter of all menu options are underlined." }, { "code": null, "e": 14348, "s": 14073, "text": "A shortcut key is a key or a combination of keys used by advanced users to perform an action that would otherwise be done on a menu item. Most shortcuts are a combination of the Ctrl key simultaneously pressed with a letter key. For example, Ctrl + N, Ctrl + O, or Ctrl + D." }, { "code": null, "e": 14483, "s": 14348, "text": "To create a shortcut, on the right side of the string that makes up a menu caption, rightclick on the menu item and select properties." }, { "code": null, "e": 14626, "s": 14483, "text": "In the Caption field type \\t followed by the desired combination as shown below for the New menu option. Repeat the step for all menu options." }, { "code": null, "e": 14948, "s": 14626, "text": "An Accelerator Table is a list of items where each item of the table combines an identifier, a shortcut key, and a constant number that specifies the kind of accelerator key. Just like the other resources, an accelerator table can be created manually in a .rc file. Following are the steps to create an accelerator table." }, { "code": null, "e": 15040, "s": 14948, "text": "Step 1 − To create an accelerator table, right-click on *.rc file in the solution explorer." }, { "code": null, "e": 15083, "s": 15040, "text": "Step 2 − Select Accelerator and click New." }, { "code": null, "e": 15151, "s": 15083, "text": "Step 3 − Click the arrow of the ID combo box and select menu Items." }, { "code": null, "e": 15200, "s": 15151, "text": "Step 4 − Select Ctrl from the Modifier dropdown." }, { "code": null, "e": 15279, "s": 15200, "text": "Step 5 − Click the Key box and type the respective Keys for both menu options." }, { "code": null, "e": 15372, "s": 15279, "text": "We will also add New menu item event handler to testing. Right-click on the New menu option." }, { "code": null, "e": 15502, "s": 15372, "text": "Step 6 − You can specify a class, message type and handler name. For now, let us leave it as it is and click Add and Edit button." }, { "code": null, "e": 15537, "s": 15502, "text": "Step 7 − Select Add Event Handler." }, { "code": null, "e": 15624, "s": 15537, "text": "Step 8 − You will now see the event added at the end of the CMFCModalDemoDlg.cpp file." }, { "code": null, "e": 15752, "s": 15624, "text": "void CMFCModalDemoDlg::OnFileNew() {\n // TODO: Add your command handler code here\n MessageBox(L\"File > New menu option\");\n}" }, { "code": null, "e": 15840, "s": 15752, "text": "Step 9 − Now Let us add a message box that will display the simple menu option message." }, { "code": null, "e": 15971, "s": 15840, "text": "To start accelerator table in working add the HACCEL variable and ProcessMessageFilter as shown in the following CMFCModalDemoApp." }, { "code": null, "e": 16271, "s": 15971, "text": "class CMFCModalDemoApp : public CWinApp {\n public:\n CMFCModalDemoApp();\n \n // Overrides\n public:\n virtual BOOL InitInstance();\n HACCEL m_hAccelTable;\n \n // Implementation\n\n DECLARE_MESSAGE_MAP()\n virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);\n};" }, { "code": null, "e": 16362, "s": 16271, "text": "Step 10 − Load Accelerator and the following call in the CMFCModalDemoApp::InitInstance()." }, { "code": null, "e": 16458, "s": 16362, "text": "m_hAccelTable = LoadAccelerators(AfxGetInstanceHandle(),\n MAKEINTRESOURCE(IDR_ACCELERATOR1));" }, { "code": null, "e": 16520, "s": 16458, "text": "Step 11 − Here is the implementation of ProcessMessageFilter." }, { "code": null, "e": 16798, "s": 16520, "text": "BOOL CMFCModalDemoApp::ProcessMessageFilter(int code, LPMSG lpMsg) {\n if (code >= 0 && m_pMainWnd && m_hAccelTable) {\n if (::TranslateAccelerator(m_pMainWnd -> m_hWnd, m_hAccelTable, lpMsg))\n return TRUE;\n }\n return CWinApp::ProcessMessageFilter(code, lpMsg);\n}" }, { "code": null, "e": 16889, "s": 16798, "text": "Step 12 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 16998, "s": 16889, "text": "Step 13 − Press Alt button followed by F key and then N key or Ctrl + N. You will see the following message." }, { "code": null, "e": 17005, "s": 16998, "text": " Print" }, { "code": null, "e": 17016, "s": 17005, "text": " Add Notes" } ]
Argument Index in Java
Argument indices allow programmers to reorder the output. Let us see an example. Live Demo public class Demo { public static void main(String[] args) { System.out.printf("Before reordering = %s %s %s %s %s %s\n", "one", "two", "three", "four", "five", "six" ); System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s\n","one", "two", "three", "four", "five", "six" ); System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300); System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300); } } Before reordering = one two three four five six After reordering = six five four three two one Before reordering = 100 200 300 After reordering = 200 300 100 Above, we have reordered the output completely. Before ordering, we displayed normally. System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300); But, we changed the order and displayed it as − System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300);
[ { "code": null, "e": 1143, "s": 1062, "text": "Argument indices allow programmers to reorder the output. Let us see an example." }, { "code": null, "e": 1154, "s": 1143, "text": " Live Demo" }, { "code": null, "e": 1618, "s": 1154, "text": "public class Demo {\n public static void main(String[] args) {\n System.out.printf(\"Before reordering = %s %s %s %s %s %s\\n\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\" );\n System.out.printf(\"After reordering = %6$s %5$s %4$s %3$s %2$s %1$s\\n\",\"one\", \"two\", \"three\", \"four\", \"five\", \"six\" );\n System.out.printf(\"Before reordering = %d %d %d\\n\", 100, 200, 300);\n System.out.printf(\"After reordering = %2$d %3$d %1$d\\n\", 100, 200, 300);\n }\n}" }, { "code": null, "e": 1776, "s": 1618, "text": "Before reordering = one two three four five six\nAfter reordering = six five four three two one\nBefore reordering = 100 200 300\nAfter reordering = 200 300 100" }, { "code": null, "e": 1864, "s": 1776, "text": "Above, we have reordered the output completely. Before ordering, we displayed normally." }, { "code": null, "e": 1932, "s": 1864, "text": "System.out.printf(\"Before reordering = %d %d %d\\n\", 100, 200, 300);" }, { "code": null, "e": 1980, "s": 1932, "text": "But, we changed the order and displayed it as −" }, { "code": null, "e": 2053, "s": 1980, "text": "System.out.printf(\"After reordering = %2$d %3$d %1$d\\n\", 100, 200, 300);" } ]
How to find an element using the “CSS Selector” in Selenium?
We can find an element using the css locator with Selenium webdriver. To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression. With id, the format of a css expression should be tagname#<id>. For example,input#txt [here input is the tagname and the txt is the value of the id attribute]. With class, the format of css expression should be tagname.<class> . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]. If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). In the above code, if we want to identify the fourth li child of ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child. For attributes whose values are dynamically changing, we can use ^= to locate an element whose value starts with a particular text. For example, input[name^='qa'] [here input is the tagname and the value of the name attribute starts with qa]. For attributes whose values are dynamically changing, we can use =tolocateanelementwhosevalueendswithaparticulartext.Forexample,input[class='txt'] [here input is the tagname and the value of the class attribute ends with txt]. For attributes whose values are dynamically changing, we can use *= to locate an element whose value contains a specific sub-text. For example, input[name*='nam'] [here input is the tagname and the value of the name attribute contains the sub-text nam]. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class LocatorCss{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.linkedin.com/"); //identify element with css WebElement n = driver. findElement(By.cssSelector("input[id='session_key']")); n.sendKeys("Java"); String str = n.getAttribute("value"); System.out.println("Attribute value: " + str); driver.quit(); } }
[ { "code": null, "e": 1219, "s": 1062, "text": "We can find an element using the css locator with Selenium webdriver. To identify the element with css, the expression should be tagname[attribute='value']." }, { "code": null, "e": 1293, "s": 1219, "text": "We can also specifically use the id attribute to create a css expression." }, { "code": null, "e": 1453, "s": 1293, "text": "With id, the format of a css expression should be tagname#<id>. For example,input#txt [here input is the tagname and the txt is the value of the id attribute]." }, { "code": null, "e": 1630, "s": 1453, "text": "With class, the format of css expression should be tagname.<class> . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]." }, { "code": null, "e": 1762, "s": 1630, "text": "If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n)." }, { "code": null, "e": 2007, "s": 1762, "text": "In the above code, if we want to identify the fourth li child of ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child." }, { "code": null, "e": 2250, "s": 2007, "text": "For attributes whose values are dynamically changing, we can use ^= to locate an element whose value starts with a particular text. For example, input[name^='qa'] [here input is the tagname and the value of the name attribute starts with qa]." }, { "code": null, "e": 2477, "s": 2250, "text": "For attributes whose values are dynamically changing, we can use =tolocateanelementwhosevalueendswithaparticulartext.Forexample,input[class='txt'] [here input is the tagname and the value of the class attribute ends with txt]." }, { "code": null, "e": 2731, "s": 2477, "text": "For attributes whose values are dynamically changing, we can use *= to locate an element whose value contains a specific sub-text. For example, input[name*='nam'] [here input is the tagname and the value of the name attribute contains the sub-text nam]." }, { "code": null, "e": 3591, "s": 2731, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class LocatorCss{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.linkedin.com/\");\n //identify element with css\n WebElement n = driver.\n findElement(By.cssSelector(\"input[id='session_key']\"));\n n.sendKeys(\"Java\");\n String str = n.getAttribute(\"value\");\n System.out.println(\"Attribute value: \" + str);\n driver.quit();\n }\n}" } ]
JavaFX | FlowPane Class - GeeksforGeeks
12 Sep, 2018 FlowPane class is a part of JavaFX. Flowpane lays out its children in such a way that wraps at the flowpane’s boundary. A horizontal flowpane (the default) will layout nodes in rows, wrapping at the flowpane’s width. A vertical flowpane lays out nodes in columns, wrapping at the flowpane’s height. FlowPane class inherits Pane class. Constructors of the class: FlowPane(): Creates a new Horizontal FlowPane layout.FlowPane(double h, double v): Creates a new Horizontal FlowPane layout, with specified horizontal and vertical gap.FlowPane(double h, double v, Node... c): Creates a new Horizontal FlowPane layout, with specified horizontal, vertical gap and nodes.FlowPane(Node... c): Creates a FlowPane with specified childrens.FlowPane(Orientation o): Creates a FlowPane with specified orientationFlowPane(Orientation o, double h, double v): Creates a FlowPane with specified orientation and specified horizontal and vertical gap.FlowPane(Orientation o, double h, double v, Node... c): Creates a FlowPane with specified orientation and specified horizontal and vertical gap and specified childrens.FlowPane(Orientation o, Node... c): Creates a FlowPane with specified orientation and specified nodes. FlowPane(): Creates a new Horizontal FlowPane layout. FlowPane(double h, double v): Creates a new Horizontal FlowPane layout, with specified horizontal and vertical gap. FlowPane(double h, double v, Node... c): Creates a new Horizontal FlowPane layout, with specified horizontal, vertical gap and nodes. FlowPane(Node... c): Creates a FlowPane with specified childrens. FlowPane(Orientation o): Creates a FlowPane with specified orientation FlowPane(Orientation o, double h, double v): Creates a FlowPane with specified orientation and specified horizontal and vertical gap. FlowPane(Orientation o, double h, double v, Node... c): Creates a FlowPane with specified orientation and specified horizontal and vertical gap and specified childrens. FlowPane(Orientation o, Node... c): Creates a FlowPane with specified orientation and specified nodes. Commonly Used Methods: Below programs illustrate the use of FlowPane Class: Java Program to create a FlowPane, add labels to the flow pane and add it to the stage: In this program we will create a FlowPane and 5 Label named label, label1, label2, label3, label4. Add the labels to the flow_pane by passing it as the arguments. Set the FlowPane to the scene and add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane,// add labels to the flow pane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_0 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("FlowPane"); // create a labels Label label = new Label("this is FlowPane example"); Label label1 = new Label("label no 1"); Label label2 = new Label("label no 2"); Label label3 = new Label("label no 3"); Label label4 = new Label("label no 4"); // create a FlowPane FlowPane flow_pane = new FlowPane(20.0, 20.0, label, label1, label2, label3, label4); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a FlowPane set its orientation, add labels and buttons and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation and the hgap, and vgap values. Add the buttons using getChildren().add(). Set the FlowPane to the scene. Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane// set its orientation, add labels // and buttons and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FlowPane"); // create a label Label label = new Label("this is FlowPane example"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:Java Program to create a FlowPane set its orientation, add labels and buttons, set the alignment, column alignment, row alignment of the FlowPane and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation, and the hgap, and vgap values. Now add the buttons using getChildren().add(). Set the FlowPane to the scene. Set the alignment of the FlowPane using functions using setAlignment(), setColumnHalignment(), setRowValignment(). Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane set its orientation,// add labels and buttons, set the alignment, column // alignment, row alignment of the FlowPane and add it // to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FlowPane"); // create a label Label label = new Label("this is FlowPane example"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button("Button " + (int)(i + 1))); } // set alignment of flow pane flow_pane.setAlignment(Pos.CENTER); flow_pane.setColumnHalignment(HPos.CENTER); flow_pane.setRowValignment(VPos.CENTER); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output: Java Program to create a FlowPane, add labels to the flow pane and add it to the stage: In this program we will create a FlowPane and 5 Label named label, label1, label2, label3, label4. Add the labels to the flow_pane by passing it as the arguments. Set the FlowPane to the scene and add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane,// add labels to the flow pane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_0 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("FlowPane"); // create a labels Label label = new Label("this is FlowPane example"); Label label1 = new Label("label no 1"); Label label2 = new Label("label no 2"); Label label3 = new Label("label no 3"); Label label4 = new Label("label no 4"); // create a FlowPane FlowPane flow_pane = new FlowPane(20.0, 20.0, label, label1, label2, label3, label4); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: // Java Program to create a FlowPane,// add labels to the flow pane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_0 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("FlowPane"); // create a labels Label label = new Label("this is FlowPane example"); Label label1 = new Label("label no 1"); Label label2 = new Label("label no 2"); Label label3 = new Label("label no 3"); Label label4 = new Label("label no 4"); // create a FlowPane FlowPane flow_pane = new FlowPane(20.0, 20.0, label, label1, label2, label3, label4); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Java Program to create a FlowPane set its orientation, add labels and buttons and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation and the hgap, and vgap values. Add the buttons using getChildren().add(). Set the FlowPane to the scene. Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane// set its orientation, add labels // and buttons and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FlowPane"); // create a label Label label = new Label("this is FlowPane example"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output: // Java Program to create a FlowPane// set its orientation, add labels // and buttons and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FlowPane"); // create a label Label label = new Label("this is FlowPane example"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}} Output: Java Program to create a FlowPane set its orientation, add labels and buttons, set the alignment, column alignment, row alignment of the FlowPane and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation, and the hgap, and vgap values. Now add the buttons using getChildren().add(). Set the FlowPane to the scene. Set the alignment of the FlowPane using functions using setAlignment(), setColumnHalignment(), setRowValignment(). Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane set its orientation,// add labels and buttons, set the alignment, column // alignment, row alignment of the FlowPane and add it // to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FlowPane"); // create a label Label label = new Label("this is FlowPane example"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button("Button " + (int)(i + 1))); } // set alignment of flow pane flow_pane.setAlignment(Pos.CENTER); flow_pane.setColumnHalignment(HPos.CENTER); flow_pane.setRowValignment(VPos.CENTER); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output: // Java Program to create a FlowPane set its orientation,// add labels and buttons, set the alignment, column // alignment, row alignment of the FlowPane and add it // to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FlowPane"); // create a label Label label = new Label("this is FlowPane example"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button("Button " + (int)(i + 1))); } // set alignment of flow pane flow_pane.setAlignment(Pos.CENTER); flow_pane.setColumnHalignment(HPos.CENTER); flow_pane.setRowValignment(VPos.CENTER); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}} Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/FlowPane.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n12 Sep, 2018" }, { "code": null, "e": 23892, "s": 23557, "text": "FlowPane class is a part of JavaFX. Flowpane lays out its children in such a way that wraps at the flowpane’s boundary. A horizontal flowpane (the default) will layout nodes in rows, wrapping at the flowpane’s width. A vertical flowpane lays out nodes in columns, wrapping at the flowpane’s height. FlowPane class inherits Pane class." }, { "code": null, "e": 23919, "s": 23892, "text": "Constructors of the class:" }, { "code": null, "e": 24759, "s": 23919, "text": "FlowPane(): Creates a new Horizontal FlowPane layout.FlowPane(double h, double v): Creates a new Horizontal FlowPane layout, with specified horizontal and vertical gap.FlowPane(double h, double v, Node... c): Creates a new Horizontal FlowPane layout, with specified horizontal, vertical gap and nodes.FlowPane(Node... c): Creates a FlowPane with specified childrens.FlowPane(Orientation o): Creates a FlowPane with specified orientationFlowPane(Orientation o, double h, double v): Creates a FlowPane with specified orientation and specified horizontal and vertical gap.FlowPane(Orientation o, double h, double v, Node... c): Creates a FlowPane with specified orientation and specified horizontal and vertical gap and specified childrens.FlowPane(Orientation o, Node... c): Creates a FlowPane with specified orientation and specified nodes." }, { "code": null, "e": 24813, "s": 24759, "text": "FlowPane(): Creates a new Horizontal FlowPane layout." }, { "code": null, "e": 24929, "s": 24813, "text": "FlowPane(double h, double v): Creates a new Horizontal FlowPane layout, with specified horizontal and vertical gap." }, { "code": null, "e": 25063, "s": 24929, "text": "FlowPane(double h, double v, Node... c): Creates a new Horizontal FlowPane layout, with specified horizontal, vertical gap and nodes." }, { "code": null, "e": 25129, "s": 25063, "text": "FlowPane(Node... c): Creates a FlowPane with specified childrens." }, { "code": null, "e": 25200, "s": 25129, "text": "FlowPane(Orientation o): Creates a FlowPane with specified orientation" }, { "code": null, "e": 25334, "s": 25200, "text": "FlowPane(Orientation o, double h, double v): Creates a FlowPane with specified orientation and specified horizontal and vertical gap." }, { "code": null, "e": 25503, "s": 25334, "text": "FlowPane(Orientation o, double h, double v, Node... c): Creates a FlowPane with specified orientation and specified horizontal and vertical gap and specified childrens." }, { "code": null, "e": 25606, "s": 25503, "text": "FlowPane(Orientation o, Node... c): Creates a FlowPane with specified orientation and specified nodes." }, { "code": null, "e": 25629, "s": 25606, "text": "Commonly Used Methods:" }, { "code": null, "e": 25682, "s": 25629, "text": "Below programs illustrate the use of FlowPane Class:" }, { "code": null, "e": 31781, "s": 25682, "text": "Java Program to create a FlowPane, add labels to the flow pane and add it to the stage: In this program we will create a FlowPane and 5 Label named label, label1, label2, label3, label4. Add the labels to the flow_pane by passing it as the arguments. Set the FlowPane to the scene and add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane,// add labels to the flow pane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_0 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a labels Label label = new Label(\"this is FlowPane example\"); Label label1 = new Label(\"label no 1\"); Label label2 = new Label(\"label no 2\"); Label label3 = new Label(\"label no 3\"); Label label4 = new Label(\"label no 4\"); // create a FlowPane FlowPane flow_pane = new FlowPane(20.0, 20.0, label, label1, label2, label3, label4); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a FlowPane set its orientation, add labels and buttons and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation and the hgap, and vgap values. Add the buttons using getChildren().add(). Set the FlowPane to the scene. Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane// set its orientation, add labels // and buttons and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a label Label label = new Label(\"this is FlowPane example\"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:Java Program to create a FlowPane set its orientation, add labels and buttons, set the alignment, column alignment, row alignment of the FlowPane and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation, and the hgap, and vgap values. Now add the buttons using getChildren().add(). Set the FlowPane to the scene. Set the alignment of the FlowPane using functions using setAlignment(), setColumnHalignment(), setRowValignment(). Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane set its orientation,// add labels and buttons, set the alignment, column // alignment, row alignment of the FlowPane and add it // to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a label Label label = new Label(\"this is FlowPane example\"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // set alignment of flow pane flow_pane.setAlignment(Pos.CENTER); flow_pane.setColumnHalignment(HPos.CENTER); flow_pane.setRowValignment(VPos.CENTER); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:" }, { "code": null, "e": 33675, "s": 31781, "text": "Java Program to create a FlowPane, add labels to the flow pane and add it to the stage: In this program we will create a FlowPane and 5 Label named label, label1, label2, label3, label4. Add the labels to the flow_pane by passing it as the arguments. Set the FlowPane to the scene and add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane,// add labels to the flow pane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_0 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a labels Label label = new Label(\"this is FlowPane example\"); Label label1 = new Label(\"label no 1\"); Label label2 = new Label(\"label no 2\"); Label label3 = new Label(\"label no 3\"); Label label4 = new Label(\"label no 4\"); // create a FlowPane FlowPane flow_pane = new FlowPane(20.0, 20.0, label, label1, label2, label3, label4); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": "// Java Program to create a FlowPane,// add labels to the flow pane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_0 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a labels Label label = new Label(\"this is FlowPane example\"); Label label1 = new Label(\"label no 1\"); Label label2 = new Label(\"label no 2\"); Label label3 = new Label(\"label no 3\"); Label label4 = new Label(\"label no 4\"); // create a FlowPane FlowPane flow_pane = new FlowPane(20.0, 20.0, label, label1, label2, label3, label4); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 35195, "s": 33675, "text": null }, { "code": null, "e": 35203, "s": 35195, "text": "Output:" }, { "code": null, "e": 37089, "s": 35203, "text": "Java Program to create a FlowPane set its orientation, add labels and buttons and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation and the hgap, and vgap values. Add the buttons using getChildren().add(). Set the FlowPane to the scene. Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane// set its orientation, add labels // and buttons and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a label Label label = new Label(\"this is FlowPane example\"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:" }, { "code": "// Java Program to create a FlowPane// set its orientation, add labels // and buttons and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a label Label label = new Label(\"this is FlowPane example\"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}", "e": 38532, "s": 37089, "text": null }, { "code": null, "e": 38540, "s": 38532, "text": "Output:" }, { "code": null, "e": 40861, "s": 38540, "text": "Java Program to create a FlowPane set its orientation, add labels and buttons, set the alignment, column alignment, row alignment of the FlowPane and add it to the stage: In this program we will create a FlowPane and a Label named label. Add the label to the flow_pane by passing it through the argument, orientation, and the hgap, and vgap values. Now add the buttons using getChildren().add(). Set the FlowPane to the scene. Set the alignment of the FlowPane using functions using setAlignment(), setColumnHalignment(), setRowValignment(). Add the scene to the stage. Call the show() function to display the final results.// Java Program to create a FlowPane set its orientation,// add labels and buttons, set the alignment, column // alignment, row alignment of the FlowPane and add it // to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a label Label label = new Label(\"this is FlowPane example\"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // set alignment of flow pane flow_pane.setAlignment(Pos.CENTER); flow_pane.setColumnHalignment(HPos.CENTER); flow_pane.setRowValignment(VPos.CENTER); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:" }, { "code": "// Java Program to create a FlowPane set its orientation,// add labels and buttons, set the alignment, column // alignment, row alignment of the FlowPane and add it // to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.geometry.*;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.*;import javafx.scene.shape.*; public class FlowPane_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FlowPane\"); // create a label Label label = new Label(\"this is FlowPane example\"); // create a FlowPane FlowPane flow_pane = new FlowPane(Orientation.VERTICAL, 20.0, 20.0, label); // add buttons for (int i = 0; i < 10; i++) { // add nodes to the flow pane flow_pane.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // set alignment of flow pane flow_pane.setAlignment(Pos.CENTER); flow_pane.setColumnHalignment(HPos.CENTER); flow_pane.setRowValignment(VPos.CENTER); // create a scene Scene scene = new Scene(flow_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}", "e": 42551, "s": 40861, "text": null }, { "code": null, "e": 42559, "s": 42551, "text": "Output:" }, { "code": null, "e": 42647, "s": 42559, "text": "Note: The above programs might not run in an online IDE please use an offline compiler." }, { "code": null, "e": 42736, "s": 42647, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/FlowPane.html" }, { "code": null, "e": 42743, "s": 42736, "text": "JavaFX" }, { "code": null, "e": 42748, "s": 42743, "text": "Java" }, { "code": null, "e": 42753, "s": 42748, "text": "Java" }, { "code": null, "e": 42851, "s": 42753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42860, "s": 42851, "text": "Comments" }, { "code": null, "e": 42873, "s": 42860, "text": "Old Comments" }, { "code": null, "e": 42903, "s": 42873, "text": "Functional Interfaces in Java" }, { "code": null, "e": 42918, "s": 42903, "text": "Stream In Java" }, { "code": null, "e": 42939, "s": 42918, "text": "Constructors in Java" }, { "code": null, "e": 42985, "s": 42939, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 43004, "s": 42985, "text": "Exceptions in Java" }, { "code": null, "e": 43021, "s": 43004, "text": "Generics in Java" }, { "code": null, "e": 43064, "s": 43021, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 43080, "s": 43064, "text": "Strings in Java" }, { "code": null, "e": 43129, "s": 43080, "text": "How to remove an element from ArrayList in Java?" } ]
How to plot CSV data using Matplotlib and Pandas in Python?
To plot CSV data using Matplotlib and Pandas in Python, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Make a list of headers of the .CSV file. Read the CSV file with headers. Set the index and plot the dataframe. To display the figure, use show() method. import pandas as pd import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True headers = ['Name', 'Age', 'Marks'] df = pd.read_csv('student.csv', names=headers) df.set_index('Name').plot() plt.show()
[ { "code": null, "e": 1152, "s": 1062, "text": "To plot CSV data using Matplotlib and Pandas in Python, we can take the following steps −" }, { "code": null, "e": 1228, "s": 1152, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1269, "s": 1228, "text": "Make a list of headers of the .CSV file." }, { "code": null, "e": 1301, "s": 1269, "text": "Read the CSV file with headers." }, { "code": null, "e": 1339, "s": 1301, "text": "Set the index and plot the dataframe." }, { "code": null, "e": 1381, "s": 1339, "text": "To display the figure, use show() method." }, { "code": null, "e": 1646, "s": 1381, "text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nheaders = ['Name', 'Age', 'Marks']\n\ndf = pd.read_csv('student.csv', names=headers)\n\ndf.set_index('Name').plot()\n\nplt.show()" } ]
How to create focusable editText inside ListView on Android?
This example demonstrates how do I create a focusable editText inside ListView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="4dp" tools:context=".MainActivity"> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:descendantFocusability="beforeDescendants"> </ListView> </LinearLayout> Step 3 − Create a new layout resource file and add the following code− <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/ItemCaption" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginStart="2dip" android:singleLine="true"> </EditText> </LinearLayout> Step 4 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.LauncherActivity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView listView; MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.listView); listView.setItemsCanFocus(true); myAdapter = new MyAdapter(); listView.setAdapter(myAdapter); } private class MyAdapter extends BaseAdapter { private LayoutInflater layoutInflater; ArrayList<LauncherActivity.ListItem> myItems = new ArrayList<>(); MyAdapter() { layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); for (int i = 0; i < 7; i++) { LauncherActivity.ListItem listItem = new LauncherActivity.ListItem(); listItem.className = "Caption" + i; myItems.add(listItem); } notifyDataSetChanged(); } @Override public int getCount() { return myItems.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.listitem, null); holder.caption = convertView.findViewById(R.id.ItemCaption); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.caption.setText(myItems.get(position).className); holder.caption.setId(position); holder.caption.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { final int position = v.getId(); final EditText Caption = (EditText) v; myItems.get(position).className = Caption.getText().toString(); } } }); return convertView; } } class ViewHolder { EditText caption; } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.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" android:windowSoftInputMode="adjustPan"> <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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates how do I create a focusable editText inside ListView in android." }, { "code": null, "e": 1282, "s": 1153, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1899, "s": 1347, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:descendantFocusability=\"beforeDescendants\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 1970, "s": 1899, "text": "Step 3 − Create a new layout resource file and add the following code−" }, { "code": null, "e": 2433, "s": 1970, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/ItemCaption\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"2dip\"\n android:singleLine=\"true\">\n </EditText>\n</LinearLayout>" }, { "code": null, "e": 2490, "s": 2433, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5252, "s": 2490, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.annotation.SuppressLint;\nimport android.app.LauncherActivity;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n ListView listView;\n MyAdapter myAdapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n listView = findViewById(R.id.listView);\n listView.setItemsCanFocus(true);\n myAdapter = new MyAdapter();\n listView.setAdapter(myAdapter);\n }\n private class MyAdapter extends BaseAdapter {\n private LayoutInflater layoutInflater;\n ArrayList<LauncherActivity.ListItem> myItems = new ArrayList<>();\n MyAdapter() {\n layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n for (int i = 0; i < 7; i++) {\n LauncherActivity.ListItem listItem = new LauncherActivity.ListItem();\n listItem.className = \"Caption\" + i;\n myItems.add(listItem);\n }\n notifyDataSetChanged();\n }\n @Override\n public int getCount() {\n return myItems.size();\n }\n @Override\n public Object getItem(int position) {\n return position;\n }\n @Override\n public long getItemId(int position) {\n return position;\n }\n @SuppressLint(\"InflateParams\")\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n if (convertView == null) {\n holder = new ViewHolder();\n convertView = layoutInflater.inflate(R.layout.listitem, null);\n holder.caption = convertView.findViewById(R.id.ItemCaption);\n convertView.setTag(holder);\n } else {\n holder = (ViewHolder) convertView.getTag();\n }\n holder.caption.setText(myItems.get(position).className);\n holder.caption.setId(position);\n holder.caption.setOnFocusChangeListener(new View.OnFocusChangeListener() {\n public void onFocusChange(View v, boolean hasFocus) {\n if (!hasFocus) {\n final int position = v.getId();\n final EditText Caption = (EditText) v;\n myItems.get(position).className = Caption.getText().toString();\n }\n }\n });\n return convertView;\n }\n }\nclass ViewHolder {\n EditText caption;\n }\n}\n" }, { "code": null, "e": 5307, "s": 5252, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 6038, "s": 5307, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.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\" android:windowSoftInputMode=\"adjustPan\">\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": 6390, "s": 6038, "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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Machine Learning : Linear Regression using Pyspark | by Somesh Routray | Towards Data Science
Introduction: PySpark is the Python API written in python to support Apache Spark. Apache Spark is a distributed framework that can handle Big Data analysis. Spark is written in Scala and can be integrated with Python, Scala, Java, R, SQL languages. Spark is basically a computational engine, that works with huge sets of data by processing them in parallel and batch systems. When you down load spark binaries there will separate folders to support above langauges. There are basically two major types of algorithms — transformers : Transforms work with the input datasets and modify it to output datasets using a transform(). Estimators are the algorithms that take input datasets and produces a trained output model using fit(). In this section, I will be showing the machine learning implementation using Spark and Python. I will be focusing here basic ML algorithm Linear Regression implemented in the context of Spark. The program has been executed in the standalone server. First, import the libraries as shown below. And it is the most important to give the path of Spark binaries present in your system. Otherwise, you may face issues in executing codes. #"F:\DATA\SPARK\practice spark\Real estate.csv" import findspark import pyspark findspark.find() from pyspark.sql import SparkSession from pyspark.ml.feature import VectorAssembler from pyspark.ml.regression import LinearRegression import os import sys os.environ['SPARK_HOME']= r'C:\SPARK\spark-3.0.0-bin-hadoop2.7' if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("LinearReg_spark")\ .getOrCreate() dataset = spark.read.csv('Real estate.csv',header= True) dataset.show() +---+-------------------+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+ | No|X1 transaction date|X2 house age|X3 distance to the nearest MRT station|X4 number of convenience stores|X5 latitude|X6 longitude|Y house price of unit area| +---+-------------------+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+ | 1| 2012.917| 32| 84.87882| 10| 24.98298| 121.54024| 37.9| | 2| 2012.917| 19.5| 306.5947| 9| 24.98034| 121.53951| 42.2| | 3| 2013.583| 13.3| 561.9845| 5| 24.98746| 121.54391| 47.3| | 4| 2013.500| 13.3| 561.9845| 5| 24.98746| 121.54391| 54.8| | 5| 2012.833| 5| 390.5684| 5| 24.97937| 121.54245| 43.1| | 6| 2012.667| 7.1| 2175.03| 3| 24.96305| 121.51254| 32.1| | 7| 2012.667| 34.5| 623.4731| 7| 24.97933| 121.53642| 40.3| | 8| 2013.417| 20.3| 287.6025| 6| 24.98042| 121.54228| 46.7| | 9| 2013.500| 31.7| 5512.038| 1| 24.95095| 121.48458| 18.8| | 10| 2013.417| 17.9| 1783.18| 3| 24.96731| 121.51486| 22.1| | 11| 2013.083| 34.8| 405.2134| 1| 24.97349| 121.53372| 41.4| | 12| 2013.333| 6.3| 90.45606| 9| 24.97433| 121.5431| 58.1| | 13| 2012.917| 13| 492.2313| 5| 24.96515| 121.53737| 39.3| | 14| 2012.667| 20.4| 2469.645| 4| 24.96108| 121.51046| 23.8| | 15| 2013.500| 13.2| 1164.838| 4| 24.99156| 121.53406| 34.3| | 16| 2013.583| 35.7| 579.2083| 2| 24.9824| 121.54619| 50.5| | 17| 2013.250| 0| 292.9978| 6| 24.97744| 121.54458| 70.1| | 18| 2012.750| 17.7| 350.8515| 1| 24.97544| 121.53119| 37.4| | 19| 2013.417| 16.9| 368.1363| 8| 24.9675| 121.54451| 42.3| | 20| 2012.667| 1.5| 23.38284| 7| 24.96772| 121.54102| 47.7| +---+-------------------+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+ only showing top 20 rows colm = ['No','X1 transaction date'] df = dataset.select([column for column in dataset.columns if column not in colm]) df.printSchema() root |-- X2 house age: string (nullable = true) |-- X3 distance to the nearest MRT station: string (nullable = true) |-- X4 number of convenience stores: string (nullable = true) |-- X5 latitude: string (nullable = true) |-- X6 longitude: string (nullable = true) |-- Y house price of unit area: string (nullable = true) from pyspark.sql.functions import col df = df.select(*(col(c).cast('float').alias(c) for c in df.columns)) df.printSchema() root |-- X2 house age: float (nullable = true) |-- X3 distance to the nearest MRT station: float (nullable = true) |-- X4 number of convenience stores: float (nullable = true) |-- X5 latitude: float (nullable = true) |-- X6 longitude: float (nullable = true) |-- Y house price of unit area: float (nullable = true) from pyspark.sql.functions import col, count, isnan, when df.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns]).show() +------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+ |X2 house age|X3 distance to the nearest MRT station|X4 number of convenience stores|X5 latitude|X6 longitude|Y house price of unit area| +------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+ | 0| 0| 0| 0| 0| 0| +------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+ from functools import reduce oldColumns = df.schema.names newColumns = ['Age','Distance_2_MRT','Stores','Latitude','Longitude','Price'] df = reduce(lambda df, idx: df.withColumnRenamed(oldColumns[idx], newColumns[idx]),range(len(oldColumns)), df) df.printSchema() root |-- Age: float (nullable = true) |-- Distance_2_MRT: float (nullable = true) |-- Stores: float (nullable = true) |-- Latitude: float (nullable = true) |-- Longitude: float (nullable = true) |-- Price: float (nullable = true) df.show() +----+--------------+------+--------+---------+-----+ | Age|Distance_2_MRT|Stores|Latitude|Longitude|Price| +----+--------------+------+--------+---------+-----+ |32.0| 84.87882| 10.0|24.98298|121.54024| 37.9| |19.5| 306.5947| 9.0|24.98034|121.53951| 42.2| |13.3| 561.9845| 5.0|24.98746|121.54391| 47.3| |13.3| 561.9845| 5.0|24.98746|121.54391| 54.8| | 5.0| 390.5684| 5.0|24.97937|121.54245| 43.1| | 7.1| 2175.03| 3.0|24.96305|121.51254| 32.1| |34.5| 623.4731| 7.0|24.97933|121.53642| 40.3| |20.3| 287.6025| 6.0|24.98042|121.54228| 46.7| |31.7| 5512.038| 1.0|24.95095|121.48458| 18.8| |17.9| 1783.18| 3.0|24.96731|121.51486| 22.1| |34.8| 405.2134| 1.0|24.97349|121.53372| 41.4| | 6.3| 90.45606| 9.0|24.97433| 121.5431| 58.1| |13.0| 492.2313| 5.0|24.96515|121.53737| 39.3| |20.4| 2469.645| 4.0|24.96108|121.51046| 23.8| |13.2| 1164.838| 4.0|24.99156|121.53406| 34.3| |35.7| 579.2083| 2.0| 24.9824|121.54619| 50.5| | 0.0| 292.9978| 6.0|24.97744|121.54458| 70.1| |17.7| 350.8515| 1.0|24.97544|121.53119| 37.4| |16.9| 368.1363| 8.0| 24.9675|121.54451| 42.3| | 1.5| 23.38284| 7.0|24.96772|121.54102| 47.7| +----+--------------+------+--------+---------+-----+ only showing top 20 rows features = df.drop('Price') from pyspark.ml.feature import VectorAssembler #let's assemble our features together using vectorAssembler assembler = VectorAssembler( inputCols=features.columns, outputCol="features") output = assembler.transform(df).select('features','Price') train,test = output.randomSplit([0.75, 0.25]) train.show() +--------------------+-----+ | features|Price| +--------------------+-----+ |[0.0,185.42959594...| 37.9| |[0.0,185.42959594...| 45.5| |[0.0,185.42959594...| 52.2| |[0.0,185.42959594...| 55.2| |[0.0,208.39050292...| 44.0| |[0.0,208.39050292...| 45.7| |[0.0,274.01440429...| 43.5| |[0.0,274.01440429...| 45.4| |[0.0,274.01440429...| 52.2| |[0.0,292.99780273...| 63.3| |[0.0,292.99780273...| 69.7| |[0.0,292.99780273...| 70.1| |[0.0,292.99780273...| 73.6| |[0.0,338.96789550...| 44.9| |[0.0,338.96789550...| 50.8| |[1.0,193.58450317...| 50.7| |[1.10000002384185...| 45.1| |[1.10000002384185...| 48.6| |[1.10000002384185...| 49.0| |[1.10000002384185...| 54.4| +--------------------+-----+ only showing top 20 rows test.show() +--------------------+-----+ | features|Price| +--------------------+-----+ |[0.0,185.42959594...| 55.3| |[0.0,292.99780273...| 71.0| |[2.09999990463256...| 45.5| |[3.70000004768371...| 41.6| |[4.09999990463256...| 31.3| |[5.09999990463256...| 28.9| |[5.09999990463256...| 35.6| |[6.19999980926513...| 31.3| |[6.30000019073486...| 58.1| |[6.40000009536743...| 59.5| |[6.59999990463256...| 58.1| |[6.80000019073486...| 54.4| |[7.59999990463256...| 27.7| |[8.0,132.54690551...| 47.3| |[8.0,2216.6120605...| 23.9| |[8.10000038146972...| 51.6| |[8.5,104.81009674...| 56.8| |[9.0,1402.0159912...| 38.5| |[10.0,942.4663696...| 43.5| |[10.1000003814697...| 47.9| +--------------------+-----+ only showing top 20 rows from pyspark.ml.regression import LinearRegression lin_reg = LinearRegression(featuresCol = 'features', labelCol='Price') linear_model = lin_reg.fit(train) print("Coefficients: " + str(linear_model.coefficients)) print("\nIntercept: " + str(linear_model.intercept)) Coefficients: [-0.2845380180805475,-0.004727311005402087,1.187968326885585,201.55230488460887,-43.50846789357342] Intercept: 298.6774040798928 trainSummary = linear_model.summary print("RMSE: %f" % trainSummary.rootMeanSquaredError) print("\nr2: %f" % trainSummary.r2) RMSE: 9.110080 r2: 0.554706 from pyspark.sql.functions import abs predictions = linear_model.transform(test) x =((predictions['Price']-predictions['prediction'])/predictions['Price'])*100 predictions = predictions.withColumn('Accuracy',abs(x)) predictions.select("prediction","Price","Accuracy","features").show() +------------------+-----+-------------------+--------------------+ | prediction|Price| Accuracy| features| +------------------+-----+-------------------+--------------------+ | 43.12547834643925| 55.3| 22.01540878586896|[0.0,185.42959594...| | 50.46230673101314| 71.0| 28.926328547868813|[0.0,292.99780273...| | 47.46100355578261| 45.5| 4.309897924796947|[2.09999990463256...| | 46.8530780492884| 41.6| 12.62759559579116|[3.70000004768371...| |35.434011977095054| 31.3| 13.207708756553762|[4.09999990463256...| |39.619817126403234| 28.9| 37.09279463450084|[5.09999990463256...| | 39.33273298109731| 35.6| 10.485209738673646|[5.09999990463256...| |29.351057585089677| 31.3| 6.226650797049346|[6.19999980926513...| | 52.62887519936618| 58.1| 9.416735659970566|[6.30000019073486...| | 52.60042142469416| 59.5| 11.595930378665274|[6.40000009536743...| | 52.54351387534922| 58.1| 9.563657047679346|[6.59999990463256...| | 54.38035537626644| 54.4|0.03611424459818044|[6.80000019073486...| | 34.33264716981199| 27.7| 23.944571206461944|[7.59999990463256...| | 53.83264404188236| 47.3| 13.811088605057204|[8.0,132.54690551...| |34.562892118922775| 23.9| 44.61461368445082|[8.0,2216.6120605...| | 45.87250193662936| 51.6| 11.099799819498518|[8.10000038146972...| | 45.75868683793948| 56.8| 19.438930541247075|[8.5,104.81009674...| | 37.9322164579217| 38.5| 1.47476244695663|[9.0,1402.0159912...| | 38.51099156627248| 43.5| 11.468984905120735|[10.0,942.4663696...| | 48.37043980769164| 47.9| 0.9821258180097748|[10.1000003814697...| +------------------+-----+-------------------+--------------------+ only showing top 20 rows from pyspark.ml.evaluation import RegressionEvaluator pred_evaluator = RegressionEvaluator(predictionCol="prediction", \ labelCol="Price",metricName="r2") print("R Squared (R2) on test data = %g" % pred_evaluator.evaluate(predictions)) R Squared (R2) on test data = 0.610204 def adj_r2(x): r2 = trainSummary.r2 n = df.count() p = len(df.columns) adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1) return adjusted_r2 adj_r2(train) 0.548141210028837 adj_r2(test) 0.548141210028837 lin_reg = LinearRegression(featuresCol = 'features', labelCol='Price',maxIter=50, regParam=0.12, elasticNetParam=0.2) linear_model = lin_reg.fit(train) linear_model.summary.rootMeanSquaredError 9.110906766525105 features_rdd = features.rdd.map(lambda row: row[0:]) features_rdd.collect() [(32.0, 84.87882232666016, 10.0, 24.982980728149414, 121.54023742675781), (19.5, 306.5946960449219, 9.0, 24.98033905029297, 121.53951263427734), (13.300000190734863, 561.9844970703125, 5.0, 24.987459182739258, 121.54390716552734), (13.300000190734863, 561.9844970703125, 5.0, 24.987459182739258, 121.54390716552734), (5.0, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188), (7.099999904632568, 2175.030029296875, 3.0, 24.963050842285156, 121.51254272460938), (34.5, 623.4730834960938, 7.0, 24.97933006286621, 121.53642272949219), (20.299999237060547, 287.6025085449219, 6.0, 24.980419158935547, 121.54228210449219), (31.700000762939453, 5512.0380859375, 1.0, 24.950950622558594, 121.48458099365234), (17.899999618530273, 1783.1800537109375, 3.0, 24.967309951782227, 121.51486206054688), (34.79999923706055, 405.2134094238281, 1.0, 24.97348976135254, 121.53372192382812), (6.300000190734863, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (13.0, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (20.399999618530273, 2469.64501953125, 4.0, 24.96108055114746, 121.51045989990234), (13.199999809265137, 1164.8380126953125, 4.0, 24.991559982299805, 121.5340576171875), (35.70000076293945, 579.2083129882812, 2.0, 24.98240089416504, 121.54618835449219), (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461), (17.700000762939453, 350.85150146484375, 1.0, 24.975439071655273, 121.53118896484375), (16.899999618530273, 368.13629150390625, 8.0, 24.967500686645508, 121.54450988769531), (1.5, 23.38283920288086, 7.0, 24.96772003173828, 121.54102325439453), (4.5, 2275.876953125, 3.0, 24.9631404876709, 121.51151275634766), (10.5, 279.172607421875, 7.0, 24.97528076171875, 121.54541015625), (14.699999809265137, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (10.100000381469727, 279.172607421875, 7.0, 24.97528076171875, 121.54541015625), (39.599998474121094, 480.69769287109375, 4.0, 24.973529815673828, 121.53884887695312), (29.299999237060547, 1487.8680419921875, 2.0, 24.975419998168945, 121.51725769042969), (3.0999999046325684, 383.8623962402344, 5.0, 24.980850219726562, 121.54390716552734), (10.399999618530273, 276.4490051269531, 5.0, 24.955930709838867, 121.53913116455078), (19.200000762939453, 557.47802734375, 4.0, 24.97418975830078, 121.53797149658203), (7.099999904632568, 451.2438049316406, 5.0, 24.975629806518555, 121.54694366455078), (25.899999618530273, 4519.68994140625, 0.0, 24.948259353637695, 121.4958724975586), (29.600000381469727, 769.4033813476562, 7.0, 24.98280906677246, 121.5340805053711), (37.900001525878906, 488.57269287109375, 1.0, 24.97348976135254, 121.53450775146484), (16.5, 323.6549987792969, 6.0, 24.978410720825195, 121.54280853271484), (15.399999618530273, 205.36700439453125, 7.0, 24.984189987182617, 121.54242706298828), (13.899999618530273, 4079.41796875, 0.0, 25.014589309692383, 121.51815795898438), (14.699999809265137, 1935.009033203125, 2.0, 24.96385955810547, 121.51457977294922), (12.0, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (3.0999999046325684, 577.9614868164062, 6.0, 24.972009658813477, 121.5472183227539), (16.200000762939453, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (13.600000381469727, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (16.799999237060547, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875), (36.099998474121094, 519.461669921875, 5.0, 24.963050842285156, 121.53758239746094), (34.400001525878906, 512.787109375, 6.0, 24.98748016357422, 121.54300689697266), (2.700000047683716, 533.4761962890625, 4.0, 24.974449157714844, 121.54765319824219), (36.599998474121094, 488.8193054199219, 8.0, 24.970149993896484, 121.54493713378906), (21.700000762939453, 463.9623107910156, 9.0, 24.970300674438477, 121.5445785522461), (35.900001525878906, 640.7390747070312, 3.0, 24.975629806518555, 121.53714752197266), (24.200000762939453, 4605.7490234375, 0.0, 24.946840286254883, 121.49578094482422), (29.399999618530273, 4510.35888671875, 1.0, 24.949249267578125, 121.49542236328125), (21.700000762939453, 512.5487060546875, 4.0, 24.974000930786133, 121.53842163085938), (31.299999237060547, 1758.406005859375, 1.0, 24.95401954650879, 121.55281829833984), (32.099998474121094, 1438.5789794921875, 3.0, 24.97418975830078, 121.51750183105469), (13.300000190734863, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (16.100000381469727, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (31.700000762939453, 1160.6319580078125, 0.0, 24.94968032836914, 121.53009033203125), (33.599998474121094, 371.24951171875, 8.0, 24.9725399017334, 121.54058837890625), (3.5, 56.47425079345703, 7.0, 24.957439422607422, 121.537109375), (30.299999237060547, 4510.35888671875, 1.0, 24.949249267578125, 121.49542236328125), (13.300000190734863, 336.0531921386719, 5.0, 24.957759857177734, 121.53437805175781), (11.0, 1931.20703125, 2.0, 24.96364974975586, 121.51470947265625), (5.300000190734863, 259.66070556640625, 6.0, 24.975849151611328, 121.54515838623047), (17.200000762939453, 2175.876953125, 3.0, 24.963029861450195, 121.51254272460938), (2.5999999046325684, 533.4761962890625, 4.0, 24.974449157714844, 121.54765319824219), (17.5, 995.75537109375, 0.0, 24.963050842285156, 121.54914855957031), (40.099998474121094, 123.7428970336914, 8.0, 24.976350784301758, 121.54328918457031), (1.0, 193.58450317382812, 6.0, 24.965709686279297, 121.5408935546875), (8.5, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (30.399999618530273, 464.2229919433594, 6.0, 24.979639053344727, 121.53804779052734), (12.5, 561.9844970703125, 5.0, 24.987459182739258, 121.54390716552734), (6.599999904632568, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (35.5, 640.7390747070312, 3.0, 24.975629806518555, 121.53714752197266), (32.5, 424.544189453125, 8.0, 24.97587013244629, 121.53913116455078), (13.800000190734863, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (6.800000190734863, 379.5574951171875, 10.0, 24.983430862426758, 121.5376205444336), (12.300000190734863, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (35.900001525878906, 616.400390625, 3.0, 24.977230072021484, 121.53766632080078), (20.5, 2185.1279296875, 3.0, 24.963220596313477, 121.51236724853516), (38.20000076293945, 552.4370727539062, 2.0, 24.975980758666992, 121.5338134765625), (18.0, 1414.8370361328125, 1.0, 24.951820373535156, 121.54886627197266), (11.800000190734863, 533.4761962890625, 4.0, 24.974449157714844, 121.54765319824219), (30.799999237060547, 377.79559326171875, 6.0, 24.964269638061523, 121.53964233398438), (13.199999809265137, 150.9346923828125, 7.0, 24.96725082397461, 121.54251861572266), (25.299999237060547, 2707.39208984375, 3.0, 24.960559844970703, 121.50830841064453), (15.100000381469727, 383.2804870605469, 7.0, 24.967350006103516, 121.54463958740234), (0.0, 338.9678955078125, 9.0, 24.968530654907227, 121.54412841796875), (1.7999999523162842, 1455.7979736328125, 1.0, 24.951200485229492, 121.54900360107422), (16.899999618530273, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875), (8.899999618530273, 1406.4300537109375, 0.0, 24.985729217529297, 121.52758026123047), (23.0, 3947.945068359375, 0.0, 24.947830200195312, 121.50243377685547), (0.0, 274.014404296875, 1.0, 24.97480010986328, 121.53058624267578), (9.100000381469727, 1402.0159912109375, 0.0, 24.985689163208008, 121.52760314941406), (20.600000381469727, 2469.64501953125, 4.0, 24.96108055114746, 121.51045989990234), (31.899999618530273, 1146.3289794921875, 0.0, 24.949199676513672, 121.53076171875), (40.900001525878906, 167.59890747070312, 5.0, 24.966299057006836, 121.5402603149414), (8.0, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (6.400000095367432, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (28.399999618530273, 617.4423828125, 3.0, 24.977460861206055, 121.53298950195312), (16.399999618530273, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (6.400000095367432, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (17.5, 964.7495727539062, 4.0, 24.988719940185547, 121.53411102294922), (12.699999809265137, 170.12890625, 1.0, 24.973709106445312, 121.52983856201172), (1.100000023841858, 193.58450317382812, 6.0, 24.965709686279297, 121.5408935546875), (0.0, 208.3905029296875, 6.0, 24.956180572509766, 121.53843688964844), (32.70000076293945, 392.4458923339844, 6.0, 24.963979721069336, 121.5425033569336), (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461), (17.200000762939453, 189.51809692382812, 8.0, 24.977069854736328, 121.54308319091797), (12.199999809265137, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (31.399999618530273, 592.5006103515625, 2.0, 24.97260093688965, 121.53560638427734), (4.0, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961), (8.100000381469727, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (33.29999923706055, 196.61720275878906, 7.0, 24.97701072692871, 121.542236328125), (9.899999618530273, 2102.427001953125, 3.0, 24.960439682006836, 121.51461791992188), (14.800000190734863, 393.2605895996094, 6.0, 24.961719512939453, 121.53811645507812), (30.600000381469727, 143.8383026123047, 8.0, 24.981550216674805, 121.54141998291016), (20.600000381469727, 737.9160766601562, 2.0, 24.980920791625977, 121.54739379882812), (30.899999618530273, 6396.283203125, 1.0, 24.943750381469727, 121.47882843017578), (13.600000381469727, 4197.34912109375, 0.0, 24.93885040283203, 121.50382995605469), (25.299999237060547, 1583.7220458984375, 3.0, 24.96622085571289, 121.51708984375), (16.600000381469727, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (13.300000190734863, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (13.600000381469727, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (31.5, 414.9476013183594, 4.0, 24.981990814208984, 121.54463958740234), (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734), (9.899999618530273, 279.172607421875, 7.0, 24.97528076171875, 121.54541015625), (1.100000023841858, 193.58450317382812, 6.0, 24.965709686279297, 121.5408935546875), (38.599998474121094, 804.689697265625, 4.0, 24.97838020324707, 121.5347671508789), (3.799999952316284, 383.8623962402344, 5.0, 24.980850219726562, 121.54390716552734), (41.29999923706055, 124.99120330810547, 6.0, 24.966739654541016, 121.54039001464844), (38.5, 216.83290100097656, 7.0, 24.980859756469727, 121.54161834716797), (29.600000381469727, 535.5269775390625, 8.0, 24.980920791625977, 121.53652954101562), (4.0, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961), (26.600000381469727, 482.7580871582031, 5.0, 24.97433090209961, 121.53862762451172), (18.0, 373.3937072753906, 8.0, 24.986600875854492, 121.54081726074219), (33.400001525878906, 186.96859741210938, 6.0, 24.966039657592773, 121.54210662841797), (18.899999618530273, 1009.2349853515625, 0.0, 24.96356964111328, 121.54950714111328), (11.399999618530273, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188), (13.600000381469727, 319.07080078125, 6.0, 24.964950561523438, 121.54277038574219), (10.0, 942.4663696289062, 0.0, 24.978429794311523, 121.52406311035156), (12.899999618530273, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (16.200000762939453, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (5.099999904632568, 1559.8270263671875, 3.0, 24.972129821777344, 121.51627349853516), (19.799999237060547, 640.6071166992188, 5.0, 24.970169067382812, 121.54647064208984), (13.600000381469727, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (11.899999618530273, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (2.0999999046325684, 451.2438049316406, 5.0, 24.975629806518555, 121.54694366455078), (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734), (3.200000047683716, 489.8821105957031, 8.0, 24.970169067382812, 121.54493713378906), (16.399999618530273, 3780.590087890625, 0.0, 24.93292999267578, 121.51203155517578), (34.900001525878906, 179.45379638671875, 8.0, 24.97348976135254, 121.54244995117188), (35.79999923706055, 170.73109436035156, 7.0, 24.96718978881836, 121.54268646240234), (4.900000095367432, 387.7720947265625, 9.0, 24.98118019104004, 121.53787994384766), (12.0, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (6.5, 376.1708984375, 6.0, 24.954179763793945, 121.5371322631836), (16.899999618530273, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875), (13.800000190734863, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (30.700000762939453, 1264.72998046875, 0.0, 24.948829650878906, 121.529541015625), (16.100000381469727, 815.931396484375, 4.0, 24.97886085510254, 121.53463745117188), (11.600000381469727, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188), (15.5, 815.931396484375, 4.0, 24.97886085510254, 121.53463745117188), (3.5, 49.661048889160156, 8.0, 24.95836067199707, 121.53755950927734), (19.200000762939453, 616.400390625, 3.0, 24.977230072021484, 121.53766632080078), (16.0, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875), (8.5, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734), (13.699999809265137, 1236.56396484375, 1.0, 24.976940155029297, 121.55390930175781), (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461), (28.200000762939453, 330.08538818359375, 8.0, 24.974079132080078, 121.54010772705078), (27.600000381469727, 515.1121826171875, 5.0, 24.962989807128906, 121.54319763183594), (8.399999618530273, 1962.6280517578125, 1.0, 24.954679489135742, 121.5548095703125), (24.0, 4527.68701171875, 0.0, 24.947410583496094, 121.49627685546875), (3.5999999046325684, 383.8623962402344, 5.0, 24.980850219726562, 121.54390716552734), (6.599999904632568, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (41.29999923706055, 401.8807067871094, 4.0, 24.983259201049805, 121.54460144042969), (4.300000190734863, 432.03851318359375, 7.0, 24.980499267578125, 121.53778076171875), (30.200000762939453, 472.17449951171875, 3.0, 24.970050811767578, 121.53758239746094), (13.899999618530273, 4573.77880859375, 0.0, 24.94866943359375, 121.49507141113281), (33.0, 181.07659912109375, 9.0, 24.976970672607422, 121.54261779785156), (13.100000381469727, 1144.43603515625, 4.0, 24.99176025390625, 121.53456115722656), (14.0, 438.8512878417969, 1.0, 24.974929809570312, 121.52729797363281), (26.899999618530273, 4449.27001953125, 0.0, 24.9489803314209, 121.49620819091797), (11.600000381469727, 201.89390563964844, 8.0, 24.98488998413086, 121.54120635986328), (13.5, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961), (17.0, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (14.100000381469727, 2615.465087890625, 0.0, 24.9549503326416, 121.56173706054688), (31.399999618530273, 1447.2860107421875, 3.0, 24.972850799560547, 121.51730346679688), (20.899999618530273, 2185.1279296875, 3.0, 24.963220596313477, 121.51236724853516), (8.899999618530273, 3078.176025390625, 0.0, 24.954639434814453, 121.56626892089844), (34.79999923706055, 190.03919982910156, 8.0, 24.977069854736328, 121.54312133789062), (16.299999237060547, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875), (35.29999923706055, 616.573486328125, 8.0, 24.979450225830078, 121.53642272949219), (13.199999809265137, 750.0703735351562, 2.0, 24.973709106445312, 121.54950714111328), (43.79999923706055, 57.58945083618164, 7.0, 24.967500686645508, 121.54068756103516), (9.699999809265137, 421.47900390625, 5.0, 24.982460021972656, 121.54476928710938), (15.199999809265137, 3771.89501953125, 0.0, 24.933629989624023, 121.51158142089844), (15.199999809265137, 461.1015930175781, 5.0, 24.95425033569336, 121.53990173339844), (22.799999237060547, 707.9066772460938, 2.0, 24.981000900268555, 121.54712677001953), (34.400001525878906, 126.72859954833984, 8.0, 24.968809127807617, 121.5408935546875), (34.0, 157.60519409179688, 7.0, 24.966279983520508, 121.54196166992188), (18.200000762939453, 451.64190673828125, 8.0, 24.969449996948242, 121.5448989868164), (17.399999618530273, 995.75537109375, 0.0, 24.963050842285156, 121.54914855957031), (13.100000381469727, 561.9844970703125, 5.0, 24.987459182739258, 121.54390716552734), (38.29999923706055, 642.698486328125, 3.0, 24.975589752197266, 121.5371322631836), (15.600000381469727, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (18.0, 1414.8370361328125, 1.0, 24.951820373535156, 121.54886627197266), (12.800000190734863, 1449.7220458984375, 3.0, 24.972890853881836, 121.51728057861328), (22.200000762939453, 379.5574951171875, 10.0, 24.983430862426758, 121.5376205444336), (38.5, 665.0635986328125, 3.0, 24.97503089904785, 121.53691864013672), (11.5, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (34.79999923706055, 175.62939453125, 8.0, 24.97347068786621, 121.54270935058594), (5.199999809265137, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188), (0.0, 274.014404296875, 1.0, 24.97480010986328, 121.53058624267578), (17.600000381469727, 1805.6650390625, 2.0, 24.986719131469727, 121.52091217041016), (6.199999809265137, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (18.100000381469727, 1783.1800537109375, 3.0, 24.967309951782227, 121.51486206054688), (19.200000762939453, 383.712890625, 8.0, 24.972000122070312, 121.54476928710938), (37.79999923706055, 590.92919921875, 1.0, 24.97153091430664, 121.53559112548828), (28.0, 372.62420654296875, 6.0, 24.97838020324707, 121.54119110107422), (13.600000381469727, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (29.299999237060547, 529.777099609375, 8.0, 24.981019973754883, 121.53655242919922), (37.20000076293945, 186.51010131835938, 9.0, 24.97702980041504, 121.54264831542969), (9.0, 1402.0159912109375, 0.0, 24.985689163208008, 121.52760314941406), (30.600000381469727, 431.11138916015625, 10.0, 24.981229782104492, 121.53742980957031), (9.100000381469727, 1402.0159912109375, 0.0, 24.985689163208008, 121.52760314941406), (34.5, 324.94189453125, 6.0, 24.978139877319336, 121.54170227050781), (1.100000023841858, 193.58450317382812, 6.0, 24.965709686279297, 121.5408935546875), (16.5, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (32.400001525878906, 265.0609130859375, 8.0, 24.9805908203125, 121.53986358642578), (11.899999618530273, 3171.3291015625, 0.0, 25.001150131225586, 121.51776123046875), (31.0, 1156.4119873046875, 0.0, 24.94890022277832, 121.53095245361328), (4.0, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961), (16.200000762939453, 4074.736083984375, 0.0, 24.942350387573242, 121.50357055664062), (27.100000381469727, 4412.76513671875, 1.0, 24.950319290161133, 121.4958724975586), (39.70000076293945, 333.3678894042969, 9.0, 24.980159759521484, 121.53932189941406), (8.0, 2216.612060546875, 4.0, 24.96006965637207, 121.51361083984375), (12.899999618530273, 250.63099670410156, 7.0, 24.966060638427734, 121.54296875), (3.5999999046325684, 373.8388977050781, 10.0, 24.983219146728516, 121.53765106201172), (13.0, 732.852783203125, 0.0, 24.976680755615234, 121.52517700195312), (12.800000190734863, 732.852783203125, 0.0, 24.976680755615234, 121.52517700195312), (18.100000381469727, 837.7233276367188, 0.0, 24.963340759277344, 121.54766845703125), (11.0, 1712.6319580078125, 2.0, 24.964120864868164, 121.5167007446289), (13.699999809265137, 250.63099670410156, 7.0, 24.966060638427734, 121.54296875), (2.0, 2077.389892578125, 3.0, 24.96356964111328, 121.51329040527344), (32.79999923706055, 204.17050170898438, 8.0, 24.98236083984375, 121.53923034667969), (4.800000190734863, 1559.8270263671875, 3.0, 24.972129821777344, 121.51627349853516), (7.5, 639.6198120117188, 5.0, 24.972579956054688, 121.54814147949219), (16.399999618530273, 389.8218994140625, 6.0, 24.964120864868164, 121.54273223876953), (21.700000762939453, 1055.0670166015625, 0.0, 24.96211051940918, 121.54927825927734), (19.0, 1009.2349853515625, 0.0, 24.96356964111328, 121.54950714111328), (18.0, 6306.15283203125, 1.0, 24.957429885864258, 121.47515869140625), (39.20000076293945, 424.71319580078125, 7.0, 24.97429084777832, 121.53916931152344), (31.700000762939453, 1159.4539794921875, 0.0, 24.949600219726562, 121.53018188476562), (5.900000095367432, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (30.399999618530273, 1735.594970703125, 2.0, 24.96463966369629, 121.51622772216797), (1.100000023841858, 329.9747009277344, 5.0, 24.982540130615234, 121.54395294189453), (31.5, 5512.0380859375, 1.0, 24.950950622558594, 121.48458099365234), (14.600000381469727, 339.2289123535156, 1.0, 24.975189208984375, 121.53150939941406), (17.299999237060547, 444.1333923339844, 1.0, 24.97500991821289, 121.52729797363281), (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461), (17.700000762939453, 837.7233276367188, 0.0, 24.963340759277344, 121.54766845703125), (17.0, 1485.0970458984375, 4.0, 24.97072982788086, 121.51699829101562), (16.200000762939453, 2288.010986328125, 3.0, 24.958850860595703, 121.51358795166016), (15.899999618530273, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (3.9000000953674316, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961), (32.599998474121094, 493.6570129394531, 7.0, 24.969680786132812, 121.54521942138672), (15.699999809265137, 815.931396484375, 4.0, 24.97886085510254, 121.53463745117188), (17.799999237060547, 1783.1800537109375, 3.0, 24.967309951782227, 121.51486206054688), (34.70000076293945, 482.7580871582031, 5.0, 24.97433090209961, 121.53862762451172), (17.200000762939453, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188), (17.600000381469727, 837.7233276367188, 0.0, 24.963340759277344, 121.54766845703125), (10.800000190734863, 252.5821990966797, 1.0, 24.974599838256836, 121.53045654296875), (17.700000762939453, 451.64190673828125, 8.0, 24.969449996948242, 121.5448989868164), (13.0, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (13.199999809265137, 170.12890625, 1.0, 24.973709106445312, 121.52983856201172), (27.5, 394.0173034667969, 7.0, 24.97304916381836, 121.5399398803711), (1.5, 23.38283920288086, 7.0, 24.96772003173828, 121.54102325439453), (19.100000381469727, 461.1015930175781, 5.0, 24.95425033569336, 121.53990173339844), (21.200000762939453, 2185.1279296875, 3.0, 24.963220596313477, 121.51236724853516), (0.0, 208.3905029296875, 6.0, 24.956180572509766, 121.53843688964844), (2.5999999046325684, 1554.25, 3.0, 24.970260620117188, 121.51641845703125), (2.299999952316284, 184.3302001953125, 6.0, 24.965810775756836, 121.54086303710938), (4.699999809265137, 387.7720947265625, 9.0, 24.98118019104004, 121.53787994384766), (2.0, 1455.7979736328125, 1.0, 24.951200485229492, 121.54900360107422), (33.5, 1978.6710205078125, 2.0, 24.986740112304688, 121.51844024658203), (15.0, 383.2804870605469, 7.0, 24.967350006103516, 121.54463958740234), (30.100000381469727, 718.293701171875, 3.0, 24.97509002685547, 121.53643798828125), (5.900000095367432, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (19.200000762939453, 461.1015930175781, 5.0, 24.95425033569336, 121.53990173339844), (16.600000381469727, 323.6911926269531, 6.0, 24.978410720825195, 121.54280090332031), (13.899999618530273, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (37.70000076293945, 490.3446044921875, 0.0, 24.972169876098633, 121.53471374511719), (3.4000000953674316, 56.47425079345703, 7.0, 24.957439422607422, 121.537109375), (17.5, 395.6747131347656, 5.0, 24.95673942565918, 121.53399658203125), (12.600000381469727, 383.2804870605469, 7.0, 24.967350006103516, 121.54463958740234), (26.399999618530273, 335.5273132324219, 6.0, 24.97960090637207, 121.54139709472656), (18.200000762939453, 2179.590087890625, 3.0, 24.962989807128906, 121.51251983642578), (12.5, 1144.43603515625, 4.0, 24.99176025390625, 121.53456115722656), (34.900001525878906, 567.034912109375, 4.0, 24.970029830932617, 121.5457992553711), (16.700000762939453, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (33.20000076293945, 121.7261962890625, 10.0, 24.981779098510742, 121.54058837890625), (2.5, 156.24420166015625, 4.0, 24.966960906982422, 121.5399169921875), (38.0, 461.7847900390625, 0.0, 24.9722900390625, 121.5344467163086), (16.5, 2288.010986328125, 3.0, 24.958850860595703, 121.51358795166016), (38.29999923706055, 439.71051025390625, 0.0, 24.971609115600586, 121.53423309326172), (20.0, 1626.0830078125, 3.0, 24.96622085571289, 121.51667785644531), (16.200000762939453, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (14.399999618530273, 169.9803009033203, 1.0, 24.973690032958984, 121.52979278564453), (10.300000190734863, 3079.889892578125, 0.0, 24.954599380493164, 121.56626892089844), (16.399999618530273, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (30.299999237060547, 1264.72998046875, 0.0, 24.948829650878906, 121.529541015625), (16.399999618530273, 1643.4990234375, 2.0, 24.95393943786621, 121.55174255371094), (21.299999237060547, 537.797119140625, 4.0, 24.97425079345703, 121.53813934326172), (35.400001525878906, 318.5292053222656, 9.0, 24.97071075439453, 121.54068756103516), (8.300000190734863, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (3.700000047683716, 577.9614868164062, 6.0, 24.972009658813477, 121.5472183227539), (15.600000381469727, 1756.4110107421875, 2.0, 24.983200073242188, 121.51811981201172), (13.300000190734863, 250.63099670410156, 7.0, 24.966060638427734, 121.54296875), (15.600000381469727, 752.7669067382812, 2.0, 24.977949142456055, 121.53450775146484), (7.099999904632568, 379.5574951171875, 10.0, 24.983430862426758, 121.5376205444336), (34.599998474121094, 272.6783142089844, 5.0, 24.95561981201172, 121.5387191772461), (13.5, 4197.34912109375, 0.0, 24.93885040283203, 121.50382995605469), (16.899999618530273, 964.7495727539062, 4.0, 24.988719940185547, 121.53411102294922), (12.899999618530273, 187.4822998046875, 1.0, 24.973880767822266, 121.5298080444336), (28.600000381469727, 197.13380432128906, 6.0, 24.97631072998047, 121.54435729980469), (12.399999618530273, 1712.6319580078125, 2.0, 24.964120864868164, 121.5167007446289), (36.599998474121094, 488.8193054199219, 8.0, 24.970149993896484, 121.54493713378906), (4.099999904632568, 56.47425079345703, 7.0, 24.957439422607422, 121.537109375), (3.5, 757.3377075195312, 3.0, 24.975379943847656, 121.54971313476562), (15.899999618530273, 1497.7130126953125, 3.0, 24.970029830932617, 121.51696014404297), (13.600000381469727, 4197.34912109375, 0.0, 24.93885040283203, 121.50382995605469), (32.0, 1156.7769775390625, 0.0, 24.949350357055664, 121.53045654296875), (25.600000381469727, 4519.68994140625, 0.0, 24.948259353637695, 121.4958724975586), (39.79999923706055, 617.71337890625, 2.0, 24.975770950317383, 121.53475189208984), (7.800000190734863, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (30.0, 1013.3410034179688, 5.0, 24.990060806274414, 121.53459930419922), (27.299999237060547, 337.6015930175781, 6.0, 24.964309692382812, 121.5406265258789), (5.099999904632568, 1867.2330322265625, 2.0, 24.98406982421875, 121.5174789428711), (31.299999237060547, 600.8604125976562, 5.0, 24.96870994567871, 121.5465087890625), (31.5, 258.1860046386719, 9.0, 24.968669891357422, 121.5433120727539), (1.7000000476837158, 329.9747009277344, 5.0, 24.982540130615234, 121.54395294189453), (33.599998474121094, 270.8894958496094, 0.0, 24.972810745239258, 121.53265380859375), (13.0, 750.0703735351562, 2.0, 24.973709106445312, 121.54950714111328), (5.699999809265137, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (33.5, 563.285400390625, 8.0, 24.982229232788086, 121.53597259521484), (34.599998474121094, 3085.169921875, 0.0, 24.99799919128418, 121.5155029296875), (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734), (13.199999809265137, 1712.6319580078125, 2.0, 24.964120864868164, 121.5167007446289), (17.399999618530273, 6488.02099609375, 1.0, 24.957189559936523, 121.4735336303711), (4.599999904632568, 259.66070556640625, 6.0, 24.975849151611328, 121.54515838623047), (7.800000190734863, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (13.199999809265137, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406), (4.0, 2180.2451171875, 3.0, 24.963239669799805, 121.51241302490234), (18.399999618530273, 2674.9609375, 3.0, 24.961429595947266, 121.50827026367188), (4.099999904632568, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961), (12.199999809265137, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984), (3.799999952316284, 383.8623962402344, 5.0, 24.980850219726562, 121.54390716552734), (10.300000190734863, 211.44729614257812, 1.0, 24.974170684814453, 121.52999114990234), (0.0, 338.9678955078125, 9.0, 24.968530654907227, 121.54412841796875), (1.100000023841858, 193.58450317382812, 6.0, 24.965709686279297, 121.5408935546875), (5.599999904632568, 2408.992919921875, 0.0, 24.955049514770508, 121.55963897705078), (32.900001525878906, 87.3022232055664, 10.0, 24.982999801635742, 121.54022216796875), (41.400001525878906, 281.2049865722656, 8.0, 24.97344970703125, 121.54093170166016), (17.100000381469727, 967.4000244140625, 4.0, 24.988719940185547, 121.5340805053711), (32.29999923706055, 109.94550323486328, 10.0, 24.98181915283203, 121.54086303710938), (35.29999923706055, 614.139404296875, 7.0, 24.979129791259766, 121.53665924072266), (17.299999237060547, 2261.431884765625, 4.0, 24.961820602416992, 121.51222229003906), (14.199999809265137, 1801.5439453125, 1.0, 24.95153045654297, 121.55254364013672), (15.0, 1828.3189697265625, 2.0, 24.96463966369629, 121.51531219482422), (18.200000762939453, 350.85150146484375, 1.0, 24.975439071655273, 121.53118896484375), (20.200000762939453, 2185.1279296875, 3.0, 24.963220596313477, 121.51236724853516), (15.899999618530273, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (4.099999904632568, 312.89630126953125, 5.0, 24.955909729003906, 121.53955841064453), (33.900001525878906, 157.60519409179688, 7.0, 24.966279983520508, 121.54196166992188), (0.0, 274.014404296875, 1.0, 24.97480010986328, 121.53058624267578), (5.400000095367432, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188), (21.700000762939453, 1157.988037109375, 0.0, 24.961650848388672, 121.55010986328125), (14.699999809265137, 1717.1929931640625, 2.0, 24.96446990966797, 121.51648712158203), (3.9000000953674316, 49.661048889160156, 8.0, 24.95836067199707, 121.53755950927734), (37.29999923706055, 587.8876953125, 8.0, 24.97076988220215, 121.54634094238281), (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461), (14.100000381469727, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (8.0, 132.54690551757812, 9.0, 24.982980728149414, 121.53981018066406), (16.299999237060547, 3529.56396484375, 0.0, 24.932069778442383, 121.5159683227539), (29.100000381469727, 506.1144104003906, 4.0, 24.978450775146484, 121.53888702392578), (16.100000381469727, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875), (18.299999237060547, 82.88642883300781, 10.0, 24.982999801635742, 121.5402603149414), (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734), (16.200000762939453, 2103.554931640625, 3.0, 24.960420608520508, 121.51461791992188), (10.399999618530273, 2251.93798828125, 4.0, 24.959569931030273, 121.5135269165039), (40.900001525878906, 122.36190032958984, 8.0, 24.967559814453125, 121.54229736328125), (32.79999923706055, 377.8302001953125, 9.0, 24.97150993347168, 121.54350280761719), (6.199999809265137, 1939.7490234375, 1.0, 24.951549530029297, 121.55387115478516), (42.70000076293945, 443.802001953125, 6.0, 24.979270935058594, 121.53874206542969), (16.899999618530273, 967.4000244140625, 4.0, 24.988719940185547, 121.5340805053711), (32.599998474121094, 4136.27099609375, 1.0, 24.955440521240234, 121.49629974365234), (21.200000762939453, 512.5487060546875, 4.0, 24.974000930786133, 121.53842163085938), (37.099998474121094, 918.6356811523438, 1.0, 24.97197914123535, 121.55062866210938), (13.100000381469727, 1164.8380126953125, 4.0, 24.991559982299805, 121.5340576171875), (14.699999809265137, 1717.1929931640625, 2.0, 24.96446990966797, 121.51648712158203), (12.699999809265137, 170.12890625, 1.0, 24.973709106445312, 121.52983856201172), (26.799999237060547, 482.7580871582031, 5.0, 24.97433090209961, 121.53862762451172), (7.599999904632568, 2175.030029296875, 3.0, 24.963050842285156, 121.51254272460938), (12.699999809265137, 187.4822998046875, 1.0, 24.973880767822266, 121.5298080444336), (30.899999618530273, 161.94200134277344, 9.0, 24.983530044555664, 121.53965759277344), (16.399999618530273, 289.3247985839844, 5.0, 24.982030868530273, 121.5434799194336), (23.0, 130.9945068359375, 6.0, 24.95663070678711, 121.53765106201172), (1.899999976158142, 372.13861083984375, 7.0, 24.972930908203125, 121.5402603149414), (5.199999809265137, 2408.992919921875, 0.0, 24.955049514770508, 121.55963897705078), (18.5, 2175.743896484375, 3.0, 24.963300704956055, 121.5124282836914), (13.699999809265137, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711), (5.599999904632568, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703), (18.799999237060547, 390.9696044921875, 7.0, 24.979230880737305, 121.53986358642578), (8.100000381469727, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461), (6.5, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703)] from pyspark.mllib.feature import StandardScaler scaler1 = StandardScaler().fit(features_rdd) scaled_features=scaler1.transform(features_rdd) for data in scaled_features.collect(): print(data) [2.808869299771829,0.06725154690948568,3.3949381000162235,2013.0949590447945,7919.393034999268] [1.7116547295484583,0.24292240417652702,3.0554442900146013,2012.8820961989197,7919.345808528075] [1.1674363194598323,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973] [1.1674363194598323,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973] [0.4388858280893483,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594] [0.6232178675157918,1.723328976948524,1.0184814300048672,2011.4890356682267,7917.58848667894] [3.0283122138165033,0.49399282615128015,2.3764566700113567,2012.8007933502065,7919.144474624567] [1.7818763950740915,0.227874433981389,2.0369628600097345,2012.8885512455092,7919.526263360108] [2.782536217055131,4.367321291012587,0.3394938100016224,2010.5140162500102,7915.7665391323835] [1.5712112310755355,1.4128567496928301,1.0184814300048672,2011.8322289785795,7917.739611386758] [3.0546452965332014,0.3210603995816714,0.3394938100016224,2012.3301897154997,7918.968493879279] [0.5529961601347445,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [1.1411031530323057,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [1.7906541451202098,1.9567595700325358,1.3579752400064895,2011.3302722604371,7917.452772714353] [1.158658569413714,0.9229293727856711,1.3579752400064895,2013.7862637962348,7918.990367192253] [3.1336448795266096,0.458920776273077,0.6789876200032448,2013.0482368028117,7919.780789183801] [0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678] [1.5536558984049558,0.27798814312265985,0.3394938100016224,2012.4872625158491,7918.803449790478] [1.4834340654576659,0.2916833009520058,2.715950480012979,2011.8475981371264,7919.671422618933] [0.1316657484268045,0.018526789892036186,2.3764566700113567,2011.8652726694554,7919.4442384364565] [0.39499724528041347,1.8032324374654856,1.0184814300048672,2011.4962591727437,7917.521375377771] [0.9216602389876315,0.22119521912804102,2.3764566700113567,2012.4745061142553,7919.730082867362] [1.2903243178405184,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [0.8865494062248149,0.22119521912804102,2.3764566700113567,2012.4745061142553,7919.730082867362] [3.4759756245303133,0.380868425777485,1.3579752400064895,2012.3334172387945,7919.302559022877] [2.5718708856349184,1.1788738896031223,0.6789876200032448,2012.4857255999946,7917.89570730207] [0.27210920504431313,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973] [0.9128824889415131,0.21903724305722802,1.6974690500081118,2010.9153049796703,7919.320952490605] [1.6853216468317602,0.44170334459435423,1.3579752400064895,2012.386594527367,7919.245390136696] [0.6232178675157918,0.35753139691528435,1.6974690500081118,2012.502631674396,7919.830004137993] [2.273428556018493,3.581059818914822,0.0,2010.2971574229132,7916.502277841498] [2.5982041357732735,0.6096169359405251,2.3764566700113567,2013.0811268021023,7918.991858554501] [3.3267547108545856,0.38710797902993216,0.3394938100016224,2012.3301897154997,7919.0196973164675] [1.4483232326948494,0.2564396952767179,2.0369628600097345,2012.7267140060103,7919.560564691817] [1.3517683170308614,0.16271725209082338,2.3764566700113567,2013.192399509982,7919.535708654346] [1.220102568604057,3.232221670476899,0.0,2015.64193599919,7917.9543675505] [1.2903243178405184,1.533154527826953,0.6789876200032448,2011.5542009004657,7917.72121791903] [1.053325987414436,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [0.27210920504431313,0.45793288569581236,2.0369628600097345,2012.2109250451756,7919.8479004849705] [1.4219901499781513,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [1.1937694858873589,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [1.4746563154115475,3.2220553150473474,0.0,2009.870970656407,7916.993930262656] [3.1687555448677696,0.4115820637565314,1.6974690500081118,2011.4890356682267,7919.220036978476] [3.019534631192042,0.4062936477604794,2.0369628600097345,2013.4575174949164,7919.573489831301] [0.23699835135378952,0.4226861124645811,1.3579752400064895,2012.4074965829907,7919.876236367687] [3.2126441276767044,0.3873033761259493,2.715950480012979,2012.0610757493432,7919.6992613809] [1.9047645608764343,0.3676085771820948,3.0554442900146013,2012.0732173845952,7919.675896705678] [3.1512003796188464,0.5076730892137474,1.0184814300048672,2012.502631674396,7919.19170109576] [2.1242074749211084,3.649246514177134,0.0,2010.182810883324,7916.4963123925045] [2.5806486356810368,3.573666598264136,0.3394938100016224,2010.3769233557716,7916.472947717283] [1.9047645608764343,0.4061047550350635,1.3579752400064895,2012.3713790604054,7919.274720260911] [2.7474252168706577,1.3932276714898462,0.3394938100016224,2010.76130601103,7920.2127871150315] [2.8176468823962906,1.1398209714784304,1.0184814300048672,2012.386594527367,7917.911615166051] [1.1674363194598323,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [1.413212399932033,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [2.782536217055131,0.9195968137754665,0.0,2010.4116576540875,7918.731864402564] [2.949312630823095,0.29414998073830584,2.715950480012979,2012.253651305936,7919.415902553741] [0.30722007966254383,0.04474591685305818,2.3764566700113567,2011.0368750237765,7919.189215492013] [2.659648051252788,3.573666598264136,0.3394938100016224,2010.3769233557716,7916.472947717283] [1.1674363194598323,0.26626308419099826,1.6974690500081118,2011.0626952101352,7919.011246263728] [0.9655488217965663,1.5301421095853742,0.6789876200032448,2011.537294826064,7917.7296689717705] [0.4652189945168749,0.205735466660267,2.0369628600097345,2012.520306206725,7919.7136778826325] [1.509767315596021,1.724000015212188,1.0184814300048672,2011.4873450607865,7917.58848667894] [0.22822062223537828,0.4226861124645811,1.3579752400064895,2012.4074965829907,7919.876236367687] [1.536100398312719,0.7889611002348912,0.0,2011.4890356682267,7919.973672034569] [3.519864207339248,0.09804449468619773,2.715950480012979,2012.5607270937035,7919.591883299029] [0.08777716561786966,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717] [0.7461059077518921,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [2.6684258012989064,0.36781512117345455,2.0369628600097345,2012.8256913870525,7919.2503613441895] [1.0972145702233709,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973] [0.579329284706857,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [3.116089379434373,0.5076730892137474,1.0184814300048672,2012.502631674396,7919.19170109576] [2.852757882580764,0.33637664483934004,2.715950480012979,2012.5219968141653,7919.320952490605] [1.211324902268767,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [0.5968847429436794,0.30073259722528967,3.3949381000162235,2013.1312302589652,7919.222522582223] [1.0796591538419624,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [3.1512003796188464,0.4883889602709763,1.0184814300048672,2012.631578914605,7919.22550530672] [1.7994318951663282,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704] [3.3530877935712837,0.43770927416813227,0.6789876200032448,2012.5309109261225,7918.974459328272] [1.5799889811216539,1.1210096546647916,0.3394938100016224,2010.5840996129841,7919.955278566841] [1.0357705710330276,0.4226861124645811,1.3579752400064895,2012.4074965829907,7919.876236367687] [2.703536634061723,0.299336599707476,2.0369628600097345,2011.5872445913417,7919.354259580815] [1.158658569413714,0.11958921279546592,2.3764566700113567,2011.82746453943,7919.54167410334] [2.22076222316344,2.14513233267738,1.0184814300048672,2011.288314457604,7917.312584663022] [1.3254352343141633,0.30368241392230844,2.3764566700113567,2011.8354565018744,7919.679873671673] [0.0,0.2685724742718668,3.0554442900146013,2011.9305915932798,7919.646566581463] [0.15799889392662397,1.153463997623701,0.3394938100016224,2010.5341498477067,7919.964226740331] [1.4834340654576659,3.2220553150473474,0.0,2009.870970656407,7916.993930262656] [0.7812167405147086,1.1143485988535313,0.0,2013.3164286194556,7918.568311676011] [2.018874809211002,3.128052506890741,0.0,2010.2625768161824,7916.929801685983] [0.0,0.21710824984735824,0.3394938100016224,2012.435775834717,7918.764177251275] [0.7987722406069453,1.1108512302150066,0.0,2013.3132010961608,7918.569803038259] [1.8082096452124463,1.9567595700325358,1.3579752400064895,2011.3302722604371,7917.452772714353] [2.800091549725711,0.9082642174431681,0.0,2010.3729273745494,7918.775611028511] [3.5900862077081945,0.13279267405910117,1.6974690500081118,2011.7507724382808,7919.394526361516] [0.7022173249429573,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [0.5617738683254487,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [2.492871470063167,0.48921455592082264,1.0184814300048672,2012.6501755964466,7918.920770287336] [1.439545482648731,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [0.5617738683254487,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [1.536100398312719,0.7643944551712603,1.3579752400064895,2013.5574170254713,7918.993847037498] [1.114769986604779,0.13479725337491694,0.3394938100016224,2012.3478642478287,7918.715459417834] [0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717] [0.0,0.16511284321702066,2.0369628600097345,2010.9354385773668,7919.27571450241] [2.8703133826730007,0.31094438652978446,2.0369628600097345,2011.5638834703502,7919.5406798618405] [0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678] [1.509767315596021,0.15015977880110146,2.715950480012979,2012.6186688214254,7919.578461038795] [1.0708814037958443,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [2.756202966916776,0.46945258544711593,0.6789876200032448,2012.258569436671,7919.091282704381] [0.35110866247147865,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167] [0.7109950749890757,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [2.922979548106397,0.15578457231246617,2.3764566700113567,2012.613904382276,7919.523280635612] [0.8689939061325783,1.665803839754847,1.0184814300048672,2011.2786318877195,7917.723703522777] [1.2991020678866367,0.31158989090737055,2.0369628600097345,2011.3817589415692,7919.254835430935] [2.685981301391143,0.11396657128775735,2.715950480012979,2012.9796903556926,7919.470088715425] [1.8082096452124463,0.5846687817343428,0.6789876200032448,2012.9289721324876,7919.859334262207] [2.712314384107841,5.067930116016753,0.3394938100016224,2009.933830514864,7915.391710087334] [1.1937694858873589,3.3256613790700786,0.0,2009.5389968317936,7917.020774783124] [2.22076222316344,1.2548213387248148,1.0184814300048672,2011.7444710832765,7917.884770645584] [1.4571009827409678,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [1.1674363194598323,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [1.1937694858873589,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [2.7649807169628944,0.3287730356064927,1.3579752400064895,2013.015193111936,7919.679873671673] [0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688] [0.8689939061325783,0.22119521912804102,2.3764566700113567,2012.4745061142553,7919.730082867362] [0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717] [3.3881984589124436,0.6375751387662827,1.3579752400064895,2012.7242549406428,7919.036599421947] [0.3335532251623633,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973] [3.6251968730493545,0.09903355798455589,2.0369628600097345,2011.7862751945243,7919.402977414256] [3.379420876287982,0.17180195970516865,2.3764566700113567,2012.9240540017527,7919.48301385491] [2.5982041357732735,0.4243109961240726,2.715950480012979,2012.9289721324876,7919.151434315059] [0.35110866247147865,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167] [2.3348726389196646,0.3825009260791303,1.6974690500081118,2012.3979677046916,7919.288142521144] [1.5799889811216539,0.2958488788156798,2.715950480012979,2013.386665674015,7919.430816176223] [2.9317574655741723,0.14813974858263068,2.0369628600097345,2011.729870382657,7919.514829582871] [1.6589883966934051,0.7996413251217569,0.0,2011.5308397794745,7919.997036709791] [1.0006596545593829,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594] [1.1937694858873589,0.2528075241619782,2.0369628600097345,2011.642112487354,7919.5580790880695] [0.8777716561786966,0.7467389335797002,0.0,2012.7282509218649,7918.339139010536] [1.1323254029861873,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [1.4219901499781513,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [0.44766353628005245,1.2358887359523067,1.0184814300048672,2012.22060761506,7917.831578725398] [1.7379878122651566,0.5075685356878004,1.6974690500081118,2012.0626126651978,7919.799182651529] [1.1937694858873589,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [1.0445482373683177,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [0.18433203942644344,0.35753139691528435,1.6974690500081118,2012.502631674396,7919.830004137993] [0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688] [0.28088693416272437,0.3881454624105542,2.715950480012979,2012.0626126651978,7919.6992613809] [1.439545482648731,2.9954531021038173,0.0,2009.061938150497,7917.55517958873] [3.0634232140009767,0.14218558970269804,2.715950480012979,2012.3301897154997,7919.537200016594] [3.142422462151071,0.13527438160126984,2.3764566700113567,2011.822546408695,7919.552610759826] [0.43010811989864417,0.3072412234742074,3.0554442900146013,2012.9498741881116,7919.239424687703] [1.053325987414436,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [0.5705515765161528,0.2980493146440235,2.0369628600097345,2010.7742161042095,7919.190706854261] [1.4834340654576659,3.2220553150473474,0.0,2009.870970656407,7916.993930262656] [1.211324902268767,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [2.6947590514372615,1.0020761984890492,0.0,2010.3431112069684,7918.696071708607] [1.413212399932033,0.6464822093597283,1.3579752400064895,2012.762985220181,7919.028148369207] [1.0182151546516194,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594] [1.3605460670769798,0.6464822093597283,1.3579752400064895,2012.762985220181,7919.028148369207] [0.30722007966254383,0.039347651951275965,2.715950480012979,2011.111108059558,7919.218545616228] [1.6853216468317602,0.4883889602709763,1.0184814300048672,2012.631578914605,7919.22550530672] [1.4044346498859146,3.2220553150473474,0.0,2009.870970656407,7916.993930262656] [0.7461059077518921,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688] [1.2025471522226487,0.9797595820571193,0.3394938100016224,2012.6082177936134,7920.283875382196] [0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678] [2.4753161373925874,0.2615346485620617,2.715950480012979,2012.3776804154097,7919.384583946528] [2.422649804537534,0.4081358596094278,1.6974690500081118,2011.4841175374918,7919.585917850036] [0.7373281577057738,1.5550377452304196,0.3394938100016224,2010.8144832996024,7920.342535630625] [2.106651974828872,3.587396091432715,0.0,2010.2287646673792,7916.528625241216] [0.31599778785324795,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973] [0.579329284706857,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [3.6251968730493545,0.31841981855609963,1.3579752400064895,2013.117398016273,7919.677388067926] [0.37744182889900524,0.34231457906249413,2.3764566700113567,2012.895006292099,7919.232962117961] [2.6508704686283266,0.37411529322551995,1.0184814300048672,2012.0530837868987,7919.220036978476] [1.220102568604057,3.6239157385568475,0.0,2010.330201113789,7916.45008016281] [2.896646465389699,0.1434713756175361,3.0554442900146013,2012.610676858981,7919.548136673081] [1.149880903078424,0.9067643917938982,1.3579752400064895,2013.8024014127093,7919.023177161714] [1.2288803186501753,0.3477125054468473,0.3394938100016224,2012.4462268625289,7918.549918208283] [2.3612057216363627,3.5252644090643797,0.0,2010.3552528422204,7916.524151154471] [1.0182151546516194,0.1599654318200806,2.715950480012979,2013.248804321849,7919.456169334442] [1.1849917358412405,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167] [1.4922118155037842,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [1.2376580686962937,2.072296342325083,0.0,2010.8363075047391,7920.793921271082] [2.756202966916776,1.146719763244157,1.0184814300048672,2012.2787030343675,7917.898690026567] [1.8345427279291446,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704] [0.7812167405147086,2.438913426137275,0.0,2010.8112557763075,7921.089210996227] [3.0546452965332014,0.1505726612553819,2.715950480012979,2012.6186688214254,7919.580946642542] [1.4307677326026127,3.2220553150473474,0.0,2009.870970656407,7916.993930262656] [3.098533879342136,0.4885261081893786,2.715950480012979,2012.810475920091,7919.144474624567] [1.158658569413714,0.5942989255562621,0.6789876200032448,2012.3478642478287,7919.997036709791] [3.8446397870940285,0.045629516859878705,2.3764566700113567,2011.8475981371264,7919.422365123482] [0.8514384897511701,0.333948024083993,1.6974690500081118,2013.0530012419613,7919.688324724412] [1.3342129006494532,2.9885637888261045,0.0,2009.1183429623643,7917.525849464516] [1.3342129006494532,0.36534196119636964,1.6974690500081118,2010.779902692872,7919.371161686295] [2.0013193091187658,0.5608916076749141,0.6789876200032448,2012.9354271790774,7919.841935035978] [3.019534631192042,0.1004101391098313,2.715950480012979,2011.9530305647584,7919.435787383717] [2.9844236310075685,0.12487441287594185,2.3764566700113567,2011.749235522426,7919.505384288633] [1.5975444812138906,0.35784682261971984,2.715950480012979,2012.004670937476,7919.696775777153] [1.5273226482666007,0.7889611002348912,0.0,2011.4890356682267,7919.973672034569] [1.149880903078424,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973] [3.3618653761957455,0.5092255785030526,1.0184814300048672,2012.4994041511013,7919.190706854261] [1.3693238171230981,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [1.5799889811216539,1.1210096546647916,0.3394938100016224,2010.5840996129841,7919.955278566841] [1.1235477366508975,1.1486498929053959,1.0184814300048672,2012.2819305576625,7917.897198664318] [1.9486531436853693,0.30073259722528967,3.3949381000162235,2013.1312302589652,7919.222522582223] [3.379420876287982,0.5269459987217269,1.0184814300048672,2012.4543725165588,7919.176787473279] [1.009437404605501,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [3.0546452965332014,0.1391554234759101,2.715950480012979,2012.328652799645,7919.554102122074] [0.45644124447075657,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594] [0.0,0.21710824984735824,0.3394938100016224,2012.435775834717,7918.764177251275] [1.5448781483588374,1.4306721482301723,0.6789876200032448,2013.396194552314,7918.1338281410335] [0.5442184100886263,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [1.5887667311677722,1.4128567496928301,1.0184814300048672,2011.8322289785795,7917.739611386758] [1.6853216468317602,0.30402501774033425,2.715950480012979,2012.2101565872483,7919.688324724412] [3.3179767933868103,0.4682075183430306,0.3394938100016224,2012.1723484572228,7919.090288462882] [2.4577606373003507,0.29523918474612504,2.0369628600097345,2012.7242549406428,7919.455175092943] [1.1937694858873589,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [2.5718708856349184,0.4197552285637734,2.715950480012979,2012.9369640949321,7919.152925677307] [3.265310627953414,0.1477764710216158,3.0554442900146013,2012.6154412981305,7919.550125156079] [0.7899944905608269,1.1108512302150066,0.0,2013.3132010961608,7918.569803038259] [2.685981301391143,0.34157999624143237,3.3949381000162235,2012.9538701693336,7919.210094563488] [0.7987722406069453,1.1108512302150066,0.0,2013.3132010961608,7918.569803038259] [3.0283122138165033,0.2574593339528652,2.0369628600097345,2012.7048898008736,7919.488482183153] [0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717] [1.4483232326948494,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [2.8439802999563026,0.21001418188469634,2.715950480012979,2012.9023834882016,7919.368676082548] [1.0445482373683177,2.5127208647917114,0.0,2014.559025087974,7917.928517271531] [2.7210921341539596,0.9162532287690011,0.0,2010.3487977956308,7918.7880390472465] [0.35110866247147865,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167] [1.4219901499781513,3.228512099769986,0.0,2009.8210208911296,7917.003872677644] [2.3787612217285994,3.496340706171308,0.3394938100016224,2010.4631443352198,7916.502277841498] [3.484753541998088,0.26413545378971887,3.0554442900146013,2012.8676491898855,7919.33338050934] [0.7022173249429573,1.7562754275300223,1.3579752400064895,2011.2488157201383,7917.658083583857] [1.1323254029861873,0.1985810096062423,2.3764566700113567,2011.7315609900973,7919.571004227554] [0.31599778785324795,0.29620161397676104,3.3949381000162235,2013.114170492978,7919.224511065221] [1.1411031530323057,0.5806570116825441,0.0,2012.5873157379897,7918.411718639949] [1.1235477366508975,0.5806570116825441,0.0,2012.5873157379897,7918.411718639949] [1.5887667311677722,0.6637484842675013,0.0,2011.512396789218,7919.877230609185] [0.9655488217965663,1.3569597846136696,0.6789876200032448,2011.575256647675,7917.859417487364] [1.2025471522226487,0.1985810096062423,2.3764566700113567,2011.7315609900973,7919.571004227554] [0.17555433123573932,1.645966331534827,1.0184814300048672,2011.5308397794745,7917.637204512382] [2.879090965297462,0.16176923403073884,2.715950480012979,2013.045009279517,7919.327415060347] [0.42133041170794006,1.2358887359523067,1.0184814300048672,2012.22060761506,7917.831578725398] [0.6583287421340225,0.5067862702688738,1.6974690500081118,2012.2568788292308,7919.908052095649] [1.439545482648731,0.30886533337957534,2.0369628600097345,2011.575256647675,7919.555593484322] [1.9047645608764343,0.8359551536490203,0.0,2011.4132657165903,7919.982123087309] [1.6677661467395235,0.7996413251217569,0.0,2011.5308397794745,7919.997036709791] [1.5799889811216539,4.996517639813289,0.3394938100016224,2011.036106565849,7915.152595006872] [3.4408649591891534,0.3365105526623499,2.3764566700113567,2012.3947401813969,7919.323438094352] [2.782536217055131,0.9186634728639134,0.0,2010.405202607498,7918.737829851557] [0.5178852855165138,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [2.6684258012989064,1.375153935794498,0.6789876200032448,2011.6170607589227,7917.828596000902] [0.09655488427242734,0.26144694836811866,1.6974690500081118,2013.059456288551,7919.6351328042265] [2.7649807169628944,4.367321291012587,0.3394938100016224,2010.5140162500102,7915.7665391323835] [1.2815466515052285,0.26877928424120656,0.3394938100016224,2012.4671289181529,7918.824328861952] [1.5185448982204823,0.3518976447819577,0.3394938100016224,2012.4526819091186,7918.549918208283] [0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678] [1.5536558984049558,0.6637484842675013,0.0,2011.512396789218,7919.877230609185] [1.4922118155037842,1.1766783622775,1.3579752400064895,2012.1077979913257,7917.87880519659] [1.4219901499781513,1.812846525889341,1.0184814300048672,2011.1506067970236,7917.656592221608] [1.3956568998397962,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [0.34233095428077454,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167] [2.8615354652052254,0.3911364089752038,2.3764566700113567,2012.0232676193177,7919.717654848628] [1.378101483458388,0.6464822093597283,1.3579752400064895,2012.762985220181,7919.028148369207] [1.5624334810294171,1.4128567496928301,1.0184814300048672,2011.8322289785795,7917.739611386758] [3.04586771390874,0.3825009260791303,1.6974690500081118,2012.3979677046916,7919.288142521144] [1.509767315596021,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594] [1.5448781483588374,0.6637484842675013,0.0,2011.512396789218,7919.877230609185] [0.9479934054151581,0.20012699452494626,0.3394938100016224,2012.4196382182429,7918.755726198535] [1.5536558984049558,0.35784682261971984,2.715950480012979,2012.004670937476,7919.696775777153] [1.1411031530323057,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [1.158658569413714,0.13479725337491694,0.3394938100016224,2012.3478642478287,7918.715459417834] [2.413872054491416,0.3121894536338698,2.3764566700113567,2012.2946869592563,7919.373647290042] [0.1316657484268045,0.018526789892036186,2.3764566700113567,2011.8652726694554,7919.4442384364565] [1.6765438967856419,0.36534196119636964,1.6974690500081118,2010.779902692872,7919.371161686295] [1.8608759780674995,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704] [0.0,0.16511284321702066,2.0369628600097345,2010.9354385773668,7919.27571450241] [0.22822062223537828,1.231469922871879,1.0184814300048672,2012.0699898613004,7917.841024019636] [0.2018874767355588,0.14604928255909894,2.0369628600097345,2011.7114273924008,7919.433798900719] [0.41255266166182175,0.3072412234742074,3.0554442900146013,2012.9498741881116,7919.239424687703] [0.17555433123573932,1.153463997623701,0.3394938100016224,2010.5341498477067,7919.964226740331] [2.9405350481986336,1.567748977972384,0.6789876200032448,2013.3978851597542,7917.972761018228] [1.316657484268045,0.30368241392230844,2.3764566700113567,2011.8354565018744,7919.679873671673] [2.6420927185822083,0.5691214983313402,1.0184814300048672,2012.4591369557083,7919.145468866066] [0.5178852855165138,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [1.6853216468317602,0.36534196119636964,1.6974690500081118,2010.779902692872,7919.371161686295] [1.4571009827409678,0.25646837253892263,2.0369628600097345,2012.7267140060103,7919.5600675710675] [1.220102568604057,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [3.309199210762349,0.3885119075275124,0.0,2012.223835138355,7919.033119576701] [0.2984423714718397,0.04474591685305818,2.3764566700113567,2011.0368750237765,7919.189215492013] [1.536100398312719,0.31350265946046174,1.6974690500081118,2010.9804702119093,7918.986390226258] [1.105992320269489,0.30368241392230844,2.3764566700113567,2011.8354565018744,7919.679873671673] [2.317317138827428,0.2658464175954572,2.0369628600097345,2012.822617555343,7919.468597353177] [1.5975444812138906,1.7269420218285219,1.0184814300048672,2011.4841175374918,7917.586995316692] [1.0972145702233709,0.9067643917938982,1.3579752400064895,2013.8024014127093,7919.023177161714] [3.0634232140009767,0.4492754958861153,1.3579752400064895,2012.0513931794585,7919.755436025582] [1.4658787327870861,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [2.9142019654819356,0.09644661383662796,3.3949381000162235,2012.9981333459489,7919.415902553741] [0.21944291404467414,0.12379606560566893,1.3579752400064895,2011.8041034184387,7919.372155927793] [3.335532293479047,0.36588327474525406,0.0,2012.2335177082396,7919.015720350472] [1.4483232326948494,1.812846525889341,1.0184814300048672,2011.1506067970236,7917.656592221608] [3.3618653761957455,0.3483932881765047,0.0,2012.1786498122271,7919.001800969489] [1.7555433123573931,1.2883849549391233,1.0184814300048672,2011.7444710832765,7917.857926125116] [1.4219901499781513,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [1.2639911514129918,0.1346795097591447,0.3394938100016224,2012.346327331974,7918.7124766933375] [0.9041048226062232,2.440271364624136,0.0,2010.8080282530127,7921.089210996227] [1.439545482648731,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [2.659648051252788,1.0020761984890492,0.0,2010.3431112069684,7918.696071708607] [1.439545482648731,1.3021840859788236,0.6789876200032448,2010.7548509644403,7920.142693089366] [1.869653560691961,0.4261096843035703,1.3579752400064895,2012.3915126581019,7919.256326793183] [3.1073117968099115,0.252378404961011,3.0554442900146013,2012.1062610754711,7919.422365123482] [0.7285504913704839,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [0.3247755169716592,0.45793288569581236,2.0369628600097345,2012.2109250451756,7919.8479004849705] [1.3693238171230981,1.3916469885346634,0.6789876200032448,2013.1126335771235,7917.951881946753] [1.1674363194598323,0.1985810096062423,2.3764566700113567,2011.7315609900973,7919.571004227554] [1.3693238171230981,0.5964354541299625,0.6789876200032448,2012.6895206423267,7919.0196973164675] [0.6232178675157918,0.30073259722528967,3.3949381000162235,2013.1312302589652,7919.222522582223] [3.0370897964409647,0.21604963330723628,1.6974690500081118,2010.8902532512388,7919.294107970137] [1.1849917358412405,3.3256613790700786,0.0,2009.5389968317936,7917.020774783124] [1.4834340654576659,0.7643944551712603,1.3579752400064895,2013.5574170254713,7918.993847037498] [1.1323254029861873,0.14854676743144346,0.3394938100016224,2012.361696490521,7918.713470934836] [2.510426970155404,0.15619388824383332,2.0369628600097345,2012.5574995704087,7919.661480203945] [1.0884368201772525,1.3569597846136696,0.6789876200032448,2011.575256647675,7917.859417487364] [3.2126441276767044,0.3873033761259493,2.715950480012979,2012.0610757493432,7919.6992613809] [0.35988637066218276,0.04474591685305818,2.3764566700113567,2011.0368750237765,7919.189215492013] [0.30722007966254383,0.6000570103053195,1.0184814300048672,2012.4824980766996,7920.010458970025] [1.3956568998397962,1.1866742983613356,1.0184814300048672,2012.0513931794585,7917.876319592844] [1.1937694858873589,3.3256613790700786,0.0,2009.5389968317936,7917.020774783124] [2.808869299771829,0.9165424193726843,0.0,2010.3850690098016,7918.755726198535] [2.247095473301795,3.581059818914822,0.0,2010.2971574229132,7916.502277841498] [3.49353112462255,0.4894292726901126,0.6789876200032448,2012.514004851721,7919.035605180448] [0.6846619085615491,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [2.63331496853609,0.8028946226939285,1.6974690500081118,2013.6654622100561,7919.025662765461] [2.396316554399179,0.267489919713547,2.0369628600097345,2011.5904721146364,7919.418388157487] [0.44766353628005245,1.4794539605468038,0.6789876200032448,2013.1827169400974,7917.910123803803] [2.7474252168706577,0.4760762592622816,1.6974690500081118,2011.9450386023138,7919.801668255276] [2.7649807169628944,0.20456702539423122,3.0554442900146013,2011.941811079019,7919.593374661277] [0.14922118573591986,0.26144694836811866,1.6974690500081118,2013.059456288551,7919.6351328042265] [2.949312630823095,0.21463230919139176,0.0,2012.2754755110727,7918.898896974363] [1.1411031530323057,0.5942989255562621,0.6789876200032448,2012.3478642478287,7919.997036709791] [0.5003298272796914,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [2.9405350481986336,0.44630466692867843,2.715950480012979,2013.0344045601196,7919.1151445003525] [3.0370897964409647,2.4444548597317337,0.0,2014.3051265887789,7917.781369529708] [0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688] [1.158658569413714,1.3569597846136696,0.6789876200032448,2011.575256647675,7917.859417487364] [1.5273226482666007,5.140616191507609,0.3394938100016224,2011.01674142608,7915.046708287249] [0.4037749534711176,0.205735466660267,2.0369628600097345,2012.520306206725,7919.7136778826325] [0.6846619085615491,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [1.158658569413714,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493] [0.35110866247147865,1.7274610174069047,1.0184814300048672,2011.5042511351883,7917.580035626201] [1.6150998138844703,2.11943634511077,1.0184814300048672,2011.358397820578,7917.310099059276] [0.35988637066218276,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167] [1.0708814037958443,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376] [0.3335532251623633,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973] [0.9041048226062232,0.1675348145228683,0.3394938100016224,2012.3850576115121,7918.725401832822] [0.0,0.2685724742718668,3.0554442900146013,2011.9305915932798,7919.646566581463] [0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717] [0.49155211908898727,1.908703442364545,0.0,2010.8442994671834,7920.6572130649965] [2.8878688827652375,0.0691716661267508,3.3949381000162235,2013.0964959606492,7919.392040757769] [3.6339747905171293,0.2228055223582665,2.715950480012979,2012.3269621922047,7919.438272987463] [1.5009895655499026,0.7664944722222548,1.3579752400064895,2013.5574170254713,7918.991858554501] [2.8352023824885273,0.08711248537155993,3.3949381000162235,2013.0013608692436,7919.433798900719] [3.098533879342136,0.48659752603638695,2.3764566700113567,2012.784655733732,7919.159885367799] [1.5185448982204823,1.791787259908208,1.3579752400064895,2011.389904595599,7917.567607607465] [1.2464357350315836,1.427406905828718,0.3394938100016224,2010.5607384919929,7920.194890768053] [1.316657484268045,1.4486214062308915,0.6789876200032448,2011.6170607589227,7917.768941510973] [1.5975444812138906,0.27798814312265985,0.3394938100016224,2012.4872625158491,7918.803449790478] [1.7730988124496299,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704] [1.3956568998397962,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [0.35988637066218276,0.2479153186368254,1.6974690500081118,2010.91361437223,7919.348791252572] [2.975646048383107,0.12487441287594185,2.3764566700113567,2011.749235522426,7919.505384288633] [0.0,0.21710824984735824,0.3394938100016224,2012.435775834717,7918.764177251275] [0.47399670270757904,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594] [1.9047645608764343,0.9175019712051733,0.0,2011.3762260444923,7920.036309248994] [1.2903243178405184,1.360573603247791,0.6789876200032448,2011.603382207816,7917.845498106381] [0.34233095428077454,0.039347651951275965,2.715950480012979,2011.111108059558,7919.218545616228] [3.2740882105778755,0.46579766112518006,2.715950480012979,2012.1110255146207,7919.7907315987895] [0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678] [1.2376580686962937,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [0.7022173249429573,0.10502012386336701,3.0554442900146013,2013.0949590447945,7919.3651962373015] [1.4307677326026127,2.796559024325235,0.0,2008.9926232454504,7917.811693895422] [2.5543155529643387,0.4010067067332254,1.3579752400064895,2012.729941529305,7919.305044626624] [1.413212399932033,3.2220553150473474,0.0,2009.870970656407,7916.993930262656] [1.6063220638383522,0.06567292528364782,3.3949381000162235,2013.0964959606492,7919.394526361516] [0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688] [1.4219901499781513,1.6666975257675671,1.0184814300048672,2011.2770949718647,7917.723703522777] [0.9128824889415131,1.784265015757417,1.3579752400064895,2011.2085485247455,7917.652615255613] [3.5900862077081945,0.09695029754629986,2.715950480012979,2011.852362576276,7919.527257601607] [2.879090965297462,0.2993640196192299,3.0554442900146013,2012.1706578497826,7919.605802680012] [0.5442184100886263,1.536910136904218,0.3394938100016224,2010.5622754078474,7920.281389778449] [3.7480850388516975,0.35163507615608836,2.0369628600097345,2012.796028911057,7919.295599332386] [1.4834340654576659,0.7664944722222548,1.3579752400064895,2013.5574170254713,7918.991858554501] [2.8615354652052254,3.2772677011656817,0.3394938100016224,2010.8758062422046,7916.530116603464] [1.8608759780674995,0.4061047550350635,1.3579752400064895,2012.3713790604054,7919.274720260911] [3.256532710485639,0.7278573018600822,0.3394938100016224,2012.2084659798081,7920.070113459953] [1.149880903078424,0.9229293727856711,1.3579752400064895,2013.7862637962348,7918.990367192253] [1.2903243178405184,1.360573603247791,0.6789876200032448,2011.603382207816,7917.845498106381] [1.114769986604779,0.13479725337491694,0.3394938100016224,2012.3478642478287,7918.715459417834] [2.3524279715902443,0.3825009260791303,1.6974690500081118,2012.3979677046916,7919.288142521144] [0.6671064503247266,1.723328976948524,1.0184814300048672,2011.4890356682267,7917.58848667894] [1.114769986604779,0.14854676743144346,0.3394938100016224,2012.361696490521,7918.713470934836] [2.712314384107841,0.12831057030934723,3.0554442900146013,2013.1392222214097,7919.355253822314] [1.439545482648731,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764] [2.018874809211002,0.10379012078487489,2.0369628600097345,2010.9717097915375,7919.224511065221] [0.16677661258118165,0.2948544355081812,2.3764566700113567,2012.2851580809572,7919.394526361516] [0.45644124447075657,1.908703442364545,0.0,2010.8442994671834,7920.6572130649965] [1.6238775639305887,1.7238945912128518,1.0184814300048672,2011.5091692659232,7917.581029867699] [1.2025471522226487,3.234279276129995,0.0,2009.7564704252325,7917.019283420876] [0.49155211908898727,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] [1.650210646647287,0.3097746879132979,2.3764566700113567,2012.792801387762,7919.368676082548] [0.7109950749890757,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984] [0.5705515765161528,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294] df =scaled_features.map(lambda x: (x, )).toDF(["Scaled_data"]) df.show() +--------------------+ | Scaled_data| +--------------------+ |[2.80886929977182...| |[1.71165472954845...| |[1.16743631945983...| |[1.16743631945983...| |[0.43888582808934...| |[0.62321786751579...| |[3.02831221381650...| |[1.78187639507409...| |[2.78253621705513...| |[1.57121123107553...| |[3.05464529653320...| |[0.55299616013474...| |[1.14110315303230...| |[1.79065414512020...| |[1.15865856941371...| |[3.13364487952660...| |[0.0,0.2321492562...| |[1.55365589840495...| |[1.48343406545766...| |[0.13166574842680...| +--------------------+ only showing top 20 rows Spark Session : This is the entry point to the programming spark with Dataframe API & dataset. That allows you to perform various tasks using spark. spark context, hive context, SQL context, now all of it is encapsulated in the session. Before spark 2.0, sparkContext was used to access all spark functionality. The spark driver program uses sparkContext to connect to the cluster through a resource manager. sparkConf creates the sparkContext object, which stores configuration parameter like appName (to identify your spark driver), application, number of core, and memory size of executor running on the worker node. After spark 2.0 onwards these two features are encapsulated in spark session. So each time you want to perform tasks using spark you need to create a session and after execution, you must end the session. Now read the data set using read.csv() you can allow the spark to read the dataset and to execute when it is required. Here I have used one real estate dataset used. Here you can notice the columns such as No and X1 transaction date are independent of the price of the house and the transaction date is not properly given in the datasets. so we will drop those columns colm = ['No','X1 transaction date']df = dataset.select([column for column in dataset.columns if column not in colm]) there is a cool spark syntax is there to do that. if you apply a list comprehension in select() you will get the required data frame. This data frame is different from the Pandas data frame. Well, it is related to the objects created in spark and pandas. Spark data frame is distributed hence you will get the benefit of parallel processing and speed of processing while handling large datasets. Spark assures fault tolerance. So if your data processing got interrupted/failed in between processing then spark can regenerate the failed result set from the lineage. df.printSchema()#outputroot |-- X2 house age: string (nullable = true) |-- X3 distance to the nearest MRT station: string (nullable = true) |-- X4 number of convenience stores: string (nullable = true) |-- X5 latitude: string (nullable = true) |-- X6 longitude: string (nullable = true) |-- Y house price of unit area: string (nullable = true) If you look at the schema of the dataset, it is in the string format. Lets typecast to float. from pyspark.sql.functions import coldf = df.select(*(col(c).cast('float').alias(c) for c in df.columns)) Let’s check for null values. df.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns]).show() Great! there are no null values present. But the column names are a bit longer. So we will now replace those with our own custom names. For renaming the column name there are several techniques that are there, I have used reduce () to do that. You can perform in another way. from functools import reduceoldColumns = df.schema.namesnewColumns = ['Age','Distance_2_MRT','Stores','Latitude','Longitude','Price']df = reduce(lambda df, idx: df.withColumnRenamed(oldColumns[idx], newColumns[idx]),range(len(oldColumns)), df) Try different techniques and let me know as well. Sharing is caring : ) Now we will do split to get Features and Label columns. VectorAssembler: VectorAssembler is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models. from pyspark.ml.feature import VectorAssembler#let's assemble our features together using vectorAssemblerassembler = VectorAssembler( inputCols=features.columns, outputCol="features")output = assembler.transform(df).select('features','Price') This will transform the target and features columns. Now we will split it into train and test dataset. train,test = output.randomSplit([0.75, 0.25]) Let’s now apply a Linear Regression model from pyspark.ml.regression import LinearRegressionlin_reg = LinearRegression(featuresCol = 'features', labelCol='Price')linear_model = lin_reg.fit(train)print("Coefficients: " + str(linear_model.coefficients))print("\nIntercept: " + str(linear_model.intercept))#Output Coefficients: [-0.2845380180805475,-0.004727311005402087,1.187968326885585,201.55230488460887,-43.50846789357342]Intercept: 298.6774040798928 The coefficients for each column and Intercept we got. trainSummary = linear_model.summaryprint("RMSE: %f" % trainSummary.rootMeanSquaredError)print("\nr2: %f" % trainSummary.r2)#OutputRMSE: 9.110080r2: 0.554706 For testing dataset from pyspark.sql.functions import abspredictions = linear_model.transform(test)x =((predictions['Price']-predictions['prediction'])/predictions['Price'])*100predictions = predictions.withColumn('Accuracy',abs(x))predictions.select("prediction","Price","Accuracy","features").show() r — square value for the test dataset from pyspark.ml.evaluation import RegressionEvaluatorpred_evaluator = RegressionEvaluator(predictionCol="prediction", \ labelCol="Price",metricName="r2")print("R Squared (R2) on test data = %g" % pred_evaluator.evaluate(predictions))#outputR Squared (R2) on test data = 0.610204 Let’s now check for adjusted R square. Adjusted R — square: The adjusted R-squared is a modified version of R-squared that has been adjusted for the number of predictors in the model. The adjusted R-squared increases only if the new term improves the model more than would be expected by chance. It decreases when a predictor improves the model by less than expected. We use Adjusted R2 value which penalizes excessive use of such features that do not correlate with the output data. r2 = trainSummary.r2n = df.count()p = len(df.columns)adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1) We got adjusted r squared value 0.54 for training and testing. Let’s now explore more on the LinearRegression() in the spark. lin_reg = LinearRegression(featuresCol = 'features', labelCol='Price',maxIter=50, regParam=0.12, elasticNetParam=0.2)linear_model = lin_reg.fit(train) Here you can apply Lasso, Ridge, Elastic net regularization, alpha values you can modify. There is a very good article on these concepts. This is a shared repository for Learning Apache Spark Notes. This shared repository mainly contains the self-learning and self-teaching notes from Wenqiang during his IMA Data Science Fellowship. Thanks to George Feng, A senior data scientist at ML Lab. I will be sharing other spark implemented ML algorithms in future stories. For suggestions, I will be available on LinkedIn , Gmail , Twiiter &follow my work at GitHub.
[ { "code": null, "e": 186, "s": 172, "text": "Introduction:" }, { "code": null, "e": 639, "s": 186, "text": "PySpark is the Python API written in python to support Apache Spark. Apache Spark is a distributed framework that can handle Big Data analysis. Spark is written in Scala and can be integrated with Python, Scala, Java, R, SQL languages. Spark is basically a computational engine, that works with huge sets of data by processing them in parallel and batch systems. When you down load spark binaries there will separate folders to support above langauges." }, { "code": null, "e": 800, "s": 639, "text": "There are basically two major types of algorithms — transformers : Transforms work with the input datasets and modify it to output datasets using a transform()." }, { "code": null, "e": 904, "s": 800, "text": "Estimators are the algorithms that take input datasets and produces a trained output model using fit()." }, { "code": null, "e": 1153, "s": 904, "text": "In this section, I will be showing the machine learning implementation using Spark and Python. I will be focusing here basic ML algorithm Linear Regression implemented in the context of Spark. The program has been executed in the standalone server." }, { "code": null, "e": 1336, "s": 1153, "text": "First, import the libraries as shown below. And it is the most important to give the path of Spark binaries present in your system. Otherwise, you may face issues in executing codes." }, { "code": null, "e": 1385, "s": 1336, "text": "#\"F:\\DATA\\SPARK\\practice spark\\Real estate.csv\"\n" }, { "code": null, "e": 1655, "s": 1385, "text": "import findspark\nimport pyspark\nfindspark.find()\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.regression import LinearRegression\nimport os\nimport sys\nos.environ['SPARK_HOME']= r'C:\\SPARK\\spark-3.0.0-bin-hadoop2.7'\n" }, { "code": null, "e": 1787, "s": 1655, "text": "if __name__ == \"__main__\":\n spark = SparkSession\\\n .builder\\\n .appName(\"LinearReg_spark\")\\\n .getOrCreate()\n" }, { "code": null, "e": 1845, "s": 1787, "text": "dataset = spark.read.csv('Real estate.csv',header= True)\n" }, { "code": null, "e": 1861, "s": 1845, "text": "dataset.show()\n" }, { "code": null, "e": 5776, "s": 1861, "text": "+---+-------------------+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+\n| No|X1 transaction date|X2 house age|X3 distance to the nearest MRT station|X4 number of convenience stores|X5 latitude|X6 longitude|Y house price of unit area|\n+---+-------------------+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+\n| 1| 2012.917| 32| 84.87882| 10| 24.98298| 121.54024| 37.9|\n| 2| 2012.917| 19.5| 306.5947| 9| 24.98034| 121.53951| 42.2|\n| 3| 2013.583| 13.3| 561.9845| 5| 24.98746| 121.54391| 47.3|\n| 4| 2013.500| 13.3| 561.9845| 5| 24.98746| 121.54391| 54.8|\n| 5| 2012.833| 5| 390.5684| 5| 24.97937| 121.54245| 43.1|\n| 6| 2012.667| 7.1| 2175.03| 3| 24.96305| 121.51254| 32.1|\n| 7| 2012.667| 34.5| 623.4731| 7| 24.97933| 121.53642| 40.3|\n| 8| 2013.417| 20.3| 287.6025| 6| 24.98042| 121.54228| 46.7|\n| 9| 2013.500| 31.7| 5512.038| 1| 24.95095| 121.48458| 18.8|\n| 10| 2013.417| 17.9| 1783.18| 3| 24.96731| 121.51486| 22.1|\n| 11| 2013.083| 34.8| 405.2134| 1| 24.97349| 121.53372| 41.4|\n| 12| 2013.333| 6.3| 90.45606| 9| 24.97433| 121.5431| 58.1|\n| 13| 2012.917| 13| 492.2313| 5| 24.96515| 121.53737| 39.3|\n| 14| 2012.667| 20.4| 2469.645| 4| 24.96108| 121.51046| 23.8|\n| 15| 2013.500| 13.2| 1164.838| 4| 24.99156| 121.53406| 34.3|\n| 16| 2013.583| 35.7| 579.2083| 2| 24.9824| 121.54619| 50.5|\n| 17| 2013.250| 0| 292.9978| 6| 24.97744| 121.54458| 70.1|\n| 18| 2012.750| 17.7| 350.8515| 1| 24.97544| 121.53119| 37.4|\n| 19| 2013.417| 16.9| 368.1363| 8| 24.9675| 121.54451| 42.3|\n| 20| 2012.667| 1.5| 23.38284| 7| 24.96772| 121.54102| 47.7|\n+---+-------------------+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+\nonly showing top 20 rows\n\n" }, { "code": null, "e": 5895, "s": 5776, "text": "colm = ['No','X1 transaction date']\ndf = dataset.select([column for column in dataset.columns if column not in colm])\n" }, { "code": null, "e": 5913, "s": 5895, "text": "df.printSchema()\n" }, { "code": null, "e": 6242, "s": 5913, "text": "root\n |-- X2 house age: string (nullable = true)\n |-- X3 distance to the nearest MRT station: string (nullable = true)\n |-- X4 number of convenience stores: string (nullable = true)\n |-- X5 latitude: string (nullable = true)\n |-- X6 longitude: string (nullable = true)\n |-- Y house price of unit area: string (nullable = true)\n\n" }, { "code": null, "e": 6350, "s": 6242, "text": "from pyspark.sql.functions import col\ndf = df.select(*(col(c).cast('float').alias(c) for c in df.columns))\n" }, { "code": null, "e": 6368, "s": 6350, "text": "df.printSchema()\n" }, { "code": null, "e": 6691, "s": 6368, "text": "root\n |-- X2 house age: float (nullable = true)\n |-- X3 distance to the nearest MRT station: float (nullable = true)\n |-- X4 number of convenience stores: float (nullable = true)\n |-- X5 latitude: float (nullable = true)\n |-- X6 longitude: float (nullable = true)\n |-- Y house price of unit area: float (nullable = true)\n\n" }, { "code": null, "e": 6831, "s": 6691, "text": "from pyspark.sql.functions import col, count, isnan, when\ndf.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns]).show()\n" }, { "code": null, "e": 7523, "s": 6831, "text": "+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+\n|X2 house age|X3 distance to the nearest MRT station|X4 number of convenience stores|X5 latitude|X6 longitude|Y house price of unit area|\n+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+\n| 0| 0| 0| 0| 0| 0|\n+------------+--------------------------------------+-------------------------------+-----------+------------+--------------------------+\n\n" }, { "code": null, "e": 7773, "s": 7523, "text": "from functools import reduce\n\noldColumns = df.schema.names\nnewColumns = ['Age','Distance_2_MRT','Stores','Latitude','Longitude','Price']\n\ndf = reduce(lambda df, idx: df.withColumnRenamed(oldColumns[idx], newColumns[idx]),range(len(oldColumns)), df)\n" }, { "code": null, "e": 7791, "s": 7773, "text": "df.printSchema()\n" }, { "code": null, "e": 8029, "s": 7791, "text": "root\n |-- Age: float (nullable = true)\n |-- Distance_2_MRT: float (nullable = true)\n |-- Stores: float (nullable = true)\n |-- Latitude: float (nullable = true)\n |-- Longitude: float (nullable = true)\n |-- Price: float (nullable = true)\n\n" }, { "code": null, "e": 8040, "s": 8029, "text": "df.show()\n" }, { "code": null, "e": 9363, "s": 8040, "text": "+----+--------------+------+--------+---------+-----+\n| Age|Distance_2_MRT|Stores|Latitude|Longitude|Price|\n+----+--------------+------+--------+---------+-----+\n|32.0| 84.87882| 10.0|24.98298|121.54024| 37.9|\n|19.5| 306.5947| 9.0|24.98034|121.53951| 42.2|\n|13.3| 561.9845| 5.0|24.98746|121.54391| 47.3|\n|13.3| 561.9845| 5.0|24.98746|121.54391| 54.8|\n| 5.0| 390.5684| 5.0|24.97937|121.54245| 43.1|\n| 7.1| 2175.03| 3.0|24.96305|121.51254| 32.1|\n|34.5| 623.4731| 7.0|24.97933|121.53642| 40.3|\n|20.3| 287.6025| 6.0|24.98042|121.54228| 46.7|\n|31.7| 5512.038| 1.0|24.95095|121.48458| 18.8|\n|17.9| 1783.18| 3.0|24.96731|121.51486| 22.1|\n|34.8| 405.2134| 1.0|24.97349|121.53372| 41.4|\n| 6.3| 90.45606| 9.0|24.97433| 121.5431| 58.1|\n|13.0| 492.2313| 5.0|24.96515|121.53737| 39.3|\n|20.4| 2469.645| 4.0|24.96108|121.51046| 23.8|\n|13.2| 1164.838| 4.0|24.99156|121.53406| 34.3|\n|35.7| 579.2083| 2.0| 24.9824|121.54619| 50.5|\n| 0.0| 292.9978| 6.0|24.97744|121.54458| 70.1|\n|17.7| 350.8515| 1.0|24.97544|121.53119| 37.4|\n|16.9| 368.1363| 8.0| 24.9675|121.54451| 42.3|\n| 1.5| 23.38284| 7.0|24.96772|121.54102| 47.7|\n+----+--------------+------+--------+---------+-----+\nonly showing top 20 rows\n\n" }, { "code": null, "e": 9392, "s": 9363, "text": "features = df.drop('Price')\n" }, { "code": null, "e": 9587, "s": 9392, "text": "from pyspark.ml.feature import VectorAssembler\n#let's assemble our features together using vectorAssembler\nassembler = VectorAssembler(\n inputCols=features.columns,\n outputCol=\"features\")\n" }, { "code": null, "e": 9648, "s": 9587, "text": "output = assembler.transform(df).select('features','Price')\n" }, { "code": null, "e": 9695, "s": 9648, "text": "train,test = output.randomSplit([0.75, 0.25])\n" }, { "code": null, "e": 9709, "s": 9695, "text": "train.show()\n" }, { "code": null, "e": 10432, "s": 9709, "text": "+--------------------+-----+\n| features|Price|\n+--------------------+-----+\n|[0.0,185.42959594...| 37.9|\n|[0.0,185.42959594...| 45.5|\n|[0.0,185.42959594...| 52.2|\n|[0.0,185.42959594...| 55.2|\n|[0.0,208.39050292...| 44.0|\n|[0.0,208.39050292...| 45.7|\n|[0.0,274.01440429...| 43.5|\n|[0.0,274.01440429...| 45.4|\n|[0.0,274.01440429...| 52.2|\n|[0.0,292.99780273...| 63.3|\n|[0.0,292.99780273...| 69.7|\n|[0.0,292.99780273...| 70.1|\n|[0.0,292.99780273...| 73.6|\n|[0.0,338.96789550...| 44.9|\n|[0.0,338.96789550...| 50.8|\n|[1.0,193.58450317...| 50.7|\n|[1.10000002384185...| 45.1|\n|[1.10000002384185...| 48.6|\n|[1.10000002384185...| 49.0|\n|[1.10000002384185...| 54.4|\n+--------------------+-----+\nonly showing top 20 rows\n\n" }, { "code": null, "e": 10445, "s": 10432, "text": "test.show()\n" }, { "code": null, "e": 11168, "s": 10445, "text": "+--------------------+-----+\n| features|Price|\n+--------------------+-----+\n|[0.0,185.42959594...| 55.3|\n|[0.0,292.99780273...| 71.0|\n|[2.09999990463256...| 45.5|\n|[3.70000004768371...| 41.6|\n|[4.09999990463256...| 31.3|\n|[5.09999990463256...| 28.9|\n|[5.09999990463256...| 35.6|\n|[6.19999980926513...| 31.3|\n|[6.30000019073486...| 58.1|\n|[6.40000009536743...| 59.5|\n|[6.59999990463256...| 58.1|\n|[6.80000019073486...| 54.4|\n|[7.59999990463256...| 27.7|\n|[8.0,132.54690551...| 47.3|\n|[8.0,2216.6120605...| 23.9|\n|[8.10000038146972...| 51.6|\n|[8.5,104.81009674...| 56.8|\n|[9.0,1402.0159912...| 38.5|\n|[10.0,942.4663696...| 43.5|\n|[10.1000003814697...| 47.9|\n+--------------------+-----+\nonly showing top 20 rows\n\n" }, { "code": null, "e": 11325, "s": 11168, "text": "from pyspark.ml.regression import LinearRegression\nlin_reg = LinearRegression(featuresCol = 'features', labelCol='Price')\nlinear_model = lin_reg.fit(train)\n" }, { "code": null, "e": 11436, "s": 11325, "text": "print(\"Coefficients: \" + str(linear_model.coefficients))\nprint(\"\\nIntercept: \" + str(linear_model.intercept))\n" }, { "code": null, "e": 11581, "s": 11436, "text": "Coefficients: [-0.2845380180805475,-0.004727311005402087,1.187968326885585,201.55230488460887,-43.50846789357342]\n\nIntercept: 298.6774040798928\n" }, { "code": null, "e": 11708, "s": 11581, "text": "trainSummary = linear_model.summary\nprint(\"RMSE: %f\" % trainSummary.rootMeanSquaredError)\nprint(\"\\nr2: %f\" % trainSummary.r2)\n" }, { "code": null, "e": 11738, "s": 11708, "text": "RMSE: 9.110080\n\nr2: 0.554706\n" }, { "code": null, "e": 12026, "s": 11738, "text": "from pyspark.sql.functions import abs\npredictions = linear_model.transform(test)\nx =((predictions['Price']-predictions['prediction'])/predictions['Price'])*100\npredictions = predictions.withColumn('Accuracy',abs(x))\npredictions.select(\"prediction\",\"Price\",\"Accuracy\",\"features\").show()\n" }, { "code": null, "e": 13685, "s": 12026, "text": "+------------------+-----+-------------------+--------------------+\n| prediction|Price| Accuracy| features|\n+------------------+-----+-------------------+--------------------+\n| 43.12547834643925| 55.3| 22.01540878586896|[0.0,185.42959594...|\n| 50.46230673101314| 71.0| 28.926328547868813|[0.0,292.99780273...|\n| 47.46100355578261| 45.5| 4.309897924796947|[2.09999990463256...|\n| 46.8530780492884| 41.6| 12.62759559579116|[3.70000004768371...|\n|35.434011977095054| 31.3| 13.207708756553762|[4.09999990463256...|\n|39.619817126403234| 28.9| 37.09279463450084|[5.09999990463256...|\n| 39.33273298109731| 35.6| 10.485209738673646|[5.09999990463256...|\n|29.351057585089677| 31.3| 6.226650797049346|[6.19999980926513...|\n| 52.62887519936618| 58.1| 9.416735659970566|[6.30000019073486...|\n| 52.60042142469416| 59.5| 11.595930378665274|[6.40000009536743...|\n| 52.54351387534922| 58.1| 9.563657047679346|[6.59999990463256...|\n| 54.38035537626644| 54.4|0.03611424459818044|[6.80000019073486...|\n| 34.33264716981199| 27.7| 23.944571206461944|[7.59999990463256...|\n| 53.83264404188236| 47.3| 13.811088605057204|[8.0,132.54690551...|\n|34.562892118922775| 23.9| 44.61461368445082|[8.0,2216.6120605...|\n| 45.87250193662936| 51.6| 11.099799819498518|[8.10000038146972...|\n| 45.75868683793948| 56.8| 19.438930541247075|[8.5,104.81009674...|\n| 37.9322164579217| 38.5| 1.47476244695663|[9.0,1402.0159912...|\n| 38.51099156627248| 43.5| 11.468984905120735|[10.0,942.4663696...|\n| 48.37043980769164| 47.9| 0.9821258180097748|[10.1000003814697...|\n+------------------+-----+-------------------+--------------------+\nonly showing top 20 rows\n\n" }, { "code": null, "e": 13939, "s": 13685, "text": "from pyspark.ml.evaluation import RegressionEvaluator\npred_evaluator = RegressionEvaluator(predictionCol=\"prediction\", \\\n labelCol=\"Price\",metricName=\"r2\")\nprint(\"R Squared (R2) on test data = %g\" % pred_evaluator.evaluate(predictions))\n" }, { "code": null, "e": 13979, "s": 13939, "text": "R Squared (R2) on test data = 0.610204\n" }, { "code": null, "e": 14141, "s": 13979, "text": "def adj_r2(x):\n r2 = trainSummary.r2\n n = df.count()\n p = len(df.columns)\n adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)\n return adjusted_r2\nadj_r2(train)\n" }, { "code": null, "e": 14159, "s": 14141, "text": "0.548141210028837" }, { "code": null, "e": 14173, "s": 14159, "text": "adj_r2(test)\n" }, { "code": null, "e": 14191, "s": 14173, "text": "0.548141210028837" }, { "code": null, "e": 14344, "s": 14191, "text": "lin_reg = LinearRegression(featuresCol = 'features', labelCol='Price',maxIter=50, regParam=0.12, elasticNetParam=0.2)\nlinear_model = lin_reg.fit(train)\n" }, { "code": null, "e": 14387, "s": 14344, "text": "linear_model.summary.rootMeanSquaredError\n" }, { "code": null, "e": 14405, "s": 14387, "text": "9.110906766525105" }, { "code": null, "e": 14459, "s": 14405, "text": "features_rdd = features.rdd.map(lambda row: row[0:])\n" }, { "code": null, "e": 14483, "s": 14459, "text": "features_rdd.collect()\n" }, { "code": null, "e": 51080, "s": 14483, "text": "[(32.0, 84.87882232666016, 10.0, 24.982980728149414, 121.54023742675781),\n (19.5, 306.5946960449219, 9.0, 24.98033905029297, 121.53951263427734),\n (13.300000190734863,\n 561.9844970703125,\n 5.0,\n 24.987459182739258,\n 121.54390716552734),\n (13.300000190734863,\n 561.9844970703125,\n 5.0,\n 24.987459182739258,\n 121.54390716552734),\n (5.0, 390.5683898925781, 5.0, 24.9793701171875, 121.54244995117188),\n (7.099999904632568,\n 2175.030029296875,\n 3.0,\n 24.963050842285156,\n 121.51254272460938),\n (34.5, 623.4730834960938, 7.0, 24.97933006286621, 121.53642272949219),\n (20.299999237060547,\n 287.6025085449219,\n 6.0,\n 24.980419158935547,\n 121.54228210449219),\n (31.700000762939453,\n 5512.0380859375,\n 1.0,\n 24.950950622558594,\n 121.48458099365234),\n (17.899999618530273,\n 1783.1800537109375,\n 3.0,\n 24.967309951782227,\n 121.51486206054688),\n (34.79999923706055,\n 405.2134094238281,\n 1.0,\n 24.97348976135254,\n 121.53372192382812),\n (6.300000190734863,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (13.0, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406),\n (20.399999618530273,\n 2469.64501953125,\n 4.0,\n 24.96108055114746,\n 121.51045989990234),\n (13.199999809265137,\n 1164.8380126953125,\n 4.0,\n 24.991559982299805,\n 121.5340576171875),\n (35.70000076293945,\n 579.2083129882812,\n 2.0,\n 24.98240089416504,\n 121.54618835449219),\n (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461),\n (17.700000762939453,\n 350.85150146484375,\n 1.0,\n 24.975439071655273,\n 121.53118896484375),\n (16.899999618530273,\n 368.13629150390625,\n 8.0,\n 24.967500686645508,\n 121.54450988769531),\n (1.5, 23.38283920288086, 7.0, 24.96772003173828, 121.54102325439453),\n (4.5, 2275.876953125, 3.0, 24.9631404876709, 121.51151275634766),\n (10.5, 279.172607421875, 7.0, 24.97528076171875, 121.54541015625),\n (14.699999809265137,\n 1360.1390380859375,\n 1.0,\n 24.95203971862793,\n 121.54842376708984),\n (10.100000381469727,\n 279.172607421875,\n 7.0,\n 24.97528076171875,\n 121.54541015625),\n (39.599998474121094,\n 480.69769287109375,\n 4.0,\n 24.973529815673828,\n 121.53884887695312),\n (29.299999237060547,\n 1487.8680419921875,\n 2.0,\n 24.975419998168945,\n 121.51725769042969),\n (3.0999999046325684,\n 383.8623962402344,\n 5.0,\n 24.980850219726562,\n 121.54390716552734),\n (10.399999618530273,\n 276.4490051269531,\n 5.0,\n 24.955930709838867,\n 121.53913116455078),\n (19.200000762939453,\n 557.47802734375,\n 4.0,\n 24.97418975830078,\n 121.53797149658203),\n (7.099999904632568,\n 451.2438049316406,\n 5.0,\n 24.975629806518555,\n 121.54694366455078),\n (25.899999618530273,\n 4519.68994140625,\n 0.0,\n 24.948259353637695,\n 121.4958724975586),\n (29.600000381469727,\n 769.4033813476562,\n 7.0,\n 24.98280906677246,\n 121.5340805053711),\n (37.900001525878906,\n 488.57269287109375,\n 1.0,\n 24.97348976135254,\n 121.53450775146484),\n (16.5, 323.6549987792969, 6.0, 24.978410720825195, 121.54280853271484),\n (15.399999618530273,\n 205.36700439453125,\n 7.0,\n 24.984189987182617,\n 121.54242706298828),\n (13.899999618530273,\n 4079.41796875,\n 0.0,\n 25.014589309692383,\n 121.51815795898438),\n (14.699999809265137,\n 1935.009033203125,\n 2.0,\n 24.96385955810547,\n 121.51457977294922),\n (12.0, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984),\n (3.0999999046325684,\n 577.9614868164062,\n 6.0,\n 24.972009658813477,\n 121.5472183227539),\n (16.200000762939453,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (13.600000381469727,\n 4082.014892578125,\n 0.0,\n 24.94154930114746,\n 121.5038070678711),\n (16.799999237060547,\n 4066.5869140625,\n 0.0,\n 24.942970275878906,\n 121.50341796875),\n (36.099998474121094,\n 519.461669921875,\n 5.0,\n 24.963050842285156,\n 121.53758239746094),\n (34.400001525878906,\n 512.787109375,\n 6.0,\n 24.98748016357422,\n 121.54300689697266),\n (2.700000047683716,\n 533.4761962890625,\n 4.0,\n 24.974449157714844,\n 121.54765319824219),\n (36.599998474121094,\n 488.8193054199219,\n 8.0,\n 24.970149993896484,\n 121.54493713378906),\n (21.700000762939453,\n 463.9623107910156,\n 9.0,\n 24.970300674438477,\n 121.5445785522461),\n (35.900001525878906,\n 640.7390747070312,\n 3.0,\n 24.975629806518555,\n 121.53714752197266),\n (24.200000762939453,\n 4605.7490234375,\n 0.0,\n 24.946840286254883,\n 121.49578094482422),\n (29.399999618530273,\n 4510.35888671875,\n 1.0,\n 24.949249267578125,\n 121.49542236328125),\n (21.700000762939453,\n 512.5487060546875,\n 4.0,\n 24.974000930786133,\n 121.53842163085938),\n (31.299999237060547,\n 1758.406005859375,\n 1.0,\n 24.95401954650879,\n 121.55281829833984),\n (32.099998474121094,\n 1438.5789794921875,\n 3.0,\n 24.97418975830078,\n 121.51750183105469),\n (13.300000190734863,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (16.100000381469727,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (31.700000762939453,\n 1160.6319580078125,\n 0.0,\n 24.94968032836914,\n 121.53009033203125),\n (33.599998474121094,\n 371.24951171875,\n 8.0,\n 24.9725399017334,\n 121.54058837890625),\n (3.5, 56.47425079345703, 7.0, 24.957439422607422, 121.537109375),\n (30.299999237060547,\n 4510.35888671875,\n 1.0,\n 24.949249267578125,\n 121.49542236328125),\n (13.300000190734863,\n 336.0531921386719,\n 5.0,\n 24.957759857177734,\n 121.53437805175781),\n (11.0, 1931.20703125, 2.0, 24.96364974975586, 121.51470947265625),\n (5.300000190734863,\n 259.66070556640625,\n 6.0,\n 24.975849151611328,\n 121.54515838623047),\n (17.200000762939453,\n 2175.876953125,\n 3.0,\n 24.963029861450195,\n 121.51254272460938),\n (2.5999999046325684,\n 533.4761962890625,\n 4.0,\n 24.974449157714844,\n 121.54765319824219),\n (17.5, 995.75537109375, 0.0, 24.963050842285156, 121.54914855957031),\n (40.099998474121094,\n 123.7428970336914,\n 8.0,\n 24.976350784301758,\n 121.54328918457031),\n (1.0, 193.58450317382812, 6.0, 24.965709686279297, 121.5408935546875),\n (8.5, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461),\n (30.399999618530273,\n 464.2229919433594,\n 6.0,\n 24.979639053344727,\n 121.53804779052734),\n (12.5, 561.9844970703125, 5.0, 24.987459182739258, 121.54390716552734),\n (6.599999904632568,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (35.5, 640.7390747070312, 3.0, 24.975629806518555, 121.53714752197266),\n (32.5, 424.544189453125, 8.0, 24.97587013244629, 121.53913116455078),\n (13.800000190734863,\n 4082.014892578125,\n 0.0,\n 24.94154930114746,\n 121.5038070678711),\n (6.800000190734863,\n 379.5574951171875,\n 10.0,\n 24.983430862426758,\n 121.5376205444336),\n (12.300000190734863,\n 1360.1390380859375,\n 1.0,\n 24.95203971862793,\n 121.54842376708984),\n (35.900001525878906,\n 616.400390625,\n 3.0,\n 24.977230072021484,\n 121.53766632080078),\n (20.5, 2185.1279296875, 3.0, 24.963220596313477, 121.51236724853516),\n (38.20000076293945,\n 552.4370727539062,\n 2.0,\n 24.975980758666992,\n 121.5338134765625),\n (18.0, 1414.8370361328125, 1.0, 24.951820373535156, 121.54886627197266),\n (11.800000190734863,\n 533.4761962890625,\n 4.0,\n 24.974449157714844,\n 121.54765319824219),\n (30.799999237060547,\n 377.79559326171875,\n 6.0,\n 24.964269638061523,\n 121.53964233398438),\n (13.199999809265137,\n 150.9346923828125,\n 7.0,\n 24.96725082397461,\n 121.54251861572266),\n (25.299999237060547,\n 2707.39208984375,\n 3.0,\n 24.960559844970703,\n 121.50830841064453),\n (15.100000381469727,\n 383.2804870605469,\n 7.0,\n 24.967350006103516,\n 121.54463958740234),\n (0.0, 338.9678955078125, 9.0, 24.968530654907227, 121.54412841796875),\n (1.7999999523162842,\n 1455.7979736328125,\n 1.0,\n 24.951200485229492,\n 121.54900360107422),\n (16.899999618530273,\n 4066.5869140625,\n 0.0,\n 24.942970275878906,\n 121.50341796875),\n (8.899999618530273,\n 1406.4300537109375,\n 0.0,\n 24.985729217529297,\n 121.52758026123047),\n (23.0, 3947.945068359375, 0.0, 24.947830200195312, 121.50243377685547),\n (0.0, 274.014404296875, 1.0, 24.97480010986328, 121.53058624267578),\n (9.100000381469727,\n 1402.0159912109375,\n 0.0,\n 24.985689163208008,\n 121.52760314941406),\n (20.600000381469727,\n 2469.64501953125,\n 4.0,\n 24.96108055114746,\n 121.51045989990234),\n (31.899999618530273,\n 1146.3289794921875,\n 0.0,\n 24.949199676513672,\n 121.53076171875),\n (40.900001525878906,\n 167.59890747070312,\n 5.0,\n 24.966299057006836,\n 121.5402603149414),\n (8.0, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461),\n (6.400000095367432,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (28.399999618530273,\n 617.4423828125,\n 3.0,\n 24.977460861206055,\n 121.53298950195312),\n (16.399999618530273,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (6.400000095367432,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (17.5, 964.7495727539062, 4.0, 24.988719940185547, 121.53411102294922),\n (12.699999809265137,\n 170.12890625,\n 1.0,\n 24.973709106445312,\n 121.52983856201172),\n (1.100000023841858,\n 193.58450317382812,\n 6.0,\n 24.965709686279297,\n 121.5408935546875),\n (0.0, 208.3905029296875, 6.0, 24.956180572509766, 121.53843688964844),\n (32.70000076293945,\n 392.4458923339844,\n 6.0,\n 24.963979721069336,\n 121.5425033569336),\n (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461),\n (17.200000762939453,\n 189.51809692382812,\n 8.0,\n 24.977069854736328,\n 121.54308319091797),\n (12.199999809265137,\n 1360.1390380859375,\n 1.0,\n 24.95203971862793,\n 121.54842376708984),\n (31.399999618530273,\n 592.5006103515625,\n 2.0,\n 24.97260093688965,\n 121.53560638427734),\n (4.0, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961),\n (8.100000381469727,\n 104.81009674072266,\n 5.0,\n 24.966739654541016,\n 121.5406723022461),\n (33.29999923706055,\n 196.61720275878906,\n 7.0,\n 24.97701072692871,\n 121.542236328125),\n (9.899999618530273,\n 2102.427001953125,\n 3.0,\n 24.960439682006836,\n 121.51461791992188),\n (14.800000190734863,\n 393.2605895996094,\n 6.0,\n 24.961719512939453,\n 121.53811645507812),\n (30.600000381469727,\n 143.8383026123047,\n 8.0,\n 24.981550216674805,\n 121.54141998291016),\n (20.600000381469727,\n 737.9160766601562,\n 2.0,\n 24.980920791625977,\n 121.54739379882812),\n (30.899999618530273,\n 6396.283203125,\n 1.0,\n 24.943750381469727,\n 121.47882843017578),\n (13.600000381469727,\n 4197.34912109375,\n 0.0,\n 24.93885040283203,\n 121.50382995605469),\n (25.299999237060547,\n 1583.7220458984375,\n 3.0,\n 24.96622085571289,\n 121.51708984375),\n (16.600000381469727,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (13.300000190734863,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (13.600000381469727,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (31.5, 414.9476013183594, 4.0, 24.981990814208984, 121.54463958740234),\n (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734),\n (9.899999618530273,\n 279.172607421875,\n 7.0,\n 24.97528076171875,\n 121.54541015625),\n (1.100000023841858,\n 193.58450317382812,\n 6.0,\n 24.965709686279297,\n 121.5408935546875),\n (38.599998474121094,\n 804.689697265625,\n 4.0,\n 24.97838020324707,\n 121.5347671508789),\n (3.799999952316284,\n 383.8623962402344,\n 5.0,\n 24.980850219726562,\n 121.54390716552734),\n (41.29999923706055,\n 124.99120330810547,\n 6.0,\n 24.966739654541016,\n 121.54039001464844),\n (38.5, 216.83290100097656, 7.0, 24.980859756469727, 121.54161834716797),\n (29.600000381469727,\n 535.5269775390625,\n 8.0,\n 24.980920791625977,\n 121.53652954101562),\n (4.0, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961),\n (26.600000381469727,\n 482.7580871582031,\n 5.0,\n 24.97433090209961,\n 121.53862762451172),\n (18.0, 373.3937072753906, 8.0, 24.986600875854492, 121.54081726074219),\n (33.400001525878906,\n 186.96859741210938,\n 6.0,\n 24.966039657592773,\n 121.54210662841797),\n (18.899999618530273,\n 1009.2349853515625,\n 0.0,\n 24.96356964111328,\n 121.54950714111328),\n (11.399999618530273,\n 390.5683898925781,\n 5.0,\n 24.9793701171875,\n 121.54244995117188),\n (13.600000381469727,\n 319.07080078125,\n 6.0,\n 24.964950561523438,\n 121.54277038574219),\n (10.0, 942.4663696289062, 0.0, 24.978429794311523, 121.52406311035156),\n (12.899999618530273,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (16.200000762939453,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (5.099999904632568,\n 1559.8270263671875,\n 3.0,\n 24.972129821777344,\n 121.51627349853516),\n (19.799999237060547,\n 640.6071166992188,\n 5.0,\n 24.970169067382812,\n 121.54647064208984),\n (13.600000381469727,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (11.899999618530273,\n 1360.1390380859375,\n 1.0,\n 24.95203971862793,\n 121.54842376708984),\n (2.0999999046325684,\n 451.2438049316406,\n 5.0,\n 24.975629806518555,\n 121.54694366455078),\n (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734),\n (3.200000047683716,\n 489.8821105957031,\n 8.0,\n 24.970169067382812,\n 121.54493713378906),\n (16.399999618530273,\n 3780.590087890625,\n 0.0,\n 24.93292999267578,\n 121.51203155517578),\n (34.900001525878906,\n 179.45379638671875,\n 8.0,\n 24.97348976135254,\n 121.54244995117188),\n (35.79999923706055,\n 170.73109436035156,\n 7.0,\n 24.96718978881836,\n 121.54268646240234),\n (4.900000095367432,\n 387.7720947265625,\n 9.0,\n 24.98118019104004,\n 121.53787994384766),\n (12.0, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984),\n (6.5, 376.1708984375, 6.0, 24.954179763793945, 121.5371322631836),\n (16.899999618530273,\n 4066.5869140625,\n 0.0,\n 24.942970275878906,\n 121.50341796875),\n (13.800000190734863,\n 4082.014892578125,\n 0.0,\n 24.94154930114746,\n 121.5038070678711),\n (30.700000762939453,\n 1264.72998046875,\n 0.0,\n 24.948829650878906,\n 121.529541015625),\n (16.100000381469727,\n 815.931396484375,\n 4.0,\n 24.97886085510254,\n 121.53463745117188),\n (11.600000381469727,\n 390.5683898925781,\n 5.0,\n 24.9793701171875,\n 121.54244995117188),\n (15.5, 815.931396484375, 4.0, 24.97886085510254, 121.53463745117188),\n (3.5, 49.661048889160156, 8.0, 24.95836067199707, 121.53755950927734),\n (19.200000762939453,\n 616.400390625,\n 3.0,\n 24.977230072021484,\n 121.53766632080078),\n (16.0, 4066.5869140625, 0.0, 24.942970275878906, 121.50341796875),\n (8.5, 104.81009674072266, 5.0, 24.966739654541016, 121.5406723022461),\n (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734),\n (13.699999809265137,\n 1236.56396484375,\n 1.0,\n 24.976940155029297,\n 121.55390930175781),\n (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461),\n (28.200000762939453,\n 330.08538818359375,\n 8.0,\n 24.974079132080078,\n 121.54010772705078),\n (27.600000381469727,\n 515.1121826171875,\n 5.0,\n 24.962989807128906,\n 121.54319763183594),\n (8.399999618530273,\n 1962.6280517578125,\n 1.0,\n 24.954679489135742,\n 121.5548095703125),\n (24.0, 4527.68701171875, 0.0, 24.947410583496094, 121.49627685546875),\n (3.5999999046325684,\n 383.8623962402344,\n 5.0,\n 24.980850219726562,\n 121.54390716552734),\n (6.599999904632568,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (41.29999923706055,\n 401.8807067871094,\n 4.0,\n 24.983259201049805,\n 121.54460144042969),\n (4.300000190734863,\n 432.03851318359375,\n 7.0,\n 24.980499267578125,\n 121.53778076171875),\n (30.200000762939453,\n 472.17449951171875,\n 3.0,\n 24.970050811767578,\n 121.53758239746094),\n (13.899999618530273,\n 4573.77880859375,\n 0.0,\n 24.94866943359375,\n 121.49507141113281),\n (33.0, 181.07659912109375, 9.0, 24.976970672607422, 121.54261779785156),\n (13.100000381469727,\n 1144.43603515625,\n 4.0,\n 24.99176025390625,\n 121.53456115722656),\n (14.0, 438.8512878417969, 1.0, 24.974929809570312, 121.52729797363281),\n (26.899999618530273,\n 4449.27001953125,\n 0.0,\n 24.9489803314209,\n 121.49620819091797),\n (11.600000381469727,\n 201.89390563964844,\n 8.0,\n 24.98488998413086,\n 121.54120635986328),\n (13.5, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961),\n (17.0, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711),\n (14.100000381469727,\n 2615.465087890625,\n 0.0,\n 24.9549503326416,\n 121.56173706054688),\n (31.399999618530273,\n 1447.2860107421875,\n 3.0,\n 24.972850799560547,\n 121.51730346679688),\n (20.899999618530273,\n 2185.1279296875,\n 3.0,\n 24.963220596313477,\n 121.51236724853516),\n (8.899999618530273,\n 3078.176025390625,\n 0.0,\n 24.954639434814453,\n 121.56626892089844),\n (34.79999923706055,\n 190.03919982910156,\n 8.0,\n 24.977069854736328,\n 121.54312133789062),\n (16.299999237060547,\n 4066.5869140625,\n 0.0,\n 24.942970275878906,\n 121.50341796875),\n (35.29999923706055,\n 616.573486328125,\n 8.0,\n 24.979450225830078,\n 121.53642272949219),\n (13.199999809265137,\n 750.0703735351562,\n 2.0,\n 24.973709106445312,\n 121.54950714111328),\n (43.79999923706055,\n 57.58945083618164,\n 7.0,\n 24.967500686645508,\n 121.54068756103516),\n (9.699999809265137,\n 421.47900390625,\n 5.0,\n 24.982460021972656,\n 121.54476928710938),\n (15.199999809265137,\n 3771.89501953125,\n 0.0,\n 24.933629989624023,\n 121.51158142089844),\n (15.199999809265137,\n 461.1015930175781,\n 5.0,\n 24.95425033569336,\n 121.53990173339844),\n (22.799999237060547,\n 707.9066772460938,\n 2.0,\n 24.981000900268555,\n 121.54712677001953),\n (34.400001525878906,\n 126.72859954833984,\n 8.0,\n 24.968809127807617,\n 121.5408935546875),\n (34.0, 157.60519409179688, 7.0, 24.966279983520508, 121.54196166992188),\n (18.200000762939453,\n 451.64190673828125,\n 8.0,\n 24.969449996948242,\n 121.5448989868164),\n (17.399999618530273,\n 995.75537109375,\n 0.0,\n 24.963050842285156,\n 121.54914855957031),\n (13.100000381469727,\n 561.9844970703125,\n 5.0,\n 24.987459182739258,\n 121.54390716552734),\n (38.29999923706055,\n 642.698486328125,\n 3.0,\n 24.975589752197266,\n 121.5371322631836),\n (15.600000381469727,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (18.0, 1414.8370361328125, 1.0, 24.951820373535156, 121.54886627197266),\n (12.800000190734863,\n 1449.7220458984375,\n 3.0,\n 24.972890853881836,\n 121.51728057861328),\n (22.200000762939453,\n 379.5574951171875,\n 10.0,\n 24.983430862426758,\n 121.5376205444336),\n (38.5, 665.0635986328125, 3.0, 24.97503089904785, 121.53691864013672),\n (11.5, 1360.1390380859375, 1.0, 24.95203971862793, 121.54842376708984),\n (34.79999923706055,\n 175.62939453125,\n 8.0,\n 24.97347068786621,\n 121.54270935058594),\n (5.199999809265137,\n 390.5683898925781,\n 5.0,\n 24.9793701171875,\n 121.54244995117188),\n (0.0, 274.014404296875, 1.0, 24.97480010986328, 121.53058624267578),\n (17.600000381469727,\n 1805.6650390625,\n 2.0,\n 24.986719131469727,\n 121.52091217041016),\n (6.199999809265137,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (18.100000381469727,\n 1783.1800537109375,\n 3.0,\n 24.967309951782227,\n 121.51486206054688),\n (19.200000762939453,\n 383.712890625,\n 8.0,\n 24.972000122070312,\n 121.54476928710938),\n (37.79999923706055,\n 590.92919921875,\n 1.0,\n 24.97153091430664,\n 121.53559112548828),\n (28.0, 372.62420654296875, 6.0, 24.97838020324707, 121.54119110107422),\n (13.600000381469727,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (29.299999237060547,\n 529.777099609375,\n 8.0,\n 24.981019973754883,\n 121.53655242919922),\n (37.20000076293945,\n 186.51010131835938,\n 9.0,\n 24.97702980041504,\n 121.54264831542969),\n (9.0, 1402.0159912109375, 0.0, 24.985689163208008, 121.52760314941406),\n (30.600000381469727,\n 431.11138916015625,\n 10.0,\n 24.981229782104492,\n 121.53742980957031),\n (9.100000381469727,\n 1402.0159912109375,\n 0.0,\n 24.985689163208008,\n 121.52760314941406),\n (34.5, 324.94189453125, 6.0, 24.978139877319336, 121.54170227050781),\n (1.100000023841858,\n 193.58450317382812,\n 6.0,\n 24.965709686279297,\n 121.5408935546875),\n (16.5, 4082.014892578125, 0.0, 24.94154930114746, 121.5038070678711),\n (32.400001525878906,\n 265.0609130859375,\n 8.0,\n 24.9805908203125,\n 121.53986358642578),\n (11.899999618530273,\n 3171.3291015625,\n 0.0,\n 25.001150131225586,\n 121.51776123046875),\n (31.0, 1156.4119873046875, 0.0, 24.94890022277832, 121.53095245361328),\n (4.0, 2147.3759765625, 3.0, 24.962989807128906, 121.5128402709961),\n (16.200000762939453,\n 4074.736083984375,\n 0.0,\n 24.942350387573242,\n 121.50357055664062),\n (27.100000381469727,\n 4412.76513671875,\n 1.0,\n 24.950319290161133,\n 121.4958724975586),\n (39.70000076293945,\n 333.3678894042969,\n 9.0,\n 24.980159759521484,\n 121.53932189941406),\n (8.0, 2216.612060546875, 4.0, 24.96006965637207, 121.51361083984375),\n (12.899999618530273,\n 250.63099670410156,\n 7.0,\n 24.966060638427734,\n 121.54296875),\n (3.5999999046325684,\n 373.8388977050781,\n 10.0,\n 24.983219146728516,\n 121.53765106201172),\n (13.0, 732.852783203125, 0.0, 24.976680755615234, 121.52517700195312),\n (12.800000190734863,\n 732.852783203125,\n 0.0,\n 24.976680755615234,\n 121.52517700195312),\n (18.100000381469727,\n 837.7233276367188,\n 0.0,\n 24.963340759277344,\n 121.54766845703125),\n (11.0, 1712.6319580078125, 2.0, 24.964120864868164, 121.5167007446289),\n (13.699999809265137,\n 250.63099670410156,\n 7.0,\n 24.966060638427734,\n 121.54296875),\n (2.0, 2077.389892578125, 3.0, 24.96356964111328, 121.51329040527344),\n (32.79999923706055,\n 204.17050170898438,\n 8.0,\n 24.98236083984375,\n 121.53923034667969),\n (4.800000190734863,\n 1559.8270263671875,\n 3.0,\n 24.972129821777344,\n 121.51627349853516),\n (7.5, 639.6198120117188, 5.0, 24.972579956054688, 121.54814147949219),\n (16.399999618530273,\n 389.8218994140625,\n 6.0,\n 24.964120864868164,\n 121.54273223876953),\n (21.700000762939453,\n 1055.0670166015625,\n 0.0,\n 24.96211051940918,\n 121.54927825927734),\n (19.0, 1009.2349853515625, 0.0, 24.96356964111328, 121.54950714111328),\n (18.0, 6306.15283203125, 1.0, 24.957429885864258, 121.47515869140625),\n (39.20000076293945,\n 424.71319580078125,\n 7.0,\n 24.97429084777832,\n 121.53916931152344),\n (31.700000762939453,\n 1159.4539794921875,\n 0.0,\n 24.949600219726562,\n 121.53018188476562),\n (5.900000095367432,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (30.399999618530273,\n 1735.594970703125,\n 2.0,\n 24.96463966369629,\n 121.51622772216797),\n (1.100000023841858,\n 329.9747009277344,\n 5.0,\n 24.982540130615234,\n 121.54395294189453),\n (31.5, 5512.0380859375, 1.0, 24.950950622558594, 121.48458099365234),\n (14.600000381469727,\n 339.2289123535156,\n 1.0,\n 24.975189208984375,\n 121.53150939941406),\n (17.299999237060547,\n 444.1333923339844,\n 1.0,\n 24.97500991821289,\n 121.52729797363281),\n (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461),\n (17.700000762939453,\n 837.7233276367188,\n 0.0,\n 24.963340759277344,\n 121.54766845703125),\n (17.0, 1485.0970458984375, 4.0, 24.97072982788086, 121.51699829101562),\n (16.200000762939453,\n 2288.010986328125,\n 3.0,\n 24.958850860595703,\n 121.51358795166016),\n (15.899999618530273,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (3.9000000953674316,\n 2147.3759765625,\n 3.0,\n 24.962989807128906,\n 121.5128402709961),\n (32.599998474121094,\n 493.6570129394531,\n 7.0,\n 24.969680786132812,\n 121.54521942138672),\n (15.699999809265137,\n 815.931396484375,\n 4.0,\n 24.97886085510254,\n 121.53463745117188),\n (17.799999237060547,\n 1783.1800537109375,\n 3.0,\n 24.967309951782227,\n 121.51486206054688),\n (34.70000076293945,\n 482.7580871582031,\n 5.0,\n 24.97433090209961,\n 121.53862762451172),\n (17.200000762939453,\n 390.5683898925781,\n 5.0,\n 24.9793701171875,\n 121.54244995117188),\n (17.600000381469727,\n 837.7233276367188,\n 0.0,\n 24.963340759277344,\n 121.54766845703125),\n (10.800000190734863,\n 252.5821990966797,\n 1.0,\n 24.974599838256836,\n 121.53045654296875),\n (17.700000762939453,\n 451.64190673828125,\n 8.0,\n 24.969449996948242,\n 121.5448989868164),\n (13.0, 492.2312927246094, 5.0, 24.965150833129883, 121.53736877441406),\n (13.199999809265137,\n 170.12890625,\n 1.0,\n 24.973709106445312,\n 121.52983856201172),\n (27.5, 394.0173034667969, 7.0, 24.97304916381836, 121.5399398803711),\n (1.5, 23.38283920288086, 7.0, 24.96772003173828, 121.54102325439453),\n (19.100000381469727,\n 461.1015930175781,\n 5.0,\n 24.95425033569336,\n 121.53990173339844),\n (21.200000762939453,\n 2185.1279296875,\n 3.0,\n 24.963220596313477,\n 121.51236724853516),\n (0.0, 208.3905029296875, 6.0, 24.956180572509766, 121.53843688964844),\n (2.5999999046325684, 1554.25, 3.0, 24.970260620117188, 121.51641845703125),\n (2.299999952316284,\n 184.3302001953125,\n 6.0,\n 24.965810775756836,\n 121.54086303710938),\n (4.699999809265137,\n 387.7720947265625,\n 9.0,\n 24.98118019104004,\n 121.53787994384766),\n (2.0, 1455.7979736328125, 1.0, 24.951200485229492, 121.54900360107422),\n (33.5, 1978.6710205078125, 2.0, 24.986740112304688, 121.51844024658203),\n (15.0, 383.2804870605469, 7.0, 24.967350006103516, 121.54463958740234),\n (30.100000381469727,\n 718.293701171875,\n 3.0,\n 24.97509002685547,\n 121.53643798828125),\n (5.900000095367432,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (19.200000762939453,\n 461.1015930175781,\n 5.0,\n 24.95425033569336,\n 121.53990173339844),\n (16.600000381469727,\n 323.6911926269531,\n 6.0,\n 24.978410720825195,\n 121.54280090332031),\n (13.899999618530273,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (37.70000076293945,\n 490.3446044921875,\n 0.0,\n 24.972169876098633,\n 121.53471374511719),\n (3.4000000953674316,\n 56.47425079345703,\n 7.0,\n 24.957439422607422,\n 121.537109375),\n (17.5, 395.6747131347656, 5.0, 24.95673942565918, 121.53399658203125),\n (12.600000381469727,\n 383.2804870605469,\n 7.0,\n 24.967350006103516,\n 121.54463958740234),\n (26.399999618530273,\n 335.5273132324219,\n 6.0,\n 24.97960090637207,\n 121.54139709472656),\n (18.200000762939453,\n 2179.590087890625,\n 3.0,\n 24.962989807128906,\n 121.51251983642578),\n (12.5, 1144.43603515625, 4.0, 24.99176025390625, 121.53456115722656),\n (34.900001525878906,\n 567.034912109375,\n 4.0,\n 24.970029830932617,\n 121.5457992553711),\n (16.700000762939453,\n 4082.014892578125,\n 0.0,\n 24.94154930114746,\n 121.5038070678711),\n (33.20000076293945,\n 121.7261962890625,\n 10.0,\n 24.981779098510742,\n 121.54058837890625),\n (2.5, 156.24420166015625, 4.0, 24.966960906982422, 121.5399169921875),\n (38.0, 461.7847900390625, 0.0, 24.9722900390625, 121.5344467163086),\n (16.5, 2288.010986328125, 3.0, 24.958850860595703, 121.51358795166016),\n (38.29999923706055,\n 439.71051025390625,\n 0.0,\n 24.971609115600586,\n 121.53423309326172),\n (20.0, 1626.0830078125, 3.0, 24.96622085571289, 121.51667785644531),\n (16.200000762939453,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (14.399999618530273,\n 169.9803009033203,\n 1.0,\n 24.973690032958984,\n 121.52979278564453),\n (10.300000190734863,\n 3079.889892578125,\n 0.0,\n 24.954599380493164,\n 121.56626892089844),\n (16.399999618530273,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (30.299999237060547,\n 1264.72998046875,\n 0.0,\n 24.948829650878906,\n 121.529541015625),\n (16.399999618530273,\n 1643.4990234375,\n 2.0,\n 24.95393943786621,\n 121.55174255371094),\n (21.299999237060547,\n 537.797119140625,\n 4.0,\n 24.97425079345703,\n 121.53813934326172),\n (35.400001525878906,\n 318.5292053222656,\n 9.0,\n 24.97071075439453,\n 121.54068756103516),\n (8.300000190734863,\n 104.81009674072266,\n 5.0,\n 24.966739654541016,\n 121.5406723022461),\n (3.700000047683716,\n 577.9614868164062,\n 6.0,\n 24.972009658813477,\n 121.5472183227539),\n (15.600000381469727,\n 1756.4110107421875,\n 2.0,\n 24.983200073242188,\n 121.51811981201172),\n (13.300000190734863,\n 250.63099670410156,\n 7.0,\n 24.966060638427734,\n 121.54296875),\n (15.600000381469727,\n 752.7669067382812,\n 2.0,\n 24.977949142456055,\n 121.53450775146484),\n (7.099999904632568,\n 379.5574951171875,\n 10.0,\n 24.983430862426758,\n 121.5376205444336),\n (34.599998474121094,\n 272.6783142089844,\n 5.0,\n 24.95561981201172,\n 121.5387191772461),\n (13.5, 4197.34912109375, 0.0, 24.93885040283203, 121.50382995605469),\n (16.899999618530273,\n 964.7495727539062,\n 4.0,\n 24.988719940185547,\n 121.53411102294922),\n (12.899999618530273,\n 187.4822998046875,\n 1.0,\n 24.973880767822266,\n 121.5298080444336),\n (28.600000381469727,\n 197.13380432128906,\n 6.0,\n 24.97631072998047,\n 121.54435729980469),\n (12.399999618530273,\n 1712.6319580078125,\n 2.0,\n 24.964120864868164,\n 121.5167007446289),\n (36.599998474121094,\n 488.8193054199219,\n 8.0,\n 24.970149993896484,\n 121.54493713378906),\n (4.099999904632568,\n 56.47425079345703,\n 7.0,\n 24.957439422607422,\n 121.537109375),\n (3.5, 757.3377075195312, 3.0, 24.975379943847656, 121.54971313476562),\n (15.899999618530273,\n 1497.7130126953125,\n 3.0,\n 24.970029830932617,\n 121.51696014404297),\n (13.600000381469727,\n 4197.34912109375,\n 0.0,\n 24.93885040283203,\n 121.50382995605469),\n (32.0, 1156.7769775390625, 0.0, 24.949350357055664, 121.53045654296875),\n (25.600000381469727,\n 4519.68994140625,\n 0.0,\n 24.948259353637695,\n 121.4958724975586),\n (39.79999923706055,\n 617.71337890625,\n 2.0,\n 24.975770950317383,\n 121.53475189208984),\n (7.800000190734863,\n 104.81009674072266,\n 5.0,\n 24.966739654541016,\n 121.5406723022461),\n (30.0, 1013.3410034179688, 5.0, 24.990060806274414, 121.53459930419922),\n (27.299999237060547,\n 337.6015930175781,\n 6.0,\n 24.964309692382812,\n 121.5406265258789),\n (5.099999904632568,\n 1867.2330322265625,\n 2.0,\n 24.98406982421875,\n 121.5174789428711),\n (31.299999237060547,\n 600.8604125976562,\n 5.0,\n 24.96870994567871,\n 121.5465087890625),\n (31.5, 258.1860046386719, 9.0, 24.968669891357422, 121.5433120727539),\n (1.7000000476837158,\n 329.9747009277344,\n 5.0,\n 24.982540130615234,\n 121.54395294189453),\n (33.599998474121094,\n 270.8894958496094,\n 0.0,\n 24.972810745239258,\n 121.53265380859375),\n (13.0, 750.0703735351562, 2.0, 24.973709106445312, 121.54950714111328),\n (5.699999809265137,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (33.5, 563.285400390625, 8.0, 24.982229232788086, 121.53597259521484),\n (34.599998474121094,\n 3085.169921875,\n 0.0,\n 24.99799919128418,\n 121.5155029296875),\n (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734),\n (13.199999809265137,\n 1712.6319580078125,\n 2.0,\n 24.964120864868164,\n 121.5167007446289),\n (17.399999618530273,\n 6488.02099609375,\n 1.0,\n 24.957189559936523,\n 121.4735336303711),\n (4.599999904632568,\n 259.66070556640625,\n 6.0,\n 24.975849151611328,\n 121.54515838623047),\n (7.800000190734863,\n 104.81009674072266,\n 5.0,\n 24.966739654541016,\n 121.5406723022461),\n (13.199999809265137,\n 492.2312927246094,\n 5.0,\n 24.965150833129883,\n 121.53736877441406),\n (4.0, 2180.2451171875, 3.0, 24.963239669799805, 121.51241302490234),\n (18.399999618530273,\n 2674.9609375,\n 3.0,\n 24.961429595947266,\n 121.50827026367188),\n (4.099999904632568,\n 2147.3759765625,\n 3.0,\n 24.962989807128906,\n 121.5128402709961),\n (12.199999809265137,\n 1360.1390380859375,\n 1.0,\n 24.95203971862793,\n 121.54842376708984),\n (3.799999952316284,\n 383.8623962402344,\n 5.0,\n 24.980850219726562,\n 121.54390716552734),\n (10.300000190734863,\n 211.44729614257812,\n 1.0,\n 24.974170684814453,\n 121.52999114990234),\n (0.0, 338.9678955078125, 9.0, 24.968530654907227, 121.54412841796875),\n (1.100000023841858,\n 193.58450317382812,\n 6.0,\n 24.965709686279297,\n 121.5408935546875),\n (5.599999904632568,\n 2408.992919921875,\n 0.0,\n 24.955049514770508,\n 121.55963897705078),\n (32.900001525878906,\n 87.3022232055664,\n 10.0,\n 24.982999801635742,\n 121.54022216796875),\n (41.400001525878906,\n 281.2049865722656,\n 8.0,\n 24.97344970703125,\n 121.54093170166016),\n (17.100000381469727,\n 967.4000244140625,\n 4.0,\n 24.988719940185547,\n 121.5340805053711),\n (32.29999923706055,\n 109.94550323486328,\n 10.0,\n 24.98181915283203,\n 121.54086303710938),\n (35.29999923706055,\n 614.139404296875,\n 7.0,\n 24.979129791259766,\n 121.53665924072266),\n (17.299999237060547,\n 2261.431884765625,\n 4.0,\n 24.961820602416992,\n 121.51222229003906),\n (14.199999809265137,\n 1801.5439453125,\n 1.0,\n 24.95153045654297,\n 121.55254364013672),\n (15.0, 1828.3189697265625, 2.0, 24.96463966369629, 121.51531219482422),\n (18.200000762939453,\n 350.85150146484375,\n 1.0,\n 24.975439071655273,\n 121.53118896484375),\n (20.200000762939453,\n 2185.1279296875,\n 3.0,\n 24.963220596313477,\n 121.51236724853516),\n (15.899999618530273,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (4.099999904632568,\n 312.89630126953125,\n 5.0,\n 24.955909729003906,\n 121.53955841064453),\n (33.900001525878906,\n 157.60519409179688,\n 7.0,\n 24.966279983520508,\n 121.54196166992188),\n (0.0, 274.014404296875, 1.0, 24.97480010986328, 121.53058624267578),\n (5.400000095367432,\n 390.5683898925781,\n 5.0,\n 24.9793701171875,\n 121.54244995117188),\n (21.700000762939453,\n 1157.988037109375,\n 0.0,\n 24.961650848388672,\n 121.55010986328125),\n (14.699999809265137,\n 1717.1929931640625,\n 2.0,\n 24.96446990966797,\n 121.51648712158203),\n (3.9000000953674316,\n 49.661048889160156,\n 8.0,\n 24.95836067199707,\n 121.53755950927734),\n (37.29999923706055,\n 587.8876953125,\n 8.0,\n 24.97076988220215,\n 121.54634094238281),\n (0.0, 292.997802734375, 6.0, 24.977439880371094, 121.5445785522461),\n (14.100000381469727,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (8.0, 132.54690551757812, 9.0, 24.982980728149414, 121.53981018066406),\n (16.299999237060547,\n 3529.56396484375,\n 0.0,\n 24.932069778442383,\n 121.5159683227539),\n (29.100000381469727,\n 506.1144104003906,\n 4.0,\n 24.978450775146484,\n 121.53888702392578),\n (16.100000381469727,\n 4066.5869140625,\n 0.0,\n 24.942970275878906,\n 121.50341796875),\n (18.299999237060547,\n 82.88642883300781,\n 10.0,\n 24.982999801635742,\n 121.5402603149414),\n (0.0, 185.42959594726562, 0.0, 24.971099853515625, 121.53170013427734),\n (16.200000762939453,\n 2103.554931640625,\n 3.0,\n 24.960420608520508,\n 121.51461791992188),\n (10.399999618530273,\n 2251.93798828125,\n 4.0,\n 24.959569931030273,\n 121.5135269165039),\n (40.900001525878906,\n 122.36190032958984,\n 8.0,\n 24.967559814453125,\n 121.54229736328125),\n (32.79999923706055,\n 377.8302001953125,\n 9.0,\n 24.97150993347168,\n 121.54350280761719),\n (6.199999809265137,\n 1939.7490234375,\n 1.0,\n 24.951549530029297,\n 121.55387115478516),\n (42.70000076293945,\n 443.802001953125,\n 6.0,\n 24.979270935058594,\n 121.53874206542969),\n (16.899999618530273,\n 967.4000244140625,\n 4.0,\n 24.988719940185547,\n 121.5340805053711),\n (32.599998474121094,\n 4136.27099609375,\n 1.0,\n 24.955440521240234,\n 121.49629974365234),\n (21.200000762939453,\n 512.5487060546875,\n 4.0,\n 24.974000930786133,\n 121.53842163085938),\n (37.099998474121094,\n 918.6356811523438,\n 1.0,\n 24.97197914123535,\n 121.55062866210938),\n (13.100000381469727,\n 1164.8380126953125,\n 4.0,\n 24.991559982299805,\n 121.5340576171875),\n (14.699999809265137,\n 1717.1929931640625,\n 2.0,\n 24.96446990966797,\n 121.51648712158203),\n (12.699999809265137,\n 170.12890625,\n 1.0,\n 24.973709106445312,\n 121.52983856201172),\n (26.799999237060547,\n 482.7580871582031,\n 5.0,\n 24.97433090209961,\n 121.53862762451172),\n (7.599999904632568,\n 2175.030029296875,\n 3.0,\n 24.963050842285156,\n 121.51254272460938),\n (12.699999809265137,\n 187.4822998046875,\n 1.0,\n 24.973880767822266,\n 121.5298080444336),\n (30.899999618530273,\n 161.94200134277344,\n 9.0,\n 24.983530044555664,\n 121.53965759277344),\n (16.399999618530273,\n 289.3247985839844,\n 5.0,\n 24.982030868530273,\n 121.5434799194336),\n (23.0, 130.9945068359375, 6.0, 24.95663070678711, 121.53765106201172),\n (1.899999976158142,\n 372.13861083984375,\n 7.0,\n 24.972930908203125,\n 121.5402603149414),\n (5.199999809265137,\n 2408.992919921875,\n 0.0,\n 24.955049514770508,\n 121.55963897705078),\n (18.5, 2175.743896484375, 3.0, 24.963300704956055, 121.5124282836914),\n (13.699999809265137,\n 4082.014892578125,\n 0.0,\n 24.94154930114746,\n 121.5038070678711),\n (5.599999904632568,\n 90.45606231689453,\n 9.0,\n 24.97433090209961,\n 121.54309844970703),\n (18.799999237060547,\n 390.9696044921875,\n 7.0,\n 24.979230880737305,\n 121.53986358642578),\n (8.100000381469727,\n 104.81009674072266,\n 5.0,\n 24.966739654541016,\n 121.5406723022461),\n (6.5, 90.45606231689453, 9.0, 24.97433090209961, 121.54309844970703)]" }, { "code": null, "e": 51223, "s": 51080, "text": "from pyspark.mllib.feature import StandardScaler\nscaler1 = StandardScaler().fit(features_rdd)\nscaled_features=scaler1.transform(features_rdd)\n" }, { "code": null, "e": 51279, "s": 51223, "text": "for data in scaled_features.collect():\n print(data)\n" }, { "code": null, "e": 89664, "s": 51279, "text": "[2.808869299771829,0.06725154690948568,3.3949381000162235,2013.0949590447945,7919.393034999268]\n[1.7116547295484583,0.24292240417652702,3.0554442900146013,2012.8820961989197,7919.345808528075]\n[1.1674363194598323,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973]\n[1.1674363194598323,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973]\n[0.4388858280893483,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594]\n[0.6232178675157918,1.723328976948524,1.0184814300048672,2011.4890356682267,7917.58848667894]\n[3.0283122138165033,0.49399282615128015,2.3764566700113567,2012.8007933502065,7919.144474624567]\n[1.7818763950740915,0.227874433981389,2.0369628600097345,2012.8885512455092,7919.526263360108]\n[2.782536217055131,4.367321291012587,0.3394938100016224,2010.5140162500102,7915.7665391323835]\n[1.5712112310755355,1.4128567496928301,1.0184814300048672,2011.8322289785795,7917.739611386758]\n[3.0546452965332014,0.3210603995816714,0.3394938100016224,2012.3301897154997,7918.968493879279]\n[0.5529961601347445,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[1.1411031530323057,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[1.7906541451202098,1.9567595700325358,1.3579752400064895,2011.3302722604371,7917.452772714353]\n[1.158658569413714,0.9229293727856711,1.3579752400064895,2013.7862637962348,7918.990367192253]\n[3.1336448795266096,0.458920776273077,0.6789876200032448,2013.0482368028117,7919.780789183801]\n[0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678]\n[1.5536558984049558,0.27798814312265985,0.3394938100016224,2012.4872625158491,7918.803449790478]\n[1.4834340654576659,0.2916833009520058,2.715950480012979,2011.8475981371264,7919.671422618933]\n[0.1316657484268045,0.018526789892036186,2.3764566700113567,2011.8652726694554,7919.4442384364565]\n[0.39499724528041347,1.8032324374654856,1.0184814300048672,2011.4962591727437,7917.521375377771]\n[0.9216602389876315,0.22119521912804102,2.3764566700113567,2012.4745061142553,7919.730082867362]\n[1.2903243178405184,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[0.8865494062248149,0.22119521912804102,2.3764566700113567,2012.4745061142553,7919.730082867362]\n[3.4759756245303133,0.380868425777485,1.3579752400064895,2012.3334172387945,7919.302559022877]\n[2.5718708856349184,1.1788738896031223,0.6789876200032448,2012.4857255999946,7917.89570730207]\n[0.27210920504431313,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973]\n[0.9128824889415131,0.21903724305722802,1.6974690500081118,2010.9153049796703,7919.320952490605]\n[1.6853216468317602,0.44170334459435423,1.3579752400064895,2012.386594527367,7919.245390136696]\n[0.6232178675157918,0.35753139691528435,1.6974690500081118,2012.502631674396,7919.830004137993]\n[2.273428556018493,3.581059818914822,0.0,2010.2971574229132,7916.502277841498]\n[2.5982041357732735,0.6096169359405251,2.3764566700113567,2013.0811268021023,7918.991858554501]\n[3.3267547108545856,0.38710797902993216,0.3394938100016224,2012.3301897154997,7919.0196973164675]\n[1.4483232326948494,0.2564396952767179,2.0369628600097345,2012.7267140060103,7919.560564691817]\n[1.3517683170308614,0.16271725209082338,2.3764566700113567,2013.192399509982,7919.535708654346]\n[1.220102568604057,3.232221670476899,0.0,2015.64193599919,7917.9543675505]\n[1.2903243178405184,1.533154527826953,0.6789876200032448,2011.5542009004657,7917.72121791903]\n[1.053325987414436,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[0.27210920504431313,0.45793288569581236,2.0369628600097345,2012.2109250451756,7919.8479004849705]\n[1.4219901499781513,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[1.1937694858873589,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[1.4746563154115475,3.2220553150473474,0.0,2009.870970656407,7916.993930262656]\n[3.1687555448677696,0.4115820637565314,1.6974690500081118,2011.4890356682267,7919.220036978476]\n[3.019534631192042,0.4062936477604794,2.0369628600097345,2013.4575174949164,7919.573489831301]\n[0.23699835135378952,0.4226861124645811,1.3579752400064895,2012.4074965829907,7919.876236367687]\n[3.2126441276767044,0.3873033761259493,2.715950480012979,2012.0610757493432,7919.6992613809]\n[1.9047645608764343,0.3676085771820948,3.0554442900146013,2012.0732173845952,7919.675896705678]\n[3.1512003796188464,0.5076730892137474,1.0184814300048672,2012.502631674396,7919.19170109576]\n[2.1242074749211084,3.649246514177134,0.0,2010.182810883324,7916.4963123925045]\n[2.5806486356810368,3.573666598264136,0.3394938100016224,2010.3769233557716,7916.472947717283]\n[1.9047645608764343,0.4061047550350635,1.3579752400064895,2012.3713790604054,7919.274720260911]\n[2.7474252168706577,1.3932276714898462,0.3394938100016224,2010.76130601103,7920.2127871150315]\n[2.8176468823962906,1.1398209714784304,1.0184814300048672,2012.386594527367,7917.911615166051]\n[1.1674363194598323,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[1.413212399932033,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[2.782536217055131,0.9195968137754665,0.0,2010.4116576540875,7918.731864402564]\n[2.949312630823095,0.29414998073830584,2.715950480012979,2012.253651305936,7919.415902553741]\n[0.30722007966254383,0.04474591685305818,2.3764566700113567,2011.0368750237765,7919.189215492013]\n[2.659648051252788,3.573666598264136,0.3394938100016224,2010.3769233557716,7916.472947717283]\n[1.1674363194598323,0.26626308419099826,1.6974690500081118,2011.0626952101352,7919.011246263728]\n[0.9655488217965663,1.5301421095853742,0.6789876200032448,2011.537294826064,7917.7296689717705]\n[0.4652189945168749,0.205735466660267,2.0369628600097345,2012.520306206725,7919.7136778826325]\n[1.509767315596021,1.724000015212188,1.0184814300048672,2011.4873450607865,7917.58848667894]\n[0.22822062223537828,0.4226861124645811,1.3579752400064895,2012.4074965829907,7919.876236367687]\n[1.536100398312719,0.7889611002348912,0.0,2011.4890356682267,7919.973672034569]\n[3.519864207339248,0.09804449468619773,2.715950480012979,2012.5607270937035,7919.591883299029]\n[0.08777716561786966,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717]\n[0.7461059077518921,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[2.6684258012989064,0.36781512117345455,2.0369628600097345,2012.8256913870525,7919.2503613441895]\n[1.0972145702233709,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973]\n[0.579329284706857,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[3.116089379434373,0.5076730892137474,1.0184814300048672,2012.502631674396,7919.19170109576]\n[2.852757882580764,0.33637664483934004,2.715950480012979,2012.5219968141653,7919.320952490605]\n[1.211324902268767,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[0.5968847429436794,0.30073259722528967,3.3949381000162235,2013.1312302589652,7919.222522582223]\n[1.0796591538419624,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[3.1512003796188464,0.4883889602709763,1.0184814300048672,2012.631578914605,7919.22550530672]\n[1.7994318951663282,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704]\n[3.3530877935712837,0.43770927416813227,0.6789876200032448,2012.5309109261225,7918.974459328272]\n[1.5799889811216539,1.1210096546647916,0.3394938100016224,2010.5840996129841,7919.955278566841]\n[1.0357705710330276,0.4226861124645811,1.3579752400064895,2012.4074965829907,7919.876236367687]\n[2.703536634061723,0.299336599707476,2.0369628600097345,2011.5872445913417,7919.354259580815]\n[1.158658569413714,0.11958921279546592,2.3764566700113567,2011.82746453943,7919.54167410334]\n[2.22076222316344,2.14513233267738,1.0184814300048672,2011.288314457604,7917.312584663022]\n[1.3254352343141633,0.30368241392230844,2.3764566700113567,2011.8354565018744,7919.679873671673]\n[0.0,0.2685724742718668,3.0554442900146013,2011.9305915932798,7919.646566581463]\n[0.15799889392662397,1.153463997623701,0.3394938100016224,2010.5341498477067,7919.964226740331]\n[1.4834340654576659,3.2220553150473474,0.0,2009.870970656407,7916.993930262656]\n[0.7812167405147086,1.1143485988535313,0.0,2013.3164286194556,7918.568311676011]\n[2.018874809211002,3.128052506890741,0.0,2010.2625768161824,7916.929801685983]\n[0.0,0.21710824984735824,0.3394938100016224,2012.435775834717,7918.764177251275]\n[0.7987722406069453,1.1108512302150066,0.0,2013.3132010961608,7918.569803038259]\n[1.8082096452124463,1.9567595700325358,1.3579752400064895,2011.3302722604371,7917.452772714353]\n[2.800091549725711,0.9082642174431681,0.0,2010.3729273745494,7918.775611028511]\n[3.5900862077081945,0.13279267405910117,1.6974690500081118,2011.7507724382808,7919.394526361516]\n[0.7022173249429573,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[0.5617738683254487,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[2.492871470063167,0.48921455592082264,1.0184814300048672,2012.6501755964466,7918.920770287336]\n[1.439545482648731,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[0.5617738683254487,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[1.536100398312719,0.7643944551712603,1.3579752400064895,2013.5574170254713,7918.993847037498]\n[1.114769986604779,0.13479725337491694,0.3394938100016224,2012.3478642478287,7918.715459417834]\n[0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717]\n[0.0,0.16511284321702066,2.0369628600097345,2010.9354385773668,7919.27571450241]\n[2.8703133826730007,0.31094438652978446,2.0369628600097345,2011.5638834703502,7919.5406798618405]\n[0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678]\n[1.509767315596021,0.15015977880110146,2.715950480012979,2012.6186688214254,7919.578461038795]\n[1.0708814037958443,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[2.756202966916776,0.46945258544711593,0.6789876200032448,2012.258569436671,7919.091282704381]\n[0.35110866247147865,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167]\n[0.7109950749890757,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[2.922979548106397,0.15578457231246617,2.3764566700113567,2012.613904382276,7919.523280635612]\n[0.8689939061325783,1.665803839754847,1.0184814300048672,2011.2786318877195,7917.723703522777]\n[1.2991020678866367,0.31158989090737055,2.0369628600097345,2011.3817589415692,7919.254835430935]\n[2.685981301391143,0.11396657128775735,2.715950480012979,2012.9796903556926,7919.470088715425]\n[1.8082096452124463,0.5846687817343428,0.6789876200032448,2012.9289721324876,7919.859334262207]\n[2.712314384107841,5.067930116016753,0.3394938100016224,2009.933830514864,7915.391710087334]\n[1.1937694858873589,3.3256613790700786,0.0,2009.5389968317936,7917.020774783124]\n[2.22076222316344,1.2548213387248148,1.0184814300048672,2011.7444710832765,7917.884770645584]\n[1.4571009827409678,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[1.1674363194598323,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[1.1937694858873589,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[2.7649807169628944,0.3287730356064927,1.3579752400064895,2013.015193111936,7919.679873671673]\n[0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688]\n[0.8689939061325783,0.22119521912804102,2.3764566700113567,2012.4745061142553,7919.730082867362]\n[0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717]\n[3.3881984589124436,0.6375751387662827,1.3579752400064895,2012.7242549406428,7919.036599421947]\n[0.3335532251623633,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973]\n[3.6251968730493545,0.09903355798455589,2.0369628600097345,2011.7862751945243,7919.402977414256]\n[3.379420876287982,0.17180195970516865,2.3764566700113567,2012.9240540017527,7919.48301385491]\n[2.5982041357732735,0.4243109961240726,2.715950480012979,2012.9289721324876,7919.151434315059]\n[0.35110866247147865,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167]\n[2.3348726389196646,0.3825009260791303,1.6974690500081118,2012.3979677046916,7919.288142521144]\n[1.5799889811216539,0.2958488788156798,2.715950480012979,2013.386665674015,7919.430816176223]\n[2.9317574655741723,0.14813974858263068,2.0369628600097345,2011.729870382657,7919.514829582871]\n[1.6589883966934051,0.7996413251217569,0.0,2011.5308397794745,7919.997036709791]\n[1.0006596545593829,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594]\n[1.1937694858873589,0.2528075241619782,2.0369628600097345,2011.642112487354,7919.5580790880695]\n[0.8777716561786966,0.7467389335797002,0.0,2012.7282509218649,7918.339139010536]\n[1.1323254029861873,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[1.4219901499781513,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[0.44766353628005245,1.2358887359523067,1.0184814300048672,2012.22060761506,7917.831578725398]\n[1.7379878122651566,0.5075685356878004,1.6974690500081118,2012.0626126651978,7919.799182651529]\n[1.1937694858873589,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[1.0445482373683177,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[0.18433203942644344,0.35753139691528435,1.6974690500081118,2012.502631674396,7919.830004137993]\n[0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688]\n[0.28088693416272437,0.3881454624105542,2.715950480012979,2012.0626126651978,7919.6992613809]\n[1.439545482648731,2.9954531021038173,0.0,2009.061938150497,7917.55517958873]\n[3.0634232140009767,0.14218558970269804,2.715950480012979,2012.3301897154997,7919.537200016594]\n[3.142422462151071,0.13527438160126984,2.3764566700113567,2011.822546408695,7919.552610759826]\n[0.43010811989864417,0.3072412234742074,3.0554442900146013,2012.9498741881116,7919.239424687703]\n[1.053325987414436,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[0.5705515765161528,0.2980493146440235,2.0369628600097345,2010.7742161042095,7919.190706854261]\n[1.4834340654576659,3.2220553150473474,0.0,2009.870970656407,7916.993930262656]\n[1.211324902268767,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[2.6947590514372615,1.0020761984890492,0.0,2010.3431112069684,7918.696071708607]\n[1.413212399932033,0.6464822093597283,1.3579752400064895,2012.762985220181,7919.028148369207]\n[1.0182151546516194,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594]\n[1.3605460670769798,0.6464822093597283,1.3579752400064895,2012.762985220181,7919.028148369207]\n[0.30722007966254383,0.039347651951275965,2.715950480012979,2011.111108059558,7919.218545616228]\n[1.6853216468317602,0.4883889602709763,1.0184814300048672,2012.631578914605,7919.22550530672]\n[1.4044346498859146,3.2220553150473474,0.0,2009.870970656407,7916.993930262656]\n[0.7461059077518921,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688]\n[1.2025471522226487,0.9797595820571193,0.3394938100016224,2012.6082177936134,7920.283875382196]\n[0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678]\n[2.4753161373925874,0.2615346485620617,2.715950480012979,2012.3776804154097,7919.384583946528]\n[2.422649804537534,0.4081358596094278,1.6974690500081118,2011.4841175374918,7919.585917850036]\n[0.7373281577057738,1.5550377452304196,0.3394938100016224,2010.8144832996024,7920.342535630625]\n[2.106651974828872,3.587396091432715,0.0,2010.2287646673792,7916.528625241216]\n[0.31599778785324795,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973]\n[0.579329284706857,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[3.6251968730493545,0.31841981855609963,1.3579752400064895,2013.117398016273,7919.677388067926]\n[0.37744182889900524,0.34231457906249413,2.3764566700113567,2012.895006292099,7919.232962117961]\n[2.6508704686283266,0.37411529322551995,1.0184814300048672,2012.0530837868987,7919.220036978476]\n[1.220102568604057,3.6239157385568475,0.0,2010.330201113789,7916.45008016281]\n[2.896646465389699,0.1434713756175361,3.0554442900146013,2012.610676858981,7919.548136673081]\n[1.149880903078424,0.9067643917938982,1.3579752400064895,2013.8024014127093,7919.023177161714]\n[1.2288803186501753,0.3477125054468473,0.3394938100016224,2012.4462268625289,7918.549918208283]\n[2.3612057216363627,3.5252644090643797,0.0,2010.3552528422204,7916.524151154471]\n[1.0182151546516194,0.1599654318200806,2.715950480012979,2013.248804321849,7919.456169334442]\n[1.1849917358412405,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167]\n[1.4922118155037842,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[1.2376580686962937,2.072296342325083,0.0,2010.8363075047391,7920.793921271082]\n[2.756202966916776,1.146719763244157,1.0184814300048672,2012.2787030343675,7917.898690026567]\n[1.8345427279291446,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704]\n[0.7812167405147086,2.438913426137275,0.0,2010.8112557763075,7921.089210996227]\n[3.0546452965332014,0.1505726612553819,2.715950480012979,2012.6186688214254,7919.580946642542]\n[1.4307677326026127,3.2220553150473474,0.0,2009.870970656407,7916.993930262656]\n[3.098533879342136,0.4885261081893786,2.715950480012979,2012.810475920091,7919.144474624567]\n[1.158658569413714,0.5942989255562621,0.6789876200032448,2012.3478642478287,7919.997036709791]\n[3.8446397870940285,0.045629516859878705,2.3764566700113567,2011.8475981371264,7919.422365123482]\n[0.8514384897511701,0.333948024083993,1.6974690500081118,2013.0530012419613,7919.688324724412]\n[1.3342129006494532,2.9885637888261045,0.0,2009.1183429623643,7917.525849464516]\n[1.3342129006494532,0.36534196119636964,1.6974690500081118,2010.779902692872,7919.371161686295]\n[2.0013193091187658,0.5608916076749141,0.6789876200032448,2012.9354271790774,7919.841935035978]\n[3.019534631192042,0.1004101391098313,2.715950480012979,2011.9530305647584,7919.435787383717]\n[2.9844236310075685,0.12487441287594185,2.3764566700113567,2011.749235522426,7919.505384288633]\n[1.5975444812138906,0.35784682261971984,2.715950480012979,2012.004670937476,7919.696775777153]\n[1.5273226482666007,0.7889611002348912,0.0,2011.4890356682267,7919.973672034569]\n[1.149880903078424,0.4452739297168213,1.6974690500081118,2013.4558268874762,7919.63215007973]\n[3.3618653761957455,0.5092255785030526,1.0184814300048672,2012.4994041511013,7919.190706854261]\n[1.3693238171230981,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[1.5799889811216539,1.1210096546647916,0.3394938100016224,2010.5840996129841,7919.955278566841]\n[1.1235477366508975,1.1486498929053959,1.0184814300048672,2012.2819305576625,7917.897198664318]\n[1.9486531436853693,0.30073259722528967,3.3949381000162235,2013.1312302589652,7919.222522582223]\n[3.379420876287982,0.5269459987217269,1.0184814300048672,2012.4543725165588,7919.176787473279]\n[1.009437404605501,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[3.0546452965332014,0.1391554234759101,2.715950480012979,2012.328652799645,7919.554102122074]\n[0.45644124447075657,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594]\n[0.0,0.21710824984735824,0.3394938100016224,2012.435775834717,7918.764177251275]\n[1.5448781483588374,1.4306721482301723,0.6789876200032448,2013.396194552314,7918.1338281410335]\n[0.5442184100886263,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[1.5887667311677722,1.4128567496928301,1.0184814300048672,2011.8322289785795,7917.739611386758]\n[1.6853216468317602,0.30402501774033425,2.715950480012979,2012.2101565872483,7919.688324724412]\n[3.3179767933868103,0.4682075183430306,0.3394938100016224,2012.1723484572228,7919.090288462882]\n[2.4577606373003507,0.29523918474612504,2.0369628600097345,2012.7242549406428,7919.455175092943]\n[1.1937694858873589,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[2.5718708856349184,0.4197552285637734,2.715950480012979,2012.9369640949321,7919.152925677307]\n[3.265310627953414,0.1477764710216158,3.0554442900146013,2012.6154412981305,7919.550125156079]\n[0.7899944905608269,1.1108512302150066,0.0,2013.3132010961608,7918.569803038259]\n[2.685981301391143,0.34157999624143237,3.3949381000162235,2012.9538701693336,7919.210094563488]\n[0.7987722406069453,1.1108512302150066,0.0,2013.3132010961608,7918.569803038259]\n[3.0283122138165033,0.2574593339528652,2.0369628600097345,2012.7048898008736,7919.488482183153]\n[0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717]\n[1.4483232326948494,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[2.8439802999563026,0.21001418188469634,2.715950480012979,2012.9023834882016,7919.368676082548]\n[1.0445482373683177,2.5127208647917114,0.0,2014.559025087974,7917.928517271531]\n[2.7210921341539596,0.9162532287690011,0.0,2010.3487977956308,7918.7880390472465]\n[0.35110866247147865,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167]\n[1.4219901499781513,3.228512099769986,0.0,2009.8210208911296,7917.003872677644]\n[2.3787612217285994,3.496340706171308,0.3394938100016224,2010.4631443352198,7916.502277841498]\n[3.484753541998088,0.26413545378971887,3.0554442900146013,2012.8676491898855,7919.33338050934]\n[0.7022173249429573,1.7562754275300223,1.3579752400064895,2011.2488157201383,7917.658083583857]\n[1.1323254029861873,0.1985810096062423,2.3764566700113567,2011.7315609900973,7919.571004227554]\n[0.31599778785324795,0.29620161397676104,3.3949381000162235,2013.114170492978,7919.224511065221]\n[1.1411031530323057,0.5806570116825441,0.0,2012.5873157379897,7918.411718639949]\n[1.1235477366508975,0.5806570116825441,0.0,2012.5873157379897,7918.411718639949]\n[1.5887667311677722,0.6637484842675013,0.0,2011.512396789218,7919.877230609185]\n[0.9655488217965663,1.3569597846136696,0.6789876200032448,2011.575256647675,7917.859417487364]\n[1.2025471522226487,0.1985810096062423,2.3764566700113567,2011.7315609900973,7919.571004227554]\n[0.17555433123573932,1.645966331534827,1.0184814300048672,2011.5308397794745,7917.637204512382]\n[2.879090965297462,0.16176923403073884,2.715950480012979,2013.045009279517,7919.327415060347]\n[0.42133041170794006,1.2358887359523067,1.0184814300048672,2012.22060761506,7917.831578725398]\n[0.6583287421340225,0.5067862702688738,1.6974690500081118,2012.2568788292308,7919.908052095649]\n[1.439545482648731,0.30886533337957534,2.0369628600097345,2011.575256647675,7919.555593484322]\n[1.9047645608764343,0.8359551536490203,0.0,2011.4132657165903,7919.982123087309]\n[1.6677661467395235,0.7996413251217569,0.0,2011.5308397794745,7919.997036709791]\n[1.5799889811216539,4.996517639813289,0.3394938100016224,2011.036106565849,7915.152595006872]\n[3.4408649591891534,0.3365105526623499,2.3764566700113567,2012.3947401813969,7919.323438094352]\n[2.782536217055131,0.9186634728639134,0.0,2010.405202607498,7918.737829851557]\n[0.5178852855165138,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[2.6684258012989064,1.375153935794498,0.6789876200032448,2011.6170607589227,7917.828596000902]\n[0.09655488427242734,0.26144694836811866,1.6974690500081118,2013.059456288551,7919.6351328042265]\n[2.7649807169628944,4.367321291012587,0.3394938100016224,2010.5140162500102,7915.7665391323835]\n[1.2815466515052285,0.26877928424120656,0.3394938100016224,2012.4671289181529,7918.824328861952]\n[1.5185448982204823,0.3518976447819577,0.3394938100016224,2012.4526819091186,7918.549918208283]\n[0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678]\n[1.5536558984049558,0.6637484842675013,0.0,2011.512396789218,7919.877230609185]\n[1.4922118155037842,1.1766783622775,1.3579752400064895,2012.1077979913257,7917.87880519659]\n[1.4219901499781513,1.812846525889341,1.0184814300048672,2011.1506067970236,7917.656592221608]\n[1.3956568998397962,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[0.34233095428077454,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167]\n[2.8615354652052254,0.3911364089752038,2.3764566700113567,2012.0232676193177,7919.717654848628]\n[1.378101483458388,0.6464822093597283,1.3579752400064895,2012.762985220181,7919.028148369207]\n[1.5624334810294171,1.4128567496928301,1.0184814300048672,2011.8322289785795,7917.739611386758]\n[3.04586771390874,0.3825009260791303,1.6974690500081118,2012.3979677046916,7919.288142521144]\n[1.509767315596021,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594]\n[1.5448781483588374,0.6637484842675013,0.0,2011.512396789218,7919.877230609185]\n[0.9479934054151581,0.20012699452494626,0.3394938100016224,2012.4196382182429,7918.755726198535]\n[1.5536558984049558,0.35784682261971984,2.715950480012979,2012.004670937476,7919.696775777153]\n[1.1411031530323057,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[1.158658569413714,0.13479725337491694,0.3394938100016224,2012.3478642478287,7918.715459417834]\n[2.413872054491416,0.3121894536338698,2.3764566700113567,2012.2946869592563,7919.373647290042]\n[0.1316657484268045,0.018526789892036186,2.3764566700113567,2011.8652726694554,7919.4442384364565]\n[1.6765438967856419,0.36534196119636964,1.6974690500081118,2010.779902692872,7919.371161686295]\n[1.8608759780674995,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704]\n[0.0,0.16511284321702066,2.0369628600097345,2010.9354385773668,7919.27571450241]\n[0.22822062223537828,1.231469922871879,1.0184814300048672,2012.0699898613004,7917.841024019636]\n[0.2018874767355588,0.14604928255909894,2.0369628600097345,2011.7114273924008,7919.433798900719]\n[0.41255266166182175,0.3072412234742074,3.0554442900146013,2012.9498741881116,7919.239424687703]\n[0.17555433123573932,1.153463997623701,0.3394938100016224,2010.5341498477067,7919.964226740331]\n[2.9405350481986336,1.567748977972384,0.6789876200032448,2013.3978851597542,7917.972761018228]\n[1.316657484268045,0.30368241392230844,2.3764566700113567,2011.8354565018744,7919.679873671673]\n[2.6420927185822083,0.5691214983313402,1.0184814300048672,2012.4591369557083,7919.145468866066]\n[0.5178852855165138,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[1.6853216468317602,0.36534196119636964,1.6974690500081118,2010.779902692872,7919.371161686295]\n[1.4571009827409678,0.25646837253892263,2.0369628600097345,2012.7267140060103,7919.5600675710675]\n[1.220102568604057,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[3.309199210762349,0.3885119075275124,0.0,2012.223835138355,7919.033119576701]\n[0.2984423714718397,0.04474591685305818,2.3764566700113567,2011.0368750237765,7919.189215492013]\n[1.536100398312719,0.31350265946046174,1.6974690500081118,2010.9804702119093,7918.986390226258]\n[1.105992320269489,0.30368241392230844,2.3764566700113567,2011.8354565018744,7919.679873671673]\n[2.317317138827428,0.2658464175954572,2.0369628600097345,2012.822617555343,7919.468597353177]\n[1.5975444812138906,1.7269420218285219,1.0184814300048672,2011.4841175374918,7917.586995316692]\n[1.0972145702233709,0.9067643917938982,1.3579752400064895,2013.8024014127093,7919.023177161714]\n[3.0634232140009767,0.4492754958861153,1.3579752400064895,2012.0513931794585,7919.755436025582]\n[1.4658787327870861,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[2.9142019654819356,0.09644661383662796,3.3949381000162235,2012.9981333459489,7919.415902553741]\n[0.21944291404467414,0.12379606560566893,1.3579752400064895,2011.8041034184387,7919.372155927793]\n[3.335532293479047,0.36588327474525406,0.0,2012.2335177082396,7919.015720350472]\n[1.4483232326948494,1.812846525889341,1.0184814300048672,2011.1506067970236,7917.656592221608]\n[3.3618653761957455,0.3483932881765047,0.0,2012.1786498122271,7919.001800969489]\n[1.7555433123573931,1.2883849549391233,1.0184814300048672,2011.7444710832765,7917.857926125116]\n[1.4219901499781513,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[1.2639911514129918,0.1346795097591447,0.3394938100016224,2012.346327331974,7918.7124766933375]\n[0.9041048226062232,2.440271364624136,0.0,2010.8080282530127,7921.089210996227]\n[1.439545482648731,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[2.659648051252788,1.0020761984890492,0.0,2010.3431112069684,7918.696071708607]\n[1.439545482648731,1.3021840859788236,0.6789876200032448,2010.7548509644403,7920.142693089366]\n[1.869653560691961,0.4261096843035703,1.3579752400064895,2012.3915126581019,7919.256326793183]\n[3.1073117968099115,0.252378404961011,3.0554442900146013,2012.1062610754711,7919.422365123482]\n[0.7285504913704839,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[0.3247755169716592,0.45793288569581236,2.0369628600097345,2012.2109250451756,7919.8479004849705]\n[1.3693238171230981,1.3916469885346634,0.6789876200032448,2013.1126335771235,7917.951881946753]\n[1.1674363194598323,0.1985810096062423,2.3764566700113567,2011.7315609900973,7919.571004227554]\n[1.3693238171230981,0.5964354541299625,0.6789876200032448,2012.6895206423267,7919.0196973164675]\n[0.6232178675157918,0.30073259722528967,3.3949381000162235,2013.1312302589652,7919.222522582223]\n[3.0370897964409647,0.21604963330723628,1.6974690500081118,2010.8902532512388,7919.294107970137]\n[1.1849917358412405,3.3256613790700786,0.0,2009.5389968317936,7917.020774783124]\n[1.4834340654576659,0.7643944551712603,1.3579752400064895,2013.5574170254713,7918.993847037498]\n[1.1323254029861873,0.14854676743144346,0.3394938100016224,2012.361696490521,7918.713470934836]\n[2.510426970155404,0.15619388824383332,2.0369628600097345,2012.5574995704087,7919.661480203945]\n[1.0884368201772525,1.3569597846136696,0.6789876200032448,2011.575256647675,7917.859417487364]\n[3.2126441276767044,0.3873033761259493,2.715950480012979,2012.0610757493432,7919.6992613809]\n[0.35988637066218276,0.04474591685305818,2.3764566700113567,2011.0368750237765,7919.189215492013]\n[0.30722007966254383,0.6000570103053195,1.0184814300048672,2012.4824980766996,7920.010458970025]\n[1.3956568998397962,1.1866742983613356,1.0184814300048672,2012.0513931794585,7917.876319592844]\n[1.1937694858873589,3.3256613790700786,0.0,2009.5389968317936,7917.020774783124]\n[2.808869299771829,0.9165424193726843,0.0,2010.3850690098016,7918.755726198535]\n[2.247095473301795,3.581059818914822,0.0,2010.2971574229132,7916.502277841498]\n[3.49353112462255,0.4894292726901126,0.6789876200032448,2012.514004851721,7919.035605180448]\n[0.6846619085615491,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[2.63331496853609,0.8028946226939285,1.6974690500081118,2013.6654622100561,7919.025662765461]\n[2.396316554399179,0.267489919713547,2.0369628600097345,2011.5904721146364,7919.418388157487]\n[0.44766353628005245,1.4794539605468038,0.6789876200032448,2013.1827169400974,7917.910123803803]\n[2.7474252168706577,0.4760762592622816,1.6974690500081118,2011.9450386023138,7919.801668255276]\n[2.7649807169628944,0.20456702539423122,3.0554442900146013,2011.941811079019,7919.593374661277]\n[0.14922118573591986,0.26144694836811866,1.6974690500081118,2013.059456288551,7919.6351328042265]\n[2.949312630823095,0.21463230919139176,0.0,2012.2754755110727,7918.898896974363]\n[1.1411031530323057,0.5942989255562621,0.6789876200032448,2012.3478642478287,7919.997036709791]\n[0.5003298272796914,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[2.9405350481986336,0.44630466692867843,2.715950480012979,2013.0344045601196,7919.1151445003525]\n[3.0370897964409647,2.4444548597317337,0.0,2014.3051265887789,7917.781369529708]\n[0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688]\n[1.158658569413714,1.3569597846136696,0.6789876200032448,2011.575256647675,7917.859417487364]\n[1.5273226482666007,5.140616191507609,0.3394938100016224,2011.01674142608,7915.046708287249]\n[0.4037749534711176,0.205735466660267,2.0369628600097345,2012.520306206725,7919.7136778826325]\n[0.6846619085615491,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[1.158658569413714,0.3900067763144282,1.6974690500081118,2011.6582501038283,7919.206117597493]\n[0.35110866247147865,1.7274610174069047,1.0184814300048672,2011.5042511351883,7917.580035626201]\n[1.6150998138844703,2.11943634511077,1.0184814300048672,2011.358397820578,7917.310099059276]\n[0.35988637066218276,1.7014180011158744,1.0184814300048672,2011.4841175374918,7917.607874388167]\n[1.0708814037958443,1.0776711058881911,0.3394938100016224,2010.6017741453131,7919.926445563376]\n[0.3335532251623633,0.30414347466068914,1.6974690500081118,2012.9232855438254,7919.63215007973]\n[0.9041048226062232,0.1675348145228683,0.3394938100016224,2012.3850576115121,7918.725401832822]\n[0.0,0.2685724742718668,3.0554442900146013,2011.9305915932798,7919.646566581463]\n[0.09655488427242734,0.15338169097163593,2.0369628600097345,2011.7032817383708,7919.435787383717]\n[0.49155211908898727,1.908703442364545,0.0,2010.8442994671834,7920.6572130649965]\n[2.8878688827652375,0.0691716661267508,3.3949381000162235,2013.0964959606492,7919.392040757769]\n[3.6339747905171293,0.2228055223582665,2.715950480012979,2012.3269621922047,7919.438272987463]\n[1.5009895655499026,0.7664944722222548,1.3579752400064895,2013.5574170254713,7918.991858554501]\n[2.8352023824885273,0.08711248537155993,3.3949381000162235,2013.0013608692436,7919.433798900719]\n[3.098533879342136,0.48659752603638695,2.3764566700113567,2012.784655733732,7919.159885367799]\n[1.5185448982204823,1.791787259908208,1.3579752400064895,2011.389904595599,7917.567607607465]\n[1.2464357350315836,1.427406905828718,0.3394938100016224,2010.5607384919929,7920.194890768053]\n[1.316657484268045,1.4486214062308915,0.6789876200032448,2011.6170607589227,7917.768941510973]\n[1.5975444812138906,0.27798814312265985,0.3394938100016224,2012.4872625158491,7918.803449790478]\n[1.7730988124496299,1.7313297880247414,1.0184814300048672,2011.5027142193335,7917.577052901704]\n[1.3956568998397962,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[0.35988637066218276,0.2479153186368254,1.6974690500081118,2010.91361437223,7919.348791252572]\n[2.975646048383107,0.12487441287594185,2.3764566700113567,2011.749235522426,7919.505384288633]\n[0.0,0.21710824984735824,0.3394938100016224,2012.435775834717,7918.764177251275]\n[0.47399670270757904,0.3094567958675935,1.6974690500081118,2012.8040208735013,7919.537200016594]\n[1.9047645608764343,0.9175019712051733,0.0,2011.3762260444923,7920.036309248994]\n[1.2903243178405184,1.360573603247791,0.6789876200032448,2011.603382207816,7917.845498106381]\n[0.34233095428077454,0.039347651951275965,2.715950480012979,2011.111108059558,7919.218545616228]\n[3.2740882105778755,0.46579766112518006,2.715950480012979,2012.1110255146207,7919.7907315987895]\n[0.0,0.23214925625538416,2.0369628600097345,2012.6484849890064,7919.675896705678]\n[1.2376580686962937,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[0.7022173249429573,0.10502012386336701,3.0554442900146013,2013.0949590447945,7919.3651962373015]\n[1.4307677326026127,2.796559024325235,0.0,2008.9926232454504,7917.811693895422]\n[2.5543155529643387,0.4010067067332254,1.3579752400064895,2012.729941529305,7919.305044626624]\n[1.413212399932033,3.2220553150473474,0.0,2009.870970656407,7916.993930262656]\n[1.6063220638383522,0.06567292528364782,3.3949381000162235,2013.0964959606492,7919.394526361516]\n[0.0,0.14692036044352125,0.0,2012.137614158907,7918.836756880688]\n[1.4219901499781513,1.6666975257675671,1.0184814300048672,2011.2770949718647,7917.723703522777]\n[0.9128824889415131,1.784265015757417,1.3579752400064895,2011.2085485247455,7917.652615255613]\n[3.5900862077081945,0.09695029754629986,2.715950480012979,2011.852362576276,7919.527257601607]\n[2.879090965297462,0.2993640196192299,3.0554442900146013,2012.1706578497826,7919.605802680012]\n[0.5442184100886263,1.536910136904218,0.3394938100016224,2010.5622754078474,7920.281389778449]\n[3.7480850388516975,0.35163507615608836,2.0369628600097345,2012.796028911057,7919.295599332386]\n[1.4834340654576659,0.7664944722222548,1.3579752400064895,2013.5574170254713,7918.991858554501]\n[2.8615354652052254,3.2772677011656817,0.3394938100016224,2010.8758062422046,7916.530116603464]\n[1.8608759780674995,0.4061047550350635,1.3579752400064895,2012.3713790604054,7919.274720260911]\n[3.256532710485639,0.7278573018600822,0.3394938100016224,2012.2084659798081,7920.070113459953]\n[1.149880903078424,0.9229293727856711,1.3579752400064895,2013.7862637962348,7918.990367192253]\n[1.2903243178405184,1.360573603247791,0.6789876200032448,2011.603382207816,7917.845498106381]\n[1.114769986604779,0.13479725337491694,0.3394938100016224,2012.3478642478287,7918.715459417834]\n[2.3524279715902443,0.3825009260791303,1.6974690500081118,2012.3979677046916,7919.288142521144]\n[0.6671064503247266,1.723328976948524,1.0184814300048672,2011.4890356682267,7917.58848667894]\n[1.114769986604779,0.14854676743144346,0.3394938100016224,2012.361696490521,7918.713470934836]\n[2.712314384107841,0.12831057030934723,3.0554442900146013,2013.1392222214097,7919.355253822314]\n[1.439545482648731,0.22923904609756549,1.6974690500081118,2013.0184206352308,7919.604311317764]\n[2.018874809211002,0.10379012078487489,2.0369628600097345,2010.9717097915375,7919.224511065221]\n[0.16677661258118165,0.2948544355081812,2.3764566700113567,2012.2851580809572,7919.394526361516]\n[0.45644124447075657,1.908703442364545,0.0,2010.8442994671834,7920.6572130649965]\n[1.6238775639305887,1.7238945912128518,1.0184814300048672,2011.5091692659232,7917.581029867699]\n[1.2025471522226487,3.234279276129995,0.0,2009.7564704252325,7917.019283420876]\n[0.49155211908898727,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n[1.650210646647287,0.3097746879132979,2.3764566700113567,2012.792801387762,7919.368676082548]\n[0.7109950749890757,0.08304357841369915,1.6974690500081118,2011.7862751945243,7919.421370881984]\n[0.5705515765161528,0.07167052924862795,3.0554442900146013,2012.3979677046916,7919.579455280294]\n" }, { "code": null, "e": 89728, "s": 89664, "text": "df =scaled_features.map(lambda x: (x, )).toDF([\"Scaled_data\"])\n" }, { "code": null, "e": 89739, "s": 89728, "text": "df.show()\n" }, { "code": null, "e": 90318, "s": 89739, "text": "+--------------------+\n| Scaled_data|\n+--------------------+\n|[2.80886929977182...|\n|[1.71165472954845...|\n|[1.16743631945983...|\n|[1.16743631945983...|\n|[0.43888582808934...|\n|[0.62321786751579...|\n|[3.02831221381650...|\n|[1.78187639507409...|\n|[2.78253621705513...|\n|[1.57121123107553...|\n|[3.05464529653320...|\n|[0.55299616013474...|\n|[1.14110315303230...|\n|[1.79065414512020...|\n|[1.15865856941371...|\n|[3.13364487952660...|\n|[0.0,0.2321492562...|\n|[1.55365589840495...|\n|[1.48343406545766...|\n|[0.13166574842680...|\n+--------------------+\nonly showing top 20 rows\n\n" }, { "code": null, "e": 90337, "s": 90321, "text": "Spark Session :" }, { "code": null, "e": 91146, "s": 90337, "text": "This is the entry point to the programming spark with Dataframe API & dataset. That allows you to perform various tasks using spark. spark context, hive context, SQL context, now all of it is encapsulated in the session. Before spark 2.0, sparkContext was used to access all spark functionality. The spark driver program uses sparkContext to connect to the cluster through a resource manager. sparkConf creates the sparkContext object, which stores configuration parameter like appName (to identify your spark driver), application, number of core, and memory size of executor running on the worker node. After spark 2.0 onwards these two features are encapsulated in spark session. So each time you want to perform tasks using spark you need to create a session and after execution, you must end the session." }, { "code": null, "e": 91312, "s": 91146, "text": "Now read the data set using read.csv() you can allow the spark to read the dataset and to execute when it is required. Here I have used one real estate dataset used." }, { "code": null, "e": 91515, "s": 91312, "text": "Here you can notice the columns such as No and X1 transaction date are independent of the price of the house and the transaction date is not properly given in the datasets. so we will drop those columns" }, { "code": null, "e": 91632, "s": 91515, "text": "colm = ['No','X1 transaction date']df = dataset.select([column for column in dataset.columns if column not in colm])" }, { "code": null, "e": 91887, "s": 91632, "text": "there is a cool spark syntax is there to do that. if you apply a list comprehension in select() you will get the required data frame. This data frame is different from the Pandas data frame. Well, it is related to the objects created in spark and pandas." }, { "code": null, "e": 92028, "s": 91887, "text": "Spark data frame is distributed hence you will get the benefit of parallel processing and speed of processing while handling large datasets." }, { "code": null, "e": 92197, "s": 92028, "text": "Spark assures fault tolerance. So if your data processing got interrupted/failed in between processing then spark can regenerate the failed result set from the lineage." }, { "code": null, "e": 92541, "s": 92197, "text": "df.printSchema()#outputroot |-- X2 house age: string (nullable = true) |-- X3 distance to the nearest MRT station: string (nullable = true) |-- X4 number of convenience stores: string (nullable = true) |-- X5 latitude: string (nullable = true) |-- X6 longitude: string (nullable = true) |-- Y house price of unit area: string (nullable = true)" }, { "code": null, "e": 92635, "s": 92541, "text": "If you look at the schema of the dataset, it is in the string format. Lets typecast to float." }, { "code": null, "e": 92741, "s": 92635, "text": "from pyspark.sql.functions import coldf = df.select(*(col(c).cast('float').alias(c) for c in df.columns))" }, { "code": null, "e": 92770, "s": 92741, "text": "Let’s check for null values." }, { "code": null, "e": 92851, "s": 92770, "text": "df.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns]).show()" }, { "code": null, "e": 93127, "s": 92851, "text": "Great! there are no null values present. But the column names are a bit longer. So we will now replace those with our own custom names. For renaming the column name there are several techniques that are there, I have used reduce () to do that. You can perform in another way." }, { "code": null, "e": 93371, "s": 93127, "text": "from functools import reduceoldColumns = df.schema.namesnewColumns = ['Age','Distance_2_MRT','Stores','Latitude','Longitude','Price']df = reduce(lambda df, idx: df.withColumnRenamed(oldColumns[idx], newColumns[idx]),range(len(oldColumns)), df)" }, { "code": null, "e": 93421, "s": 93371, "text": "Try different techniques and let me know as well." }, { "code": null, "e": 93443, "s": 93421, "text": "Sharing is caring : )" }, { "code": null, "e": 93499, "s": 93443, "text": "Now we will do split to get Features and Label columns." }, { "code": null, "e": 93516, "s": 93499, "text": "VectorAssembler:" }, { "code": null, "e": 93772, "s": 93516, "text": "VectorAssembler is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models." }, { "code": null, "e": 94021, "s": 93772, "text": "from pyspark.ml.feature import VectorAssembler#let's assemble our features together using vectorAssemblerassembler = VectorAssembler( inputCols=features.columns, outputCol=\"features\")output = assembler.transform(df).select('features','Price')" }, { "code": null, "e": 94124, "s": 94021, "text": "This will transform the target and features columns. Now we will split it into train and test dataset." }, { "code": null, "e": 94170, "s": 94124, "text": "train,test = output.randomSplit([0.75, 0.25])" }, { "code": null, "e": 94212, "s": 94170, "text": "Let’s now apply a Linear Regression model" }, { "code": null, "e": 94623, "s": 94212, "text": "from pyspark.ml.regression import LinearRegressionlin_reg = LinearRegression(featuresCol = 'features', labelCol='Price')linear_model = lin_reg.fit(train)print(\"Coefficients: \" + str(linear_model.coefficients))print(\"\\nIntercept: \" + str(linear_model.intercept))#Output Coefficients: [-0.2845380180805475,-0.004727311005402087,1.187968326885585,201.55230488460887,-43.50846789357342]Intercept: 298.6774040798928" }, { "code": null, "e": 94678, "s": 94623, "text": "The coefficients for each column and Intercept we got." }, { "code": null, "e": 94835, "s": 94678, "text": "trainSummary = linear_model.summaryprint(\"RMSE: %f\" % trainSummary.rootMeanSquaredError)print(\"\\nr2: %f\" % trainSummary.r2)#OutputRMSE: 9.110080r2: 0.554706" }, { "code": null, "e": 94855, "s": 94835, "text": "For testing dataset" }, { "code": null, "e": 95138, "s": 94855, "text": "from pyspark.sql.functions import abspredictions = linear_model.transform(test)x =((predictions['Price']-predictions['prediction'])/predictions['Price'])*100predictions = predictions.withColumn('Accuracy',abs(x))predictions.select(\"prediction\",\"Price\",\"Accuracy\",\"features\").show()" }, { "code": null, "e": 95176, "s": 95138, "text": "r — square value for the test dataset" }, { "code": null, "e": 95471, "s": 95176, "text": "from pyspark.ml.evaluation import RegressionEvaluatorpred_evaluator = RegressionEvaluator(predictionCol=\"prediction\", \\ labelCol=\"Price\",metricName=\"r2\")print(\"R Squared (R2) on test data = %g\" % pred_evaluator.evaluate(predictions))#outputR Squared (R2) on test data = 0.610204" }, { "code": null, "e": 95510, "s": 95471, "text": "Let’s now check for adjusted R square." }, { "code": null, "e": 95531, "s": 95510, "text": "Adjusted R — square:" }, { "code": null, "e": 95955, "s": 95531, "text": "The adjusted R-squared is a modified version of R-squared that has been adjusted for the number of predictors in the model. The adjusted R-squared increases only if the new term improves the model more than would be expected by chance. It decreases when a predictor improves the model by less than expected. We use Adjusted R2 value which penalizes excessive use of such features that do not correlate with the output data." }, { "code": null, "e": 96045, "s": 95955, "text": "r2 = trainSummary.r2n = df.count()p = len(df.columns)adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)" }, { "code": null, "e": 96108, "s": 96045, "text": "We got adjusted r squared value 0.54 for training and testing." }, { "code": null, "e": 96171, "s": 96108, "text": "Let’s now explore more on the LinearRegression() in the spark." }, { "code": null, "e": 96322, "s": 96171, "text": "lin_reg = LinearRegression(featuresCol = 'features', labelCol='Price',maxIter=50, regParam=0.12, elasticNetParam=0.2)linear_model = lin_reg.fit(train)" }, { "code": null, "e": 96714, "s": 96322, "text": "Here you can apply Lasso, Ridge, Elastic net regularization, alpha values you can modify. There is a very good article on these concepts. This is a shared repository for Learning Apache Spark Notes. This shared repository mainly contains the self-learning and self-teaching notes from Wenqiang during his IMA Data Science Fellowship. Thanks to George Feng, A senior data scientist at ML Lab." }, { "code": null, "e": 96789, "s": 96714, "text": "I will be sharing other spark implemented ML algorithms in future stories." } ]
C++ Program to Find Inverse of a Graph Matrix
This is a C++ program to Find Inverse of a Graph Matrix. Inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Inverse of a matrix can find out in many ways. Here we find out inverse of a graph matrix using adjoint matrix and its determinant. Steps involved in the Example Begin function INV() to get the inverse of the matrix: Call function DET(). Call function ADJ(). Find the inverse of the matrix using the formula; Inverse(matrix) = ADJ(matrix) / DET(matrix) End. #include<bits/stdc++.h> using namespace std; #define N 5 void getCfactor(int M[N][N], int t[N][N], int p, int q, int n) { int i = 0, j = 0; for (int r= 0; r< n; r++) { for (int c = 0; c< n; c++) //Copy only those elements which are not in given row r and column c: { if (r != p && c != q) { t[i][j++] = M[r][c]; //If row is filled increase r index and reset c index if (j == n - 1) { j = 0; i++; } } } } } int DET(int M[N][N], int n) //to find determinant { int D = 0; if (n == 1) return M[0][0]; int t[N][N]; //store cofactors int s = 1; //store sign multiplier // To Iterate each element of first row for (int f = 0; f < n; f++) { //For Getting Cofactor of M[0][f] do getCfactor(M, t, 0, f, n); D += s * M[0][f] * DET(t, n - 1); s = -s; } return D; } void ADJ(int M[N][N],int adj[N][N]) //to find adjoint matrix { if (N == 1) { adj[0][0] = 1; return; } int s = 1, t[N][N]; for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { //To get cofactor of M[i][j] getCfactor(M, t, i, j, N); s = ((i+j)%2==0)? 1: -1; //sign of adj[j][i] positive if sum of row and column indexes is even. adj[j][i] = (s)*(DET(t, N-1)); //Interchange rows and columns to get the transpose of the cofactor matrix } } } bool INV(int M[N][N], float inv[N][N]) { int det = DET(M, N); if (det == 0) { cout << "can't find its inverse"; return false; } int adj[N][N]; ADJ(M, adj); for (int i=0; i<N; i++) for (int j=0; j<N; j++) inv[i][j] = adj[i][j]/float(det); return true; } template<class T> void print(T A[N][N]) //print the matrix. { for (int i=0; i<N; i++) { for (int j=0; j<N; j++) cout << A[i][j] << " "; cout << endl; } } int main() { int M[N][N] = { {1, 2, 3, 4,-2}, {-5, 6, 7, 8, 4}, {9, 10, -11, 12, 1}, {13, -14, -15, 0, 9}, {20 , -26 , 16 , -17 , 25} }; float inv[N][N]; cout << "Input matrix is :\n"; print(M); cout << "\nThe Inverse is :\n"; if (INV(M, inv)) print(inv); return 0; } Input matrix is : 1 2 3 4 -2 -5 6 7 8 4 9 10 -11 12 1 13 -14 -15 0 9 20 -26 16 -17 25 The Inverse is : 0.0811847 -0.0643008 0.0493814 -0.0247026 0.0237006 -0.126819 -0.0161738 0.0745377 -0.0713976 0.0151639 0.0933664 0.0028245 -0.0111876 -0.0220437 0.0154006 0.143624 0.0582573 -0.0282371 0.0579023 -0.0175466 -0.15893 0.0724272 0.0259728 -0.00100988 0.0150219
[ { "code": null, "e": 1503, "s": 1187, "text": "This is a C++ program to Find Inverse of a Graph Matrix. Inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Inverse of a matrix can find out in many ways. Here we find out inverse of a graph matrix using adjoint matrix and its determinant. Steps involved in the Example" }, { "code": null, "e": 1714, "s": 1503, "text": "Begin\n function INV() to get the inverse of the matrix:\n Call function DET().\n Call function ADJ().\n Find the inverse of the matrix using the formula;\n Inverse(matrix) = ADJ(matrix) / DET(matrix)\nEnd." }, { "code": null, "e": 3829, "s": 1714, "text": "#include<bits/stdc++.h>\nusing namespace std;\n#define N 5\nvoid getCfactor(int M[N][N], int t[N][N], int p, int q, int n) {\n int i = 0, j = 0;\n for (int r= 0; r< n; r++) {\n for (int c = 0; c< n; c++) //Copy only those elements which are not in given row r and column c: {\n if (r != p && c != q) { t[i][j++] = M[r][c]; //If row is filled increase r index and reset c index\n if (j == n - 1) {\n j = 0; i++;\n }\n }\n }\n }\n}\nint DET(int M[N][N], int n) //to find determinant {\n int D = 0;\n if (n == 1)\n return M[0][0];\n int t[N][N]; //store cofactors\n int s = 1; //store sign multiplier //\n To Iterate each element of first row\n for (int f = 0; f < n; f++) {\n //For Getting Cofactor of M[0][f] do getCfactor(M, t, 0, f, n); D += s * M[0][f] * DET(t, n - 1);\n s = -s;\n }\n return D;\n}\nvoid ADJ(int M[N][N],int adj[N][N])\n//to find adjoint matrix {\n if (N == 1) {\n adj[0][0] = 1; return;\n }\n int s = 1,\n t[N][N];\n for (int i=0; i<N; i++) {\n for (int j=0; j<N; j++) {\n //To get cofactor of M[i][j]\n getCfactor(M, t, i, j, N);\n s = ((i+j)%2==0)? 1: -1; //sign of adj[j][i] positive if sum of row and column indexes is even.\n adj[j][i] = (s)*(DET(t, N-1)); //Interchange rows and columns to get the transpose of the cofactor matrix\n }\n }\n}\nbool INV(int M[N][N], float inv[N][N]) {\n int det = DET(M, N);\n if (det == 0) {\n cout << \"can't find its inverse\";\n return false;\n }\n int adj[N][N]; ADJ(M, adj);\n for (int i=0; i<N; i++) for (int j=0; j<N; j++) inv[i][j] = adj[i][j]/float(det);\n return true;\n}\ntemplate<class T> void print(T A[N][N]) //print the matrix. {\n for (int i=0; i<N; i++) { for (int j=0; j<N; j++) cout << A[i][j] << \" \"; cout << endl; }\n}\nint main() {\n int M[N][N] = {\n {1, 2, 3, 4,-2}, {-5, 6, 7, 8, 4}, {9, 10, -11, 12, 1}, {13, -14, -15, 0, 9}, {20 , -26 , 16 , -17 , 25}\n };\n float inv[N][N];\n cout << \"Input matrix is :\\n\"; print(M);\n cout << \"\\nThe Inverse is :\\n\"; if (INV(M, inv)) print(inv);\n return 0;\n}" }, { "code": null, "e": 4198, "s": 3829, "text": "Input matrix is :\n1 2 3 4 -2\n-5 6 7 8 4 \n9 10 -11 12 1 \n13 -14 -15 0 9 \n20 -26 16 -17 25\nThe Inverse is : \n0.0811847 -0.0643008 0.0493814 -0.0247026 0.0237006 \n-0.126819 -0.0161738 0.0745377 -0.0713976 0.0151639 \n0.0933664 0.0028245 -0.0111876 -0.0220437 0.0154006 \n0.143624 0.0582573 -0.0282371 0.0579023 -0.0175466 \n-0.15893 0.0724272 0.0259728 -0.00100988 0.0150219" } ]
Program to calculate gross salary of a person
16 Apr, 2021 Given an integer basic and a character grade which denotes the basic salary and grade of a person respectively, the task is to find the gross salary of the person. Gross Salary: The final salary computed after the additions of DA, HRA and other allowances. The formula for Gross Salary is defined as below: Gross Salary = Basic + HRA + DA + Allow – PFHere, HRA = 20% of Basic DA = 50% of basic Allow = 1700 if grade = ‘A’ Allow = 1500 if grade = ‘B’ Allow = 1300 if grade = ‘C’ PF = 11% of basic Examples: Input: basic = 10000, grade = ‘A’Output: 17600 Input: basic = 4567, grade = ‘B’Output: 8762 Approach: The idea is to find the allowance on the basis of the grade and then compute the HRA, DA, and PF on the basis of the basic salary. Below is the illustration of the computation of HRA, DA, and PF: HRA: House Rent Allowance is 20% of the basic salary: HRA = Basic Salary * 0.20 DA: Daily Allowance is the 50% of the basic salary: DA = Basic Salary * 0.5 PF: Provident Fund is the 11% of the basic salary. PF = Basic Salary * 0.11 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the// salary of the personint computeSalary(int basic, char grade){ int allowance; double hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700; } else if (grade == 'B') { allowance = 1500; } else { allowance = 1300; } int gross; // Calculate gross salary gross = round(basic + hra + da + allowance - pf); return gross;} // Driver Codeint main(){ int basic = 10000; char grade = 'A'; cout << computeSalary(basic, grade);} // Java program to implement// the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to calculate the// salary of the personstatic int computeSalary(int basic, char grade){ double allowance; double hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700.0; } else if (grade == 'B') { allowance = 1500.0; } else { allowance = 1300.0; } double gross; // Calculate gross salary gross = Math.round(basic + hra + da + allowance - pf); return (int)gross;} // Driver Codepublic static void main (String[] args){ int basic = 10000; char grade = 'A'; // Function call System.out.println(computeSalary(basic, grade));}} // This code is contributed by jana_sayantan # Python3 program to implement# the above approach # Function to calculate the# salary of the persondef computeSalary( basic, grade): hra = 0.2 * basic da = 0.5 * basic pf = 0.11 * basic # Condition to compute the # allowance for the person if grade == 'A': allowance = 1700.0 elif grade == 'B': allowance = 1500.0 else: allowance = 1300.0; gross = round(basic + hra + da + allowance - pf) return gross # Driver codeif __name__ == '__main__': basic = 10000 grade = 'A' # Function call print(computeSalary(basic, grade)); # This code is contributed by jana_sayantan // C# program to implement// the above approachusing System; class GFG{ // Function to calculate the// salary of the personstatic int computeSalary(int basic, char grade){ double allowance; double hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700.0; } else if (grade == 'B') { allowance = 1500.0; } else { allowance = 1300.0; } double gross; // Calculate gross salary gross = Math.Round(basic + hra + da + allowance - pf); return (int)gross;} // Driver Codepublic static void Main (String[] args){ int basic = 10000; char grade = 'A'; // Function call Console.WriteLine(computeSalary(basic, grade));}} // This code is contributed by jana_sayantan <script> // JavaScript program for// the above approach // Function to calculate the// salary of the personfunction computeSalary(basic, grade){ let allowance; let hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700.0; } else if (grade == 'B') { allowance = 1500.0; } else { allowance = 1300.0; } let gross; // Calculate gross salary gross = Math.round(basic + hra + da + allowance - pf); return gross;} // Driver code let basic = 10000; let grade = 'A'; // Function call document.write(computeSalary(basic, grade)); // This code is contributed by splevel62.</script> 17600 Time Complexity: O(1) Auxiliary Space: O(1) jana_sayantan splevel62 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2021" }, { "code": null, "e": 192, "s": 28, "text": "Given an integer basic and a character grade which denotes the basic salary and grade of a person respectively, the task is to find the gross salary of the person." }, { "code": null, "e": 335, "s": 192, "text": "Gross Salary: The final salary computed after the additions of DA, HRA and other allowances. The formula for Gross Salary is defined as below:" }, { "code": null, "e": 524, "s": 335, "text": "Gross Salary = Basic + HRA + DA + Allow – PFHere, HRA = 20% of Basic DA = 50% of basic Allow = 1700 if grade = ‘A’ Allow = 1500 if grade = ‘B’ Allow = 1300 if grade = ‘C’ PF = 11% of basic" }, { "code": null, "e": 534, "s": 524, "text": "Examples:" }, { "code": null, "e": 581, "s": 534, "text": "Input: basic = 10000, grade = ‘A’Output: 17600" }, { "code": null, "e": 626, "s": 581, "text": "Input: basic = 4567, grade = ‘B’Output: 8762" }, { "code": null, "e": 832, "s": 626, "text": "Approach: The idea is to find the allowance on the basis of the grade and then compute the HRA, DA, and PF on the basis of the basic salary. Below is the illustration of the computation of HRA, DA, and PF:" }, { "code": null, "e": 886, "s": 832, "text": "HRA: House Rent Allowance is 20% of the basic salary:" }, { "code": null, "e": 915, "s": 889, "text": "HRA = Basic Salary * 0.20" }, { "code": null, "e": 969, "s": 917, "text": "DA: Daily Allowance is the 50% of the basic salary:" }, { "code": null, "e": 996, "s": 972, "text": "DA = Basic Salary * 0.5" }, { "code": null, "e": 1049, "s": 998, "text": "PF: Provident Fund is the 11% of the basic salary." }, { "code": null, "e": 1077, "s": 1052, "text": "PF = Basic Salary * 0.11" }, { "code": null, "e": 1130, "s": 1079, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1134, "s": 1130, "text": "C++" }, { "code": null, "e": 1139, "s": 1134, "text": "Java" }, { "code": null, "e": 1147, "s": 1139, "text": "Python3" }, { "code": null, "e": 1150, "s": 1147, "text": "C#" }, { "code": null, "e": 1161, "s": 1150, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the// salary of the personint computeSalary(int basic, char grade){ int allowance; double hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700; } else if (grade == 'B') { allowance = 1500; } else { allowance = 1300; } int gross; // Calculate gross salary gross = round(basic + hra + da + allowance - pf); return gross;} // Driver Codeint main(){ int basic = 10000; char grade = 'A'; cout << computeSalary(basic, grade);}", "e": 1910, "s": 1161, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to calculate the// salary of the personstatic int computeSalary(int basic, char grade){ double allowance; double hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700.0; } else if (grade == 'B') { allowance = 1500.0; } else { allowance = 1300.0; } double gross; // Calculate gross salary gross = Math.round(basic + hra + da + allowance - pf); return (int)gross;} // Driver Codepublic static void main (String[] args){ int basic = 10000; char grade = 'A'; // Function call System.out.println(computeSalary(basic, grade));}} // This code is contributed by jana_sayantan", "e": 2883, "s": 1910, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to calculate the# salary of the persondef computeSalary( basic, grade): hra = 0.2 * basic da = 0.5 * basic pf = 0.11 * basic # Condition to compute the # allowance for the person if grade == 'A': allowance = 1700.0 elif grade == 'B': allowance = 1500.0 else: allowance = 1300.0; gross = round(basic + hra + da + allowance - pf) return gross # Driver codeif __name__ == '__main__': basic = 10000 grade = 'A' # Function call print(computeSalary(basic, grade)); # This code is contributed by jana_sayantan", "e": 3576, "s": 2883, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to calculate the// salary of the personstatic int computeSalary(int basic, char grade){ double allowance; double hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700.0; } else if (grade == 'B') { allowance = 1500.0; } else { allowance = 1300.0; } double gross; // Calculate gross salary gross = Math.Round(basic + hra + da + allowance - pf); return (int)gross;} // Driver Codepublic static void Main (String[] args){ int basic = 10000; char grade = 'A'; // Function call Console.WriteLine(computeSalary(basic, grade));}} // This code is contributed by jana_sayantan", "e": 4521, "s": 3576, "text": null }, { "code": "<script> // JavaScript program for// the above approach // Function to calculate the// salary of the personfunction computeSalary(basic, grade){ let allowance; let hra, da, pf; hra = 0.2 * basic; da = 0.5 * basic; pf = 0.11 * basic; // Condition to compute the // allowance for the person if (grade == 'A') { allowance = 1700.0; } else if (grade == 'B') { allowance = 1500.0; } else { allowance = 1300.0; } let gross; // Calculate gross salary gross = Math.round(basic + hra + da + allowance - pf); return gross;} // Driver code let basic = 10000; let grade = 'A'; // Function call document.write(computeSalary(basic, grade)); // This code is contributed by splevel62.</script>", "e": 5401, "s": 4521, "text": null }, { "code": null, "e": 5407, "s": 5401, "text": "17600" }, { "code": null, "e": 5452, "s": 5407, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 5466, "s": 5452, "text": "jana_sayantan" }, { "code": null, "e": 5476, "s": 5466, "text": "splevel62" }, { "code": null, "e": 5489, "s": 5476, "text": "Mathematical" }, { "code": null, "e": 5508, "s": 5489, "text": "School Programming" }, { "code": null, "e": 5521, "s": 5508, "text": "Mathematical" }, { "code": null, "e": 5619, "s": 5521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5651, "s": 5619, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5695, "s": 5651, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 5741, "s": 5695, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 5783, "s": 5741, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 5808, "s": 5783, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 5826, "s": 5808, "text": "Python Dictionary" }, { "code": null, "e": 5851, "s": 5826, "text": "Reverse a string in Java" }, { "code": null, "e": 5867, "s": 5851, "text": "Arrays in C/C++" }, { "code": null, "e": 5890, "s": 5867, "text": "Introduction To PYTHON" } ]
zlib.crc32() in python
23 Mar, 2020 With the help of zlib.crc32() method, we can compute the checksum for crc32 (Cyclic Redundancy Check) to a particular data. It will give 32-bit integer value as a result by using zlib.crc32() method. Syntax : zlib.crc32(s)Return : Return the unsigned 32-bit checksum integer. Example #1 :In this example we can see that by using zlib.crc32() method, we are able to compute the unsigned 32-bit checksum for given data by using this method. # import zlib and crc32import zlib s = b'I love python, Hello world'# using zlib.crc32() methodt = zlib.crc32(s) print(t) Output : 2185029202 Example #2 : # import zlib and crc32import zlib s = b'Hello GeeksForGeeks'# using zlib.crc32() methodt = zlib.crc32(s) print(t) Output : 3165518624 python-zlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2020" }, { "code": null, "e": 228, "s": 28, "text": "With the help of zlib.crc32() method, we can compute the checksum for crc32 (Cyclic Redundancy Check) to a particular data. It will give 32-bit integer value as a result by using zlib.crc32() method." }, { "code": null, "e": 304, "s": 228, "text": "Syntax : zlib.crc32(s)Return : Return the unsigned 32-bit checksum integer." }, { "code": null, "e": 467, "s": 304, "text": "Example #1 :In this example we can see that by using zlib.crc32() method, we are able to compute the unsigned 32-bit checksum for given data by using this method." }, { "code": "# import zlib and crc32import zlib s = b'I love python, Hello world'# using zlib.crc32() methodt = zlib.crc32(s) print(t)", "e": 591, "s": 467, "text": null }, { "code": null, "e": 600, "s": 591, "text": "Output :" }, { "code": null, "e": 611, "s": 600, "text": "2185029202" }, { "code": null, "e": 624, "s": 611, "text": "Example #2 :" }, { "code": "# import zlib and crc32import zlib s = b'Hello GeeksForGeeks'# using zlib.crc32() methodt = zlib.crc32(s) print(t)", "e": 741, "s": 624, "text": null }, { "code": null, "e": 750, "s": 741, "text": "Output :" }, { "code": null, "e": 761, "s": 750, "text": "3165518624" }, { "code": null, "e": 773, "s": 761, "text": "python-zlib" }, { "code": null, "e": 780, "s": 773, "text": "Python" }, { "code": null, "e": 878, "s": 780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 910, "s": 878, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 937, "s": 910, "text": "Python Classes and Objects" }, { "code": null, "e": 958, "s": 937, "text": "Python OOPs Concepts" }, { "code": null, "e": 981, "s": 958, "text": "Introduction To PYTHON" }, { "code": null, "e": 1037, "s": 981, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1079, "s": 1037, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1110, "s": 1079, "text": "Python | os.path.join() method" }, { "code": null, "e": 1152, "s": 1110, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1191, "s": 1152, "text": "Python | Get unique values from a list" } ]
Batch Script - CMD
This batch command invokes another instance of command prompt. cmd @echo off cmd Another instance of command prompt will be invoked.
[ { "code": null, "e": 2366, "s": 2303, "text": "This batch command invokes another instance of command prompt." }, { "code": null, "e": 2371, "s": 2366, "text": "cmd\n" }, { "code": null, "e": 2386, "s": 2371, "text": "@echo off \ncmd" } ]
How to add timestamp to CSV file in Python
23 Aug, 2021 Prerequisite: Datetime module In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let’s the stepwise implementation for adding timestamp to CSV files in Python. Import csv and datetime module. We will use the csv module to read and write the csv file and datetime module to add the current date and time in the csv file Take the data from the user. Open the CSV file in read and write mode (‘r+’) using open() function.The open() function opens a file and returns its as a file-object.newline = ‘ ‘ controls how universal newlines mode works. It can be None, ‘ ‘, ‘\n’, ‘\r’, and ‘\r\n’.write() returns a writer object which is responsible for converting the user’s data into a delimited string. The open() function opens a file and returns its as a file-object. newline = ‘ ‘ controls how universal newlines mode works. It can be None, ‘ ‘, ‘\n’, ‘\r’, and ‘\r\n’. write() returns a writer object which is responsible for converting the user’s data into a delimited string. Get current date and time using the datetime.now() function of datetime module. Iterate over all the data in the rows variable with the help of a for loop. Insert the current date and time at 0th index in every data using the insert() function. Write the data using writerow() in the CSV file with the current date and time. Example 1: Add timestamp to CSV file Python3 # Importing required modulesimport csvfrom datetime import datetime # Here we are storing our data in a# variable. We'll add this data in# our csv filerows = [['GeeksforGeeks1', 'GeeksforGeeks2'], ['GeeksforGeeks3', 'GeeksforGeeks4'], ['GeeksforGeeks5', 'GeeksforGeeks6']] # Opening the CSV file in read and# write mode using the open() modulewith open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file: # creating the csv writer file_write = csv.writer(file) # storing current date and time current_date_time = datetime.now() # Iterating over all the data in the rows # variable for val in rows: # Inserting the date and time at 0th # index val.insert(0, current_date_time) # writing the data in csv file file_write.writerow(val) Output : Example 2: Adding timestamp to CSV file Python3 # Importing required modulesimport csvfrom datetime import datetime # function to write in csv filedef write_in_csv(rows): # Opening the CSV file in read and # write mode using the open() module with open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file: # creating the csv writer file_write = csv.writer(file) # Iterating over all the data in the rows # variable for val in rows: # writing the data in csv file file_write.writerow(val) # list to store the values of the rowsrows = [] # while loop to take# inputs from the userrun = ''while run != 'no': # lists to store the user data val = [] # Taking inputs from the user val1 = input("Enter 1st value:- ") val2 = input("Enter 2nd value:- ") val3 = input("Enter 3rd value:- ") # storing current date and time current_date_time = datetime.now() # Appending the inputs in a list val.append(current_date_time) val.append(val1) val.append(val2) val.append(val3) # Taking input to add one more row # If user enters 'no' then the will loop will break run = input("Do you want to add one more row? Type Yes or No:- ") run = run.lower() # Adding the stored data in rows list rows.append(val) # Calling function to write in csv filewrite_in_csv(rows) Output: It is also possible to add timestamp to a CSV file that already contains some data. For this open the first file in read mode and the second file in write mode. Creating a csv reader object of the first file using the reader() function of csv module. reader() return a reader object which will iterate over lines in the given CSV file. Append every data stored in the first file in rows variable using a for loop. Create a writer object of the second file using the writer() function of csv module. Now iterate over all the data in the rows variable using a for loop. Store the current date and time in a variable and then inserting it in the data at 0th index using the insert() function. Write the stored data in File2 using the writerow() function of csv module. Example 1: Adding timestamp to existing data Content of File1: Python3 # Importing required modulesimport csvfrom datetime import datetime # creating a list to store the# existing data of CSV filerows = [] # Opening the CSV file in read mode using # the open() modulewith open(r'FILE1.csv', 'r', newline='') as file: # Opening another CSV file to in write mode # to add the data with open(r'FILE2.csv', 'w', newline='') as file2: # creating the csv reader reader = csv.reader(file, delimiter=',') # storing the data of the csv file in a list for row in reader: rows.append(row) # creating the csv writer file_write = csv.writer(file2) # Iterating over all the data in the rows # variable for val in rows: # storing current date and time in a # variable current_date_time = datetime.now() val.insert(0, current_date_time) # writing the data in csv file file_write.writerow(val) Output: Picked python-csv Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Aug, 2021" }, { "code": null, "e": 84, "s": 54, "text": "Prerequisite: Datetime module" }, { "code": null, "e": 324, "s": 84, "text": "In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let’s the stepwise implementation for adding timestamp to CSV files in Python." }, { "code": null, "e": 483, "s": 324, "text": "Import csv and datetime module. We will use the csv module to read and write the csv file and datetime module to add the current date and time in the csv file" }, { "code": null, "e": 512, "s": 483, "text": "Take the data from the user." }, { "code": null, "e": 859, "s": 512, "text": "Open the CSV file in read and write mode (‘r+’) using open() function.The open() function opens a file and returns its as a file-object.newline = ‘ ‘ controls how universal newlines mode works. It can be None, ‘ ‘, ‘\\n’, ‘\\r’, and ‘\\r\\n’.write() returns a writer object which is responsible for converting the user’s data into a delimited string." }, { "code": null, "e": 926, "s": 859, "text": "The open() function opens a file and returns its as a file-object." }, { "code": null, "e": 1029, "s": 926, "text": "newline = ‘ ‘ controls how universal newlines mode works. It can be None, ‘ ‘, ‘\\n’, ‘\\r’, and ‘\\r\\n’." }, { "code": null, "e": 1138, "s": 1029, "text": "write() returns a writer object which is responsible for converting the user’s data into a delimited string." }, { "code": null, "e": 1218, "s": 1138, "text": "Get current date and time using the datetime.now() function of datetime module." }, { "code": null, "e": 1294, "s": 1218, "text": "Iterate over all the data in the rows variable with the help of a for loop." }, { "code": null, "e": 1383, "s": 1294, "text": "Insert the current date and time at 0th index in every data using the insert() function." }, { "code": null, "e": 1464, "s": 1383, "text": "Write the data using writerow() in the CSV file with the current date and time. " }, { "code": null, "e": 1501, "s": 1464, "text": "Example 1: Add timestamp to CSV file" }, { "code": null, "e": 1509, "s": 1501, "text": "Python3" }, { "code": "# Importing required modulesimport csvfrom datetime import datetime # Here we are storing our data in a# variable. We'll add this data in# our csv filerows = [['GeeksforGeeks1', 'GeeksforGeeks2'], ['GeeksforGeeks3', 'GeeksforGeeks4'], ['GeeksforGeeks5', 'GeeksforGeeks6']] # Opening the CSV file in read and# write mode using the open() modulewith open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file: # creating the csv writer file_write = csv.writer(file) # storing current date and time current_date_time = datetime.now() # Iterating over all the data in the rows # variable for val in rows: # Inserting the date and time at 0th # index val.insert(0, current_date_time) # writing the data in csv file file_write.writerow(val)", "e": 2340, "s": 1509, "text": null }, { "code": null, "e": 2349, "s": 2340, "text": "Output :" }, { "code": null, "e": 2390, "s": 2349, "text": "Example 2: Adding timestamp to CSV file" }, { "code": null, "e": 2398, "s": 2390, "text": "Python3" }, { "code": "# Importing required modulesimport csvfrom datetime import datetime # function to write in csv filedef write_in_csv(rows): # Opening the CSV file in read and # write mode using the open() module with open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file: # creating the csv writer file_write = csv.writer(file) # Iterating over all the data in the rows # variable for val in rows: # writing the data in csv file file_write.writerow(val) # list to store the values of the rowsrows = [] # while loop to take# inputs from the userrun = ''while run != 'no': # lists to store the user data val = [] # Taking inputs from the user val1 = input(\"Enter 1st value:- \") val2 = input(\"Enter 2nd value:- \") val3 = input(\"Enter 3rd value:- \") # storing current date and time current_date_time = datetime.now() # Appending the inputs in a list val.append(current_date_time) val.append(val1) val.append(val2) val.append(val3) # Taking input to add one more row # If user enters 'no' then the will loop will break run = input(\"Do you want to add one more row? Type Yes or No:- \") run = run.lower() # Adding the stored data in rows list rows.append(val) # Calling function to write in csv filewrite_in_csv(rows)", "e": 3753, "s": 2398, "text": null }, { "code": null, "e": 3761, "s": 3753, "text": "Output:" }, { "code": null, "e": 4097, "s": 3761, "text": "It is also possible to add timestamp to a CSV file that already contains some data. For this open the first file in read mode and the second file in write mode. Creating a csv reader object of the first file using the reader() function of csv module. reader() return a reader object which will iterate over lines in the given CSV file." }, { "code": null, "e": 4528, "s": 4097, "text": "Append every data stored in the first file in rows variable using a for loop. Create a writer object of the second file using the writer() function of csv module. Now iterate over all the data in the rows variable using a for loop. Store the current date and time in a variable and then inserting it in the data at 0th index using the insert() function. Write the stored data in File2 using the writerow() function of csv module. " }, { "code": null, "e": 4573, "s": 4528, "text": "Example 1: Adding timestamp to existing data" }, { "code": null, "e": 4591, "s": 4573, "text": "Content of File1:" }, { "code": null, "e": 4599, "s": 4591, "text": "Python3" }, { "code": "# Importing required modulesimport csvfrom datetime import datetime # creating a list to store the# existing data of CSV filerows = [] # Opening the CSV file in read mode using # the open() modulewith open(r'FILE1.csv', 'r', newline='') as file: # Opening another CSV file to in write mode # to add the data with open(r'FILE2.csv', 'w', newline='') as file2: # creating the csv reader reader = csv.reader(file, delimiter=',') # storing the data of the csv file in a list for row in reader: rows.append(row) # creating the csv writer file_write = csv.writer(file2) # Iterating over all the data in the rows # variable for val in rows: # storing current date and time in a # variable current_date_time = datetime.now() val.insert(0, current_date_time) # writing the data in csv file file_write.writerow(val)", "e": 5590, "s": 4599, "text": null }, { "code": null, "e": 5598, "s": 5590, "text": "Output:" }, { "code": null, "e": 5605, "s": 5598, "text": "Picked" }, { "code": null, "e": 5616, "s": 5605, "text": "python-csv" }, { "code": null, "e": 5632, "s": 5616, "text": "Python-datetime" }, { "code": null, "e": 5639, "s": 5632, "text": "Python" } ]
Solving multiplexer circuit
14 May, 2020 The procedure for solving and finding the output function of the given multiplexer is quite simple. Firstly we will discuss the procedure and then illustrate it with examples. Procedure: Firstly truth table is constructed for the given multiplexer. Select lines in multiplexer are considered as input for the truth table. Output in truth table can be four forms i.e. ( 0, 1, Q, Q’). Now with the help of truth table we find the extended expression. Then the expression is minimized using boolean algebraic rules. Final function can be either in expression form or in SOP or POS form. Example-1:Given MUX is following, Explanation : Step-1: First draw the truth table. For the truth table, select lines A and B are the input.According to the circuit,I0 = C' (hence first row of truth table will be C') I1 = C' I2 = C I3 = C I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively. I0 = C' (hence first row of truth table will be C') I1 = C' I2 = C I3 = C I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively. Step-2: Now we will find the expression of Y:Y = A'B'C' + A'BC' + AB'C + ABC = A'C'(B' + B) + AC(B' + B) = A'C' + AC Y = A'B'C' + A'BC' + AB'C + ABC = A'C'(B' + B) + AC(B' + B) = A'C' + AC Example-2:Given MUX, Explanation : Step-1: Truth table is following. For the truth table select lines B and C are input.According to the circuit,I0 = A (hence first row of truth table will be A) I1 = A' I2 = 1 I3 = 0 I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively. I0 = A (hence first row of truth table will be A) I1 = A' I2 = 1 I3 = 0 I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively. Step-2: Now we will find the output:f(A, B, C) = AB'C' + A'B'C + BC'.1 = AB'C' + A'B'C + BC'(A + A') = AB'C' + A'B'C + ABC' + A'BC' = 100 001 110 010 = m(1, 2, 4, 6) f(A, B, C) = AB'C' + A'B'C + BC'.1 = AB'C' + A'B'C + BC'(A + A') = AB'C' + A'B'C + ABC' + A'BC' = 100 001 110 010 = m(1, 2, 4, 6) Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Latches in Digital Logic Digital to Analog Conversion Half Subtractor in Digital Logic Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2020" }, { "code": null, "e": 230, "s": 54, "text": "The procedure for solving and finding the output function of the given multiplexer is quite simple. Firstly we will discuss the procedure and then illustrate it with examples." }, { "code": null, "e": 241, "s": 230, "text": "Procedure:" }, { "code": null, "e": 303, "s": 241, "text": "Firstly truth table is constructed for the given multiplexer." }, { "code": null, "e": 376, "s": 303, "text": "Select lines in multiplexer are considered as input for the truth table." }, { "code": null, "e": 437, "s": 376, "text": "Output in truth table can be four forms i.e. ( 0, 1, Q, Q’)." }, { "code": null, "e": 503, "s": 437, "text": "Now with the help of truth table we find the extended expression." }, { "code": null, "e": 567, "s": 503, "text": "Then the expression is minimized using boolean algebraic rules." }, { "code": null, "e": 638, "s": 567, "text": "Final function can be either in expression form or in SOP or POS form." }, { "code": null, "e": 672, "s": 638, "text": "Example-1:Given MUX is following," }, { "code": null, "e": 686, "s": 672, "text": "Explanation :" }, { "code": null, "e": 975, "s": 686, "text": "Step-1: First draw the truth table. For the truth table, select lines A and B are the input.According to the circuit,I0 = C' (hence first row of truth table will be C')\nI1 = C'\nI2 = C\nI3 = C I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively." }, { "code": null, "e": 1050, "s": 975, "text": "I0 = C' (hence first row of truth table will be C')\nI1 = C'\nI2 = C\nI3 = C " }, { "code": null, "e": 1148, "s": 1050, "text": "I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively." }, { "code": null, "e": 1270, "s": 1148, "text": "Step-2: Now we will find the expression of Y:Y = A'B'C' + A'BC' + AB'C + ABC\n = A'C'(B' + B) + AC(B' + B)\n = A'C' + AC\n" }, { "code": null, "e": 1347, "s": 1270, "text": "Y = A'B'C' + A'BC' + AB'C + ABC\n = A'C'(B' + B) + AC(B' + B)\n = A'C' + AC\n" }, { "code": null, "e": 1368, "s": 1347, "text": "Example-2:Given MUX," }, { "code": null, "e": 1382, "s": 1368, "text": "Explanation :" }, { "code": null, "e": 1662, "s": 1382, "text": "Step-1: Truth table is following. For the truth table select lines B and C are input.According to the circuit,I0 = A (hence first row of truth table will be A)\nI1 = A'\nI2 = 1\nI3 = 0 I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively." }, { "code": null, "e": 1735, "s": 1662, "text": "I0 = A (hence first row of truth table will be A)\nI1 = A'\nI2 = 1\nI3 = 0 " }, { "code": null, "e": 1833, "s": 1735, "text": "I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively." }, { "code": null, "e": 2047, "s": 1833, "text": "Step-2: Now we will find the output:f(A, B, C) = AB'C' + A'B'C + BC'.1\n = AB'C' + A'B'C + BC'(A + A')\n = AB'C' + A'B'C + ABC' + A'BC'\n = 100 001 110 010\n = m(1, 2, 4, 6)" }, { "code": null, "e": 2225, "s": 2047, "text": "f(A, B, C) = AB'C' + A'B'C + BC'.1\n = AB'C' + A'B'C + BC'(A + A')\n = AB'C' + A'B'C + ABC' + A'BC'\n = 100 001 110 010\n = m(1, 2, 4, 6)" }, { "code": null, "e": 2260, "s": 2225, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 2268, "s": 2260, "text": "GATE CS" }, { "code": null, "e": 2366, "s": 2268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2406, "s": 2366, "text": "Introduction to memory and memory units" }, { "code": null, "e": 2435, "s": 2406, "text": "Analog to Digital Conversion" }, { "code": null, "e": 2460, "s": 2435, "text": "Latches in Digital Logic" }, { "code": null, "e": 2489, "s": 2460, "text": "Digital to Analog Conversion" }, { "code": null, "e": 2522, "s": 2489, "text": "Half Subtractor in Digital Logic" }, { "code": null, "e": 2542, "s": 2522, "text": "Layers of OSI Model" }, { "code": null, "e": 2566, "s": 2542, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2579, "s": 2566, "text": "TCP/IP Model" }, { "code": null, "e": 2606, "s": 2579, "text": "Types of Operating Systems" } ]
Python | Pandas Series.nlargest()
11 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.nlargest() function return the n largest element from the underlying data in the given series object. Syntax: Series.nlargest(n=5, keep=’first’) Parameter :n : Return this many descending sorted values.keep : {‘first’, ‘last’, ‘all’}, default ‘first’ Returns : Series Example #1: Use Series.nlargest() function to return the first n largest element from the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.nlargest() function to find the first 2 largest value in the given series object. # return the first 2 of the largest# elementresult = sr.nlargest(n = 2) # Print the resultprint(result) Output : As we can see in the output, the Series.nlargest() function has successfully returned the first 2 largest value in the given series object. Example #2: Use Series.nlargest() function to return the first n largest element from the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Print the seriesprint(sr) Output : Now we will use Series.nlargest() function to find the first 5 largest value in the given series object. # return the first 5 of the largest# elementresult = sr.nlargest(n = 5) # Print the resultprint(result) Output : As we can see in the output, the Series.nlargest() function has successfully returned the first 5 largest value in the given series object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 401, "s": 285, "text": "Pandas Series.nlargest() function return the n largest element from the underlying data in the given series object." }, { "code": null, "e": 444, "s": 401, "text": "Syntax: Series.nlargest(n=5, keep=’first’)" }, { "code": null, "e": 550, "s": 444, "text": "Parameter :n : Return this many descending sorted values.keep : {‘first’, ‘last’, ‘all’}, default ‘first’" }, { "code": null, "e": 567, "s": 550, "text": "Returns : Series" }, { "code": null, "e": 678, "s": 567, "text": "Example #1: Use Series.nlargest() function to return the first n largest element from the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 934, "s": 678, "text": null }, { "code": null, "e": 943, "s": 934, "text": "Output :" }, { "code": null, "e": 1048, "s": 943, "text": "Now we will use Series.nlargest() function to find the first 2 largest value in the given series object." }, { "code": "# return the first 2 of the largest# elementresult = sr.nlargest(n = 2) # Print the resultprint(result)", "e": 1153, "s": 1048, "text": null }, { "code": null, "e": 1162, "s": 1153, "text": "Output :" }, { "code": null, "e": 1413, "s": 1162, "text": "As we can see in the output, the Series.nlargest() function has successfully returned the first 2 largest value in the given series object. Example #2: Use Series.nlargest() function to return the first n largest element from the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Print the seriesprint(sr)", "e": 1567, "s": 1413, "text": null }, { "code": null, "e": 1576, "s": 1567, "text": "Output :" }, { "code": null, "e": 1681, "s": 1576, "text": "Now we will use Series.nlargest() function to find the first 5 largest value in the given series object." }, { "code": "# return the first 5 of the largest# elementresult = sr.nlargest(n = 5) # Print the resultprint(result)", "e": 1786, "s": 1681, "text": null }, { "code": null, "e": 1795, "s": 1786, "text": "Output :" }, { "code": null, "e": 1935, "s": 1795, "text": "As we can see in the output, the Series.nlargest() function has successfully returned the first 5 largest value in the given series object." }, { "code": null, "e": 1956, "s": 1935, "text": "Python pandas-series" }, { "code": null, "e": 1985, "s": 1956, "text": "Python pandas-series-methods" }, { "code": null, "e": 1999, "s": 1985, "text": "Python-pandas" }, { "code": null, "e": 2006, "s": 1999, "text": "Python" } ]
Send multiple data with ajax in PHP
Data can be sent through JSON or via normal POST. Following is an example showing data sent through JSON − var value_1 = 1; var value_2 = 2; var value_3 = 3; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "your_url_goes_here", data: { data_1: value_1, data_2: value_2, data_3: value_3 }, success: function (result) { // perform operations here } }); With normal post, the below code can be used − $.ajax({ type: "POST", url: $('form').attr("action"), data: $('#form0').serialize(), success: function (result) { // perform operations here } }); An alternate to the above code has been demonstrated below − data:'id='+ID & 'user_id=' + USERID, with: data: {id:ID, user_id:USERID} so your code will look like this : $(document).ready(function(){ $(document).on('click','.show_more',function(){ var ID = 10; var USERID =1; $('.show_more').hide(); $('.loding').show(); $.ajax({ type:'POST', url:'/ajaxload.php', data: {id:ID, user_id:USERID}, success:function(html){ $('#show_more_main'+ID).remove(); $('.post_list').append(html); } }); }); });
[ { "code": null, "e": 1294, "s": 1187, "text": "Data can be sent through JSON or via normal POST. Following is an example showing data sent through JSON −" }, { "code": null, "e": 1590, "s": 1294, "text": "var value_1 = 1;\nvar value_2 = 2;\nvar value_3 = 3;\n$.ajax({\n type: \"POST\",\n contentType: \"application/json; charset=utf-8\",\n url: \"your_url_goes_here\",\n data: { data_1: value_1, data_2: value_2, data_3: value_3 },\n success: function (result) {\n // perform operations here\n }\n});" }, { "code": null, "e": 1637, "s": 1590, "text": "With normal post, the below code can be used −" }, { "code": null, "e": 1805, "s": 1637, "text": "$.ajax({\n type: \"POST\",\n url: $('form').attr(\"action\"),\n data: $('#form0').serialize(),\n success: function (result) {\n // perform operations here\n }\n});" }, { "code": null, "e": 1866, "s": 1805, "text": "An alternate to the above code has been demonstrated below −" }, { "code": null, "e": 2412, "s": 1866, "text": "data:'id='+ID & 'user_id=' + USERID,\nwith:\ndata: {id:ID, user_id:USERID}\nso your code will look like this :\n$(document).ready(function(){\n $(document).on('click','.show_more',function(){\n var ID = 10;\n var USERID =1;\n $('.show_more').hide();\n $('.loding').show();\n $.ajax({\n type:'POST',\n url:'/ajaxload.php',\n data: {id:ID, user_id:USERID},\n success:function(html){\n $('#show_more_main'+ID).remove();\n $('.post_list').append(html);\n }\n });\n });\n});" } ]
Flutter – Installation on macOS
24 Sep, 2021 In this article, we are going to take a look at Flutter installation of macOS. In this article, we will see what are the system requirement for it to work with flutter, how to set an environment variable, how to install flutter SDK and Dart SDK. We will understand how to use flutter doctor, how to install Xcode and Android Studio, accept Android licenses, move to the desired flutter channel and finally create our first flutter project. To install and run Flutter SDK, on a macOS system it must fulfill these minimum requirements. Operating System: macOS (64-bit) Disk Space: 3.5 Gb Tools: Git, IDE (Xcode includes git) First, we will create a new folder in our home directory, here I will name it tools. In the tools folder, we will clone flutter from the Github repository. And to do that we will open the terminal in that folder and execute the following command: git clone https://github.com/flutter/flutter.git This command will take some time to execute as it will download the flutter SDK in our system. After it gets executed you will see that it contains a flutter directory, and if you open it you will find a bunch of other folders and one among them in bin folder. You can take a note of its location as it will be required in the next step. The problem with our flutter installation is that it will just execute the export path and append the path to the flutter repository that we just downloaded. So if we open a terminal in another directory flutter won’t work. And to make it work we will have to update path variables. For this first we need to identify which terminal we are using, so you can open the terminal and take a look at the title bar, here in the image below you can see zsh written, so this is Z shell. The other one is the bash terminal. So if you are using the Zsh terminal we have to create a file in the home repository which will be named .zshrc and for the bash terminal, the file will be named .bashrc . So this file is going to hold a script that will get executed whenever the terminal opens. To do that we will have to open this file in any text editor from the finder as this will be invisible into the terminal. And once this is open we will paste the below code in the file and replace the PATH_TO_FLUTTER_GIT_DIRECTORY with the path of the bin folder in the flutter directory and save the file. export PATH="$PATH:[PATH_TO_FLUTTER_GIT_DIRECTORY]/flutter/bin" After all, this is we will restart the system and run the command flutter in the terminal, which will install dart SDK (dart SDK is mandatory for flutter to work). Flutter doctor command checks the system environment and reports the output to the terminal, it shows if something is missing or not working or if something needs to be updated for flutter to work. Now we will run the flutter doctor command in the terminal. It will show output similar to this. It says that Android Studio is not installed, Xcode is not installed and some other dependencies need to be installed or fixed. We have to deal with all of that to work with flutter. Now we will install Xcode, and to do so you need to go to the app store and search for Xcode, and hit the installation button. It will take a while to get installed. After it is installed we need to run the two commands in the terminal. 1. sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer 2. sudo xcodebuild -runFirstLaunch Now to fix the issues with the Android Studio and Android Toolchain we will install android studio. First, we will download the Android Studio DMG file from the official website. After it is downloaded launch the DMG file and copy the Android Studio into the application folder. And then we can go through all the default settings in the Android Studio setup wizard to install Android Studio. After the Android Studio is installed we will launch it and click on the configurations button and go to plugins. Here we will search for flutter plugin and install it which will install the dart plugin automatically. And after this, you can restart the system. Now, if we run the flutter doctor in the terminal once again we will see both the Xcode and Android Studio are installed but we need to accept android licenses. And to resolve this problem we will run the below command in the terminal. It will ask for your content to approve all the licenses. flutter doctor --android-licenses And if you run flutter doctor everything will be sorted except VS code not installed and no connected device. If you want you can install vs code by it is not mandatory and we can always connect a device while making our first flutter project. If you run the command flutter channel you will see that we are currently in the master channel by default. If you want to make a production-ready application you should switch to the stable channel, and to do that you can run the command flutter channel stable. But because we are going to make a macOS desktop app we will use the master channel only. To create a macOS desktop app we need to enable macOS desktop and to do this we will run this command flutter config –enable-macos-desktop. Now we are all set to create our first project in flutter. For we will create a folder with any desired name and open a terminal in that folder and run the command flutter create hello_world. This command will create a flutter project with the name hello_world inside that folder. And to run this project we go inside the project folder with the command cd hello_world and run the command flutter run. This command will execute our hello_world project and open that in a new window. Here you will see a counter app, which is always the demo app of flutter. And if you want to edit the code you can always open the hello_world folder with the IDE of your choice. With this, we are all ready to have a deep dive in the world of flutter and make some amazing applications! khushboogoyal499 Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Search Bar Flutter - FutureBuilder Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Search Bar Flutter - FutureBuilder Widget Flutter - Dialogs
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 469, "s": 28, "text": "In this article, we are going to take a look at Flutter installation of macOS. In this article, we will see what are the system requirement for it to work with flutter, how to set an environment variable, how to install flutter SDK and Dart SDK. We will understand how to use flutter doctor, how to install Xcode and Android Studio, accept Android licenses, move to the desired flutter channel and finally create our first flutter project." }, { "code": null, "e": 563, "s": 469, "text": "To install and run Flutter SDK, on a macOS system it must fulfill these minimum requirements." }, { "code": null, "e": 596, "s": 563, "text": "Operating System: macOS (64-bit)" }, { "code": null, "e": 615, "s": 596, "text": "Disk Space: 3.5 Gb" }, { "code": null, "e": 652, "s": 615, "text": "Tools: Git, IDE (Xcode includes git)" }, { "code": null, "e": 900, "s": 652, "text": " First, we will create a new folder in our home directory, here I will name it tools. In the tools folder, we will clone flutter from the Github repository. And to do that we will open the terminal in that folder and execute the following command:" }, { "code": null, "e": 950, "s": 900, "text": "git clone https://github.com/flutter/flutter.git " }, { "code": null, "e": 1288, "s": 950, "text": "This command will take some time to execute as it will download the flutter SDK in our system. After it gets executed you will see that it contains a flutter directory, and if you open it you will find a bunch of other folders and one among them in bin folder. You can take a note of its location as it will be required in the next step." }, { "code": null, "e": 1768, "s": 1288, "text": "The problem with our flutter installation is that it will just execute the export path and append the path to the flutter repository that we just downloaded. So if we open a terminal in another directory flutter won’t work. And to make it work we will have to update path variables. For this first we need to identify which terminal we are using, so you can open the terminal and take a look at the title bar, here in the image below you can see zsh written, so this is Z shell. " }, { "code": null, "e": 2374, "s": 1768, "text": "The other one is the bash terminal. So if you are using the Zsh terminal we have to create a file in the home repository which will be named .zshrc and for the bash terminal, the file will be named .bashrc . So this file is going to hold a script that will get executed whenever the terminal opens. To do that we will have to open this file in any text editor from the finder as this will be invisible into the terminal. And once this is open we will paste the below code in the file and replace the PATH_TO_FLUTTER_GIT_DIRECTORY with the path of the bin folder in the flutter directory and save the file." }, { "code": null, "e": 2438, "s": 2374, "text": "export PATH=\"$PATH:[PATH_TO_FLUTTER_GIT_DIRECTORY]/flutter/bin\"" }, { "code": null, "e": 2602, "s": 2438, "text": "After all, this is we will restart the system and run the command flutter in the terminal, which will install dart SDK (dart SDK is mandatory for flutter to work)." }, { "code": null, "e": 2897, "s": 2602, "text": "Flutter doctor command checks the system environment and reports the output to the terminal, it shows if something is missing or not working or if something needs to be updated for flutter to work. Now we will run the flutter doctor command in the terminal. It will show output similar to this." }, { "code": null, "e": 3080, "s": 2897, "text": "It says that Android Studio is not installed, Xcode is not installed and some other dependencies need to be installed or fixed. We have to deal with all of that to work with flutter." }, { "code": null, "e": 3247, "s": 3080, "text": "Now we will install Xcode, and to do so you need to go to the app store and search for Xcode, and hit the installation button. It will take a while to get installed. " }, { "code": null, "e": 3318, "s": 3247, "text": "After it is installed we need to run the two commands in the terminal." }, { "code": null, "e": 3426, "s": 3318, "text": "1. sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer\n2. sudo xcodebuild -runFirstLaunch" }, { "code": null, "e": 3527, "s": 3426, "text": "Now to fix the issues with the Android Studio and Android Toolchain we will install android studio. " }, { "code": null, "e": 3820, "s": 3527, "text": "First, we will download the Android Studio DMG file from the official website. After it is downloaded launch the DMG file and copy the Android Studio into the application folder. And then we can go through all the default settings in the Android Studio setup wizard to install Android Studio." }, { "code": null, "e": 4082, "s": 3820, "text": "After the Android Studio is installed we will launch it and click on the configurations button and go to plugins. Here we will search for flutter plugin and install it which will install the dart plugin automatically. And after this, you can restart the system." }, { "code": null, "e": 4244, "s": 4082, "text": "Now, if we run the flutter doctor in the terminal once again we will see both the Xcode and Android Studio are installed but we need to accept android licenses. " }, { "code": null, "e": 4377, "s": 4244, "text": "And to resolve this problem we will run the below command in the terminal. It will ask for your content to approve all the licenses." }, { "code": null, "e": 4411, "s": 4377, "text": "flutter doctor --android-licenses" }, { "code": null, "e": 4655, "s": 4411, "text": "And if you run flutter doctor everything will be sorted except VS code not installed and no connected device. If you want you can install vs code by it is not mandatory and we can always connect a device while making our first flutter project." }, { "code": null, "e": 5149, "s": 4655, "text": "If you run the command flutter channel you will see that we are currently in the master channel by default. If you want to make a production-ready application you should switch to the stable channel, and to do that you can run the command flutter channel stable. But because we are going to make a macOS desktop app we will use the master channel only. To create a macOS desktop app we need to enable macOS desktop and to do this we will run this command flutter config –enable-macos-desktop. " }, { "code": null, "e": 5812, "s": 5149, "text": "Now we are all set to create our first project in flutter. For we will create a folder with any desired name and open a terminal in that folder and run the command flutter create hello_world. This command will create a flutter project with the name hello_world inside that folder. And to run this project we go inside the project folder with the command cd hello_world and run the command flutter run. This command will execute our hello_world project and open that in a new window. Here you will see a counter app, which is always the demo app of flutter. And if you want to edit the code you can always open the hello_world folder with the IDE of your choice." }, { "code": null, "e": 5920, "s": 5812, "text": "With this, we are all ready to have a deep dive in the world of flutter and make some amazing applications!" }, { "code": null, "e": 5937, "s": 5920, "text": "khushboogoyal499" }, { "code": null, "e": 5944, "s": 5937, "text": "Picked" }, { "code": null, "e": 5949, "s": 5944, "text": "Dart" }, { "code": null, "e": 5957, "s": 5949, "text": "Flutter" }, { "code": null, "e": 6055, "s": 5957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6094, "s": 6055, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6120, "s": 6094, "text": "ListView Class in Flutter" }, { "code": null, "e": 6141, "s": 6120, "text": "Flutter - Search Bar" }, { "code": null, "e": 6172, "s": 6141, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 6190, "s": 6172, "text": "Flutter - Dialogs" }, { "code": null, "e": 6229, "s": 6190, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6246, "s": 6229, "text": "Flutter Tutorial" }, { "code": null, "e": 6267, "s": 6246, "text": "Flutter - Search Bar" }, { "code": null, "e": 6298, "s": 6267, "text": "Flutter - FutureBuilder Widget" } ]
What does enumerable property mean in JavaScript?
04 Jun, 2020 An enumerable property in JavaScript means that a property can be viewed if it is iterated using the for...in loop or Object.keys() method. All the properties which are created by simple assignment or property initializer are enumerable by default. Example 1: <script>// Creating a student objectconst student = { registration: '12342', name: 'Sandeep', age: 27, marks: 98}; // prints all the keys in student objectfor (const key in student) { console.log(key);}</script> Output: registration name age marks Example 2: Since all the properties are initialized by property initializer, they all have enumerable set to true by default. To explicitly change the internal enumerable attribute of a property, the Object.defineProperty() method is used. Also, to check whether a property is enumerable or not, we use the function propertyIsEnumerable(). It returns true if the property is enumerable or false otherwise. <script>// Creating a student objectconst student = { registration: '12342', name: 'Sandeep', age: 27,}; // This sets the enumerable attribute// of marks property to false Object.defineProperty(student, 'marks', { value: 98, configurable: true, writable: false, enumerable: false,}); // To print whether enumerable or notconsole.log(student.propertyIsEnumerable('registration')); console.log(student.propertyIsEnumerable('name'));console.log(student.propertyIsEnumerable('age'));console.log(student.propertyIsEnumerable('marks'));</script> Output: true true true false Note: Properties that are created using the defineProperty() method have enumerable flag set to false. When the same above code is run using a for loop, the “marks” property is not visible. // This will not print the property // Who's enumerable property is set to false for (const key in student){ console.log(key) } Output: registration name age javascript-basics Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Node.js | fs.writeFileSync() Method Remove elements from a JavaScript Array How do you run JavaScript script through the Terminal? How to insert spaces/tabs in text using HTML/CSS? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jun, 2020" }, { "code": null, "e": 277, "s": 28, "text": "An enumerable property in JavaScript means that a property can be viewed if it is iterated using the for...in loop or Object.keys() method. All the properties which are created by simple assignment or property initializer are enumerable by default." }, { "code": null, "e": 288, "s": 277, "text": "Example 1:" }, { "code": "<script>// Creating a student objectconst student = { registration: '12342', name: 'Sandeep', age: 27, marks: 98}; // prints all the keys in student objectfor (const key in student) { console.log(key);}</script>", "e": 516, "s": 288, "text": null }, { "code": null, "e": 524, "s": 516, "text": "Output:" }, { "code": null, "e": 553, "s": 524, "text": "registration\nname\nage\nmarks\n" }, { "code": null, "e": 959, "s": 553, "text": "Example 2: Since all the properties are initialized by property initializer, they all have enumerable set to true by default. To explicitly change the internal enumerable attribute of a property, the Object.defineProperty() method is used. Also, to check whether a property is enumerable or not, we use the function propertyIsEnumerable(). It returns true if the property is enumerable or false otherwise." }, { "code": "<script>// Creating a student objectconst student = { registration: '12342', name: 'Sandeep', age: 27,}; // This sets the enumerable attribute// of marks property to false Object.defineProperty(student, 'marks', { value: 98, configurable: true, writable: false, enumerable: false,}); // To print whether enumerable or notconsole.log(student.propertyIsEnumerable('registration')); console.log(student.propertyIsEnumerable('name'));console.log(student.propertyIsEnumerable('age'));console.log(student.propertyIsEnumerable('marks'));</script>", "e": 1524, "s": 959, "text": null }, { "code": null, "e": 1532, "s": 1524, "text": "Output:" }, { "code": null, "e": 1554, "s": 1532, "text": "true\ntrue\ntrue\nfalse\n" }, { "code": null, "e": 1744, "s": 1554, "text": "Note: Properties that are created using the defineProperty() method have enumerable flag set to false. When the same above code is run using a for loop, the “marks” property is not visible." }, { "code": null, "e": 1879, "s": 1744, "text": "// This will not print the property \n// Who's enumerable property is set to false\n\nfor (const key in student){\n console.log(key)\n}\n" }, { "code": null, "e": 1887, "s": 1879, "text": "Output:" }, { "code": null, "e": 1910, "s": 1887, "text": "registration\nname\nage\n" }, { "code": null, "e": 1928, "s": 1910, "text": "javascript-basics" }, { "code": null, "e": 1935, "s": 1928, "text": "Picked" }, { "code": null, "e": 1946, "s": 1935, "text": "JavaScript" }, { "code": null, "e": 1963, "s": 1946, "text": "Web Technologies" }, { "code": null, "e": 1990, "s": 1963, "text": "Web technologies Questions" }, { "code": null, "e": 2088, "s": 1990, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2149, "s": 2088, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2221, "s": 2149, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2257, "s": 2221, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 2297, "s": 2257, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2352, "s": 2297, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 2402, "s": 2352, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2435, "s": 2402, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2497, "s": 2435, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2530, "s": 2497, "text": "Node.js fs.readFileSync() Method" } ]
How to rearrange columns of a 2D NumPy array using given index positions?
05 Sep, 2020 In this article, we will learn how to rearrange columns of a given numpy array using given index positions. Here the columns are rearranged with the given indexes. For this, we can simply store the columns values in lists and arrange these according to the given index list but this approach is very costly. So, using by using the concept of numpy array this can be easily done in minimum time. Arr = [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]] and i = [2, 4, 0, 3, 1]then output is [[3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2]]. Here, i[0] = 2 i.e; 3rd column so output = [[3],[3],[3],][3],[3]]. i[1] = 4 i.e; 5th column so output = [[3,5],[3,5],[3,5],][3,5],[3,5]]. i[2] = 0 i.e; 1st column so output = [[3,5,1],[3,5,1],[3,5,1],][3,5,1],[3,5,1]]. i[3] = 3 i.e; 4th column so output = [[3,5,1,4],[3,5,1,4],[3,5,1,4],][3,5,1,4],[3,5,1,4]]. i[4] = 1 i.e; 2nd column so output = [[3,5,1,4,2],[3,5,1,4,2],[3,5,1,4,2],][3,5,1,4,2],[3,5,1,4,2]]. Below is the implementation with an example : Python3 # importing packageimport numpy # create a numpy arrayarr = numpy.array([[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5] ]) # view arrayprint(arr) # declare index listi = [2,4,0,3,1] # create outputoutput = arr[:,i] # view outputprint(output) Output : [[1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5]] [[3 5 1 4 2] [3 5 1 4 2] [3 5 1 4 2] [3 5 1 4 2] [3 5 1 4 2]] Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 423, "s": 28, "text": "In this article, we will learn how to rearrange columns of a given numpy array using given index positions. Here the columns are rearranged with the given indexes. For this, we can simply store the columns values in lists and arrange these according to the given index list but this approach is very costly. So, using by using the concept of numpy array this can be easily done in minimum time." }, { "code": null, "e": 607, "s": 423, "text": "Arr = [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]] and i = [2, 4, 0, 3, 1]then output is [[3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2]]." }, { "code": null, "e": 1034, "s": 607, "text": "Here, i[0] = 2 i.e; 3rd column so output = [[3],[3],[3],][3],[3]]. i[1] = 4 i.e; 5th column so output = [[3,5],[3,5],[3,5],][3,5],[3,5]]. i[2] = 0 i.e; 1st column so output = [[3,5,1],[3,5,1],[3,5,1],][3,5,1],[3,5,1]]. i[3] = 3 i.e; 4th column so output = [[3,5,1,4],[3,5,1,4],[3,5,1,4],][3,5,1,4],[3,5,1,4]]. i[4] = 1 i.e; 2nd column so output = [[3,5,1,4,2],[3,5,1,4,2],[3,5,1,4,2],][3,5,1,4,2],[3,5,1,4,2]]." }, { "code": null, "e": 1080, "s": 1034, "text": "Below is the implementation with an example :" }, { "code": null, "e": 1088, "s": 1080, "text": "Python3" }, { "code": "# importing packageimport numpy # create a numpy arrayarr = numpy.array([[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5] ]) # view arrayprint(arr) # declare index listi = [2,4,0,3,1] # create outputoutput = arr[:,i] # view outputprint(output)", "e": 1442, "s": 1088, "text": null }, { "code": null, "e": 1451, "s": 1442, "text": "Output :" }, { "code": null, "e": 1584, "s": 1451, "text": "[[1 2 3 4 5]\n [1 2 3 4 5]\n [1 2 3 4 5]\n [1 2 3 4 5]\n [1 2 3 4 5]]\n[[3 5 1 4 2]\n [3 5 1 4 2]\n [3 5 1 4 2]\n [3 5 1 4 2]\n [3 5 1 4 2]]\n" }, { "code": null, "e": 1615, "s": 1584, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1628, "s": 1615, "text": "Python-numpy" }, { "code": null, "e": 1635, "s": 1628, "text": "Python" } ]
Sphenic Number
23 Jun, 2022 A Sphenic Number is a positive integer n which is product of exactly three distinct primes. The first few sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114, ... Given a number n, determine whether it is a Sphenic Number or not. Examples: Input : 30 Output : Yes Explanation : 30 is the smallest Sphenic number, 30 = 2 × 3 × 5 the product of the smallest three primes Input : 60 Output : No Explanation : 60 = 22 x 3 x 5 has exactly 3 prime factors but is not a sphenic number Sphenic number can be checked by fact that every sphenic number will have exactly 8 divisor SPHENIC NUMBER So first We will try to find if the number is having exactly 8 divisors if not then simply answer is no.If there are exactly 8 divisors then we will confirm weather the first 3 digits after 1 are prime or not. Eg. 30 (sphenic number) 30=p*q*r(i.e p,q and r are three distinct prime no and their product are 30) the set of divisor is (1,2,3,5,6,10,15,30). Below is the implementation of the idea. C++ Java Python3 C# Javascript // C++ program to check whether a number is a// Sphenic number or not#include<bits/stdc++.h>using namespace std;//create a global array of size 10001;bool arr[1001];// This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.void simpleSieve(){ // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. memset(arr,true,sizeof(arr)); // One by one traverse all numbers so that their // multiples can be marked as composite. for(int p=2;p*p<1001;p++) { // If p is not changed, then it is a prime if(arr[p]) {// Update all multiples of p for(int i=p*2;i<1001;i=i+p) arr[i]=false; } }}int find_sphene(int N){ int arr1[8]={0}; //to store the 8 divisors int count=0; //to count the number of divisor int j=0; for(int i=1;i<=N;i++) { if(N%i==0 &&count<9) { count++; arr1[j++]=i; } } //finally check if there re 8 divisor and all the numbers are distinct prime no return 1 //else return 0 if(count==8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0;} // Driver program to test above functionint main(){ int n = 60; simpleSieve(); int ans=find_sphene(n); if(ans) cout<<"Yes"; else cout<<"NO";} // Java program to check whether a number is a// Sphenic number or notimport java.util.*; class GFG{ // create a global array of size 10001;static boolean []arr = new boolean[1001]; // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.static void simpleSieve(){ // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. Arrays.fill(arr, true); // One by one traverse all numbers so that their // multiples can be marked as composite. for(int p = 2; p * p < 1001; p++) { // If p is not changed, then it is a prime if(arr[p]) { // Update all multiples of p for(int i = p * 2; i < 1001; i = i + p) arr[i] = false; } }}static int find_sphene(int N){ int []arr1 = new int[8]; // to store the 8 divisors int count = 0; // to count the number of divisor int j = 0; for(int i = 1; i <= N; i++) { if(N % i == 0 && count < 8) { count++; arr1[j++] = i; } } // finally check if there re 8 divisor and // all the numbers are distinct prime no return 1 // else return 0); if(count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0;} // Driver codepublic static void main(String[] args){ int n = 60; simpleSieve(); int ans = find_sphene(n); if(ans == 1) System.out.print("Yes"); else System.out.print("NO");}} // This code is contributed by aashish1995 # Python3 program to check whether a number# is a Sphenic number or not # Create a global array of size 1001;arr = [True] * (1001) # This functions finds all primes smaller# than 'limit' using simple sieve of# eratosthenes.def simpleSieve(): # Initialize all entries of it as # True. A value in mark[p] will # finally be False if 'p' is Not # a prime, else True. k = 0 # One by one traverse all numbers so # that their multiples can be marked # as composite. for p in range(2, 1001): if (p * p > 1001): break # If p is not changed, then it is a prime if (arr[p]): # Update all multiples of p for k in range(p, 1001, k + p): arr[k] = False def find_sphene(N): # To store the 8 divisors arr1 = [0] * (8) # To count the number of divisor count = 0 j = 0 for i in range(1, N + 1): if (N % i == 0 and count < 8): count += 1 arr1[j] = i j += 1 # Finally check if there re 8 divisor and # all the numbers are distinct prime no return 1 # else return 0); if (count == 8 and (arr[arr1[1]] and arr[arr1[2]] and arr[arr1[3]])): return 1; return 0; # Driver codeif __name__ == '__main__': n = 60 simpleSieve() ans = find_sphene(n) if (ans == 1): print("Yes") else: print("NO") # This code is contributed by gauravrajput1 // C# program to check whether a number// is a Sphenic number or notusing System; class GFG{ // Create a global array of size 10001;static bool []arr = new bool[1001]; // This functions finds all primes smaller than// 'limit'. Using simple sieve of eratosthenes.static void simpleSieve(){ // Initialize all entries of it as true. // A value in mark[p] will finally be // false if 'p' is Not a prime, else true. for(int i = 0;i<1001;i++) arr[i] = true; // One by one traverse all numbers so // that their multiples can be marked // as composite. for(int p = 2; p * p < 1001; p++) { // If p is not changed, then it // is a prime if (arr[p]) { // Update all multiples of p for(int i = p * 2; i < 1001; i = i + p) arr[i] = false; } }} static int find_sphene(int N){ // To store the 8 divisors int []arr1 = new int[8]; // To count the number of divisor int count = 0; int j = 0; for(int i = 1; i <= N; i++) { if (N % i == 0 && count < 8) { count++; arr1[j++] = i; } } // Finally check if there re 8 divisor // and all the numbers are distinct prime // no return 1 else return 0); if (count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0;} // Driver codepublic static void Main(String[] args){ int n = 60; simpleSieve(); int ans = find_sphene(n); if (ans == 1) Console.Write("Yes"); else Console.Write("NO");}} // This code is contributed by aashish1995 <script>// javascript program to check whether a number is a// Sphenic number or not // create a global array of size 10001; // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. let arr = Array(1001).fill(true); // This functions finds all primes smaller than 'limit' // using simple sieve of eratosthenes. function simpleSieve() { // One by one traverse all numbers so that their // multiples can be marked as composite. for (let p = 2; p * p < 1001; p++) { // If p is not changed, then it is a prime if (arr[p]) { // Update all multiples of p for (let i = p * 2; i < 1001; i = i + p) arr[i] = false; } } } function find_sphene(N) { var arr1 = Array(8).fill(0); // to store the 8 divisors var count = 0; // to count the number of divisor var j = 0; for (let i = 1; i <= N; i++) { if (N % i == 0 && count < 8) { count++; arr1[j++] = i; } } // finally check if there re 8 divisor and // all the numbers are distinct prime no return 1 // else return 0); if (count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0; } // Driver code var n = 60; simpleSieve(); var ans = find_sphene(n); if (ans == 1) document.write("Yes"); else document.write("NO"); // This code is contributed by aashish1995</script> Output: NO Time Complexity: O(√p log p) Auxiliary Space: O(n) References: 1. OEIS 2. https://en.wikipedia.org/wiki/Sphenic_number This article is contributed by Aarti_Rathi and mra11145. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Mohammedansari1111145 aashish1995 GauravRajput1 codewithshinchan Prime Number prime-factor sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Modulo Operator (%) in C/C++ with Examples Program for Decimal to Binary Conversion
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 290, "s": 52, "text": "A Sphenic Number is a positive integer n which is product of exactly three distinct primes. The first few sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114, ... Given a number n, determine whether it is a Sphenic Number or not. " }, { "code": null, "e": 301, "s": 290, "text": "Examples: " }, { "code": null, "e": 592, "s": 301, "text": "Input : 30\nOutput : Yes\nExplanation : 30 is the smallest Sphenic number, \n 30 = 2 × 3 × 5 \n the product of the smallest three primes\n\nInput : 60\nOutput : No\nExplanation : 60 = 22 x 3 x 5\n has exactly 3 prime factors but\n is not a sphenic number" }, { "code": null, "e": 1054, "s": 592, "text": "Sphenic number can be checked by fact that every sphenic number will have exactly 8 divisor SPHENIC NUMBER So first We will try to find if the number is having exactly 8 divisors if not then simply answer is no.If there are exactly 8 divisors then we will confirm weather the first 3 digits after 1 are prime or not. Eg. 30 (sphenic number) 30=p*q*r(i.e p,q and r are three distinct prime no and their product are 30) the set of divisor is (1,2,3,5,6,10,15,30)." }, { "code": null, "e": 1096, "s": 1054, "text": "Below is the implementation of the idea. " }, { "code": null, "e": 1100, "s": 1096, "text": "C++" }, { "code": null, "e": 1105, "s": 1100, "text": "Java" }, { "code": null, "e": 1113, "s": 1105, "text": "Python3" }, { "code": null, "e": 1116, "s": 1113, "text": "C#" }, { "code": null, "e": 1127, "s": 1116, "text": "Javascript" }, { "code": "// C++ program to check whether a number is a// Sphenic number or not#include<bits/stdc++.h>using namespace std;//create a global array of size 10001;bool arr[1001];// This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.void simpleSieve(){ // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. memset(arr,true,sizeof(arr)); // One by one traverse all numbers so that their // multiples can be marked as composite. for(int p=2;p*p<1001;p++) { // If p is not changed, then it is a prime if(arr[p]) {// Update all multiples of p for(int i=p*2;i<1001;i=i+p) arr[i]=false; } }}int find_sphene(int N){ int arr1[8]={0}; //to store the 8 divisors int count=0; //to count the number of divisor int j=0; for(int i=1;i<=N;i++) { if(N%i==0 &&count<9) { count++; arr1[j++]=i; } } //finally check if there re 8 divisor and all the numbers are distinct prime no return 1 //else return 0 if(count==8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0;} // Driver program to test above functionint main(){ int n = 60; simpleSieve(); int ans=find_sphene(n); if(ans) cout<<\"Yes\"; else cout<<\"NO\";}", "e": 2527, "s": 1127, "text": null }, { "code": "// Java program to check whether a number is a// Sphenic number or notimport java.util.*; class GFG{ // create a global array of size 10001;static boolean []arr = new boolean[1001]; // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.static void simpleSieve(){ // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. Arrays.fill(arr, true); // One by one traverse all numbers so that their // multiples can be marked as composite. for(int p = 2; p * p < 1001; p++) { // If p is not changed, then it is a prime if(arr[p]) { // Update all multiples of p for(int i = p * 2; i < 1001; i = i + p) arr[i] = false; } }}static int find_sphene(int N){ int []arr1 = new int[8]; // to store the 8 divisors int count = 0; // to count the number of divisor int j = 0; for(int i = 1; i <= N; i++) { if(N % i == 0 && count < 8) { count++; arr1[j++] = i; } } // finally check if there re 8 divisor and // all the numbers are distinct prime no return 1 // else return 0); if(count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0;} // Driver codepublic static void main(String[] args){ int n = 60; simpleSieve(); int ans = find_sphene(n); if(ans == 1) System.out.print(\"Yes\"); else System.out.print(\"NO\");}} // This code is contributed by aashish1995", "e": 4150, "s": 2527, "text": null }, { "code": "# Python3 program to check whether a number# is a Sphenic number or not # Create a global array of size 1001;arr = [True] * (1001) # This functions finds all primes smaller# than 'limit' using simple sieve of# eratosthenes.def simpleSieve(): # Initialize all entries of it as # True. A value in mark[p] will # finally be False if 'p' is Not # a prime, else True. k = 0 # One by one traverse all numbers so # that their multiples can be marked # as composite. for p in range(2, 1001): if (p * p > 1001): break # If p is not changed, then it is a prime if (arr[p]): # Update all multiples of p for k in range(p, 1001, k + p): arr[k] = False def find_sphene(N): # To store the 8 divisors arr1 = [0] * (8) # To count the number of divisor count = 0 j = 0 for i in range(1, N + 1): if (N % i == 0 and count < 8): count += 1 arr1[j] = i j += 1 # Finally check if there re 8 divisor and # all the numbers are distinct prime no return 1 # else return 0); if (count == 8 and (arr[arr1[1]] and arr[arr1[2]] and arr[arr1[3]])): return 1; return 0; # Driver codeif __name__ == '__main__': n = 60 simpleSieve() ans = find_sphene(n) if (ans == 1): print(\"Yes\") else: print(\"NO\") # This code is contributed by gauravrajput1", "e": 5637, "s": 4150, "text": null }, { "code": "// C# program to check whether a number// is a Sphenic number or notusing System; class GFG{ // Create a global array of size 10001;static bool []arr = new bool[1001]; // This functions finds all primes smaller than// 'limit'. Using simple sieve of eratosthenes.static void simpleSieve(){ // Initialize all entries of it as true. // A value in mark[p] will finally be // false if 'p' is Not a prime, else true. for(int i = 0;i<1001;i++) arr[i] = true; // One by one traverse all numbers so // that their multiples can be marked // as composite. for(int p = 2; p * p < 1001; p++) { // If p is not changed, then it // is a prime if (arr[p]) { // Update all multiples of p for(int i = p * 2; i < 1001; i = i + p) arr[i] = false; } }} static int find_sphene(int N){ // To store the 8 divisors int []arr1 = new int[8]; // To count the number of divisor int count = 0; int j = 0; for(int i = 1; i <= N; i++) { if (N % i == 0 && count < 8) { count++; arr1[j++] = i; } } // Finally check if there re 8 divisor // and all the numbers are distinct prime // no return 1 else return 0); if (count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0;} // Driver codepublic static void Main(String[] args){ int n = 60; simpleSieve(); int ans = find_sphene(n); if (ans == 1) Console.Write(\"Yes\"); else Console.Write(\"NO\");}} // This code is contributed by aashish1995", "e": 7333, "s": 5637, "text": null }, { "code": "<script>// javascript program to check whether a number is a// Sphenic number or not // create a global array of size 10001; // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. let arr = Array(1001).fill(true); // This functions finds all primes smaller than 'limit' // using simple sieve of eratosthenes. function simpleSieve() { // One by one traverse all numbers so that their // multiples can be marked as composite. for (let p = 2; p * p < 1001; p++) { // If p is not changed, then it is a prime if (arr[p]) { // Update all multiples of p for (let i = p * 2; i < 1001; i = i + p) arr[i] = false; } } } function find_sphene(N) { var arr1 = Array(8).fill(0); // to store the 8 divisors var count = 0; // to count the number of divisor var j = 0; for (let i = 1; i <= N; i++) { if (N % i == 0 && count < 8) { count++; arr1[j++] = i; } } // finally check if there re 8 divisor and // all the numbers are distinct prime no return 1 // else return 0); if (count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]])) return 1; return 0; } // Driver code var n = 60; simpleSieve(); var ans = find_sphene(n); if (ans == 1) document.write(\"Yes\"); else document.write(\"NO\"); // This code is contributed by aashish1995</script>", "e": 8964, "s": 7333, "text": null }, { "code": null, "e": 8973, "s": 8964, "text": "Output: " }, { "code": null, "e": 8976, "s": 8973, "text": "NO" }, { "code": null, "e": 9027, "s": 8976, "text": "Time Complexity: O(√p log p) Auxiliary Space: O(n)" }, { "code": null, "e": 9095, "s": 9027, "text": "References: 1. OEIS 2. https://en.wikipedia.org/wiki/Sphenic_number" }, { "code": null, "e": 9404, "s": 9095, "text": "This article is contributed by Aarti_Rathi and mra11145. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 9426, "s": 9404, "text": "Mohammedansari1111145" }, { "code": null, "e": 9438, "s": 9426, "text": "aashish1995" }, { "code": null, "e": 9452, "s": 9438, "text": "GauravRajput1" }, { "code": null, "e": 9469, "s": 9452, "text": "codewithshinchan" }, { "code": null, "e": 9482, "s": 9469, "text": "Prime Number" }, { "code": null, "e": 9495, "s": 9482, "text": "prime-factor" }, { "code": null, "e": 9501, "s": 9495, "text": "sieve" }, { "code": null, "e": 9514, "s": 9501, "text": "Mathematical" }, { "code": null, "e": 9527, "s": 9514, "text": "Mathematical" }, { "code": null, "e": 9540, "s": 9527, "text": "Prime Number" }, { "code": null, "e": 9546, "s": 9540, "text": "sieve" }, { "code": null, "e": 9644, "s": 9546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9668, "s": 9644, "text": "Merge two sorted arrays" }, { "code": null, "e": 9689, "s": 9668, "text": "Operators in C / C++" }, { "code": null, "e": 9703, "s": 9689, "text": "Prime Numbers" }, { "code": null, "e": 9756, "s": 9703, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 9793, "s": 9756, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9825, "s": 9793, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9852, "s": 9825, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 9895, "s": 9852, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9938, "s": 9895, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Difference between Array and Pointers in C.
Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.r Benefit of using pointer for array is two folds, first, we store the address of dynamically allocated array to the pointer and second, to pass the array to a function. Following are the differences in using array and using pointer to array. sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int. sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int. assignment array variable cannot be assigned address of another variable but pointer can take it. assignment array variable cannot be assigned address of another variable but pointer can take it. first value first indexed value is same as value of pointer. For example, array[0] == *p. first value first indexed value is same as value of pointer. For example, array[0] == *p. iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2) iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2) Live Demo #include <stdio.h> void printElement(char* q, int index){ printf("Element at index(%d) is: %c\n", index, *(q+index)); } int main() { char arr[] = {'A', 'B', 'C'}; char* p = arr; printf("Size of arr[]: %d\n", sizeof(arr)); printf("Size of p: %d\n", sizeof(p)); printf("First element using arr is: %c\n", arr[0]); printf("First element using p is: %c\n", *p); printf("Second element using arr is: %c\n", arr[1]); printf("Second element using p is: %c\n", *(p+1)); printElement(p, 2); return 0; } Size of arr[]: 3 Size of p: 8 First element using arr is: A First element using p is: A Second element using arr is: B Second element using p is: B Element at index(2) is: C
[ { "code": null, "e": 1678, "s": 1187, "text": "Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.r Benefit of using pointer for array is two folds, first, we store the address of dynamically allocated array to the pointer and second, to pass the array to a function. Following are the differences in using array and using pointer to array." }, { "code": null, "e": 1789, "s": 1678, "text": "sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int." }, { "code": null, "e": 1900, "s": 1789, "text": "sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int." }, { "code": null, "e": 1998, "s": 1900, "text": "assignment array variable cannot be assigned address of another variable but pointer can take it." }, { "code": null, "e": 2096, "s": 1998, "text": "assignment array variable cannot be assigned address of another variable but pointer can take it." }, { "code": null, "e": 2186, "s": 2096, "text": "first value first indexed value is same as value of pointer. For example, array[0] == *p." }, { "code": null, "e": 2276, "s": 2186, "text": "first value first indexed value is same as value of pointer. For example, array[0] == *p." }, { "code": null, "e": 2445, "s": 2276, "text": "iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2)" }, { "code": null, "e": 2614, "s": 2445, "text": "iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2)" }, { "code": null, "e": 2625, "s": 2614, "text": " Live Demo" }, { "code": null, "e": 3152, "s": 2625, "text": "#include <stdio.h>\nvoid printElement(char* q, int index){\n printf(\"Element at index(%d) is: %c\\n\", index, *(q+index));\n}\nint main() {\n char arr[] = {'A', 'B', 'C'};\n char* p = arr;\n printf(\"Size of arr[]: %d\\n\", sizeof(arr));\n printf(\"Size of p: %d\\n\", sizeof(p));\n printf(\"First element using arr is: %c\\n\", arr[0]);\n printf(\"First element using p is: %c\\n\", *p);\n printf(\"Second element using arr is: %c\\n\", arr[1]);\n printf(\"Second element using p is: %c\\n\", *(p+1));\n printElement(p, 2);\n return 0;\n}" }, { "code": null, "e": 3326, "s": 3152, "text": "Size of arr[]: 3\nSize of p: 8\nFirst element using arr is: A\nFirst element using p is: A\nSecond element using arr is: B\nSecond element using p is: B\nElement at index(2) is: C" } ]
Create and save animated GIF with Python – Pillow
24 Feb, 2021 Prerequisites: pillow In this article, we are going to use a pillow library to create and save gifs. GIFs: The Graphics Interchange Format(gif) is a bitmap image format that was developed by a team at the online services provider CompuServe led by American computer scientist Steve Wilhite on 15 June 1987. A GIF file normally stores a single image, but the format allows multiple images to be stored in one file. The format also has parameters that can be used to sequence the images to display each image for a short time then replace it with the next one. In simple words, GIF is a moving image. Pillow: Pillow is used for image processing in python. Pillow was developed on top of PIL(python image library). PIL was not supported in python 3, so we use a pillow. This module is not preloaded with Python. So to install it execute the following command in the command-line: pip install pillow Let’s create a gif in step wise: Step 1: First we import our requirements for PIL module. Python3 from PIL import Image, ImageDraw Step 2: Create a list after we enter the values of the circle. (0,255,0) it is the color code of green and (255,0,0) is the color code of red. Python3 images = []width = 200center = width // 2color_1 = (0,255, 0)color_2 = (255, 0, 0)max_radius = int(center * 1.5)step = 8 Step 3: For loop was used to create an animation image.2nd line of code used to set values of the square, that square contains red color and it’s edge size is 200.3rd line used to create square image .4th line used to draw a circle in that square image, that circle color is green. Python3 for i in range(0, max_radius, step): im = Image.new('RGB', (width, width), color_2) draw = ImageDraw.Draw(im) draw.ellipse((center - i, center - i, center + i, center + i), fill=color_1) images.append(im) Step 4: Save the gif image. Python3 images[0].save('pillow_imagedraw.gif', save_all = True, append_images = images[1:], optimize = False, duration = 10) Below is the full implementation: Python3 from PIL import Image, ImageDraw images = [] width = 200center = width // 2color_1 = (0,255, 0)color_2 = (255, 0, 0)max_radius = int(center * 1.5)step = 8 for i in range(0, max_radius, step): im = Image.new('RGB', (width, width), color_2) draw = ImageDraw.Draw(im) draw.ellipse((center - i, center - i, center + i, center + i), fill = color_1) images.append(im) images[0].save('pillow_imagedraw.gif', save_all = True, append_images = images[1:], optimize = False, duration = 10) Output: Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisites: pillow" }, { "code": null, "e": 129, "s": 50, "text": "In this article, we are going to use a pillow library to create and save gifs." }, { "code": null, "e": 335, "s": 129, "text": "GIFs: The Graphics Interchange Format(gif) is a bitmap image format that was developed by a team at the online services provider CompuServe led by American computer scientist Steve Wilhite on 15 June 1987." }, { "code": null, "e": 627, "s": 335, "text": "A GIF file normally stores a single image, but the format allows multiple images to be stored in one file. The format also has parameters that can be used to sequence the images to display each image for a short time then replace it with the next one. In simple words, GIF is a moving image." }, { "code": null, "e": 796, "s": 627, "text": "Pillow: Pillow is used for image processing in python. Pillow was developed on top of PIL(python image library). PIL was not supported in python 3, so we use a pillow. " }, { "code": null, "e": 906, "s": 796, "text": "This module is not preloaded with Python. So to install it execute the following command in the command-line:" }, { "code": null, "e": 925, "s": 906, "text": "pip install pillow" }, { "code": null, "e": 958, "s": 925, "text": "Let’s create a gif in step wise:" }, { "code": null, "e": 1015, "s": 958, "text": "Step 1: First we import our requirements for PIL module." }, { "code": null, "e": 1023, "s": 1015, "text": "Python3" }, { "code": "from PIL import Image, ImageDraw", "e": 1056, "s": 1023, "text": null }, { "code": null, "e": 1199, "s": 1056, "text": "Step 2: Create a list after we enter the values of the circle. (0,255,0) it is the color code of green and (255,0,0) is the color code of red." }, { "code": null, "e": 1207, "s": 1199, "text": "Python3" }, { "code": "images = []width = 200center = width // 2color_1 = (0,255, 0)color_2 = (255, 0, 0)max_radius = int(center * 1.5)step = 8", "e": 1328, "s": 1207, "text": null }, { "code": null, "e": 1610, "s": 1328, "text": "Step 3: For loop was used to create an animation image.2nd line of code used to set values of the square, that square contains red color and it’s edge size is 200.3rd line used to create square image .4th line used to draw a circle in that square image, that circle color is green." }, { "code": null, "e": 1618, "s": 1610, "text": "Python3" }, { "code": "for i in range(0, max_radius, step): im = Image.new('RGB', (width, width), color_2) draw = ImageDraw.Draw(im) draw.ellipse((center - i, center - i, center + i, center + i), fill=color_1) images.append(im)", "e": 1869, "s": 1618, "text": null }, { "code": null, "e": 1897, "s": 1869, "text": "Step 4: Save the gif image." }, { "code": null, "e": 1905, "s": 1897, "text": "Python3" }, { "code": "images[0].save('pillow_imagedraw.gif', save_all = True, append_images = images[1:], optimize = False, duration = 10)", "e": 2050, "s": 1905, "text": null }, { "code": null, "e": 2084, "s": 2050, "text": "Below is the full implementation:" }, { "code": null, "e": 2092, "s": 2084, "text": "Python3" }, { "code": "from PIL import Image, ImageDraw images = [] width = 200center = width // 2color_1 = (0,255, 0)color_2 = (255, 0, 0)max_radius = int(center * 1.5)step = 8 for i in range(0, max_radius, step): im = Image.new('RGB', (width, width), color_2) draw = ImageDraw.Draw(im) draw.ellipse((center - i, center - i, center + i, center + i), fill = color_1) images.append(im) images[0].save('pillow_imagedraw.gif', save_all = True, append_images = images[1:], optimize = False, duration = 10)", "e": 2649, "s": 2092, "text": null }, { "code": null, "e": 2659, "s": 2649, "text": " Output:" }, { "code": null, "e": 2666, "s": 2659, "text": "Picked" }, { "code": null, "e": 2677, "s": 2666, "text": "Python-pil" }, { "code": null, "e": 2684, "s": 2677, "text": "Python" } ]
How to create multiple subplots in Matplotlib in Python?
16 Dec, 2020 To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid. By default, it returns a figure with a single plot. For each axes object i.e plot we can set title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()). Let’s see how this works When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots.We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots. We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding Example 1: 1-D array of subplots Python3 # importing libraryimport matplotlib.pyplot as plt # Some data to displayx = [1, 2, 3]y = [0, 1, 0]z = [1, 0, 1] # Creating 2 subplotsfig, ax = plt.subplots(2) # Accessing each axes object to plot the data through returned arrayax[0].plot(x, y)ax[1].plot(x, z) Output : subplots_fig1 Example2: Stacking in two directions returns a 2D array of axes objects. Python3 # importing libraryimport matplotlib.pyplot as pltimport numpy as np # Data for plottingx = np.arange(0.0, 2.0, 0.01)y = 1 + np.sin(2 * np.pi * x) # Creating 6 subplots and unpacking the output array immediatelyfig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)ax1.plot(x, y, color="orange")ax2.plot(x, y, color="green")ax3.plot(x, y, color="blue")ax4.plot(x, y, color="magenta")ax5.plot(x, y, color="black")ax6.plot(x, y, color="red") Output : Subplots_fig2 tejalkadam18m Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2020" }, { "code": null, "e": 271, "s": 28, "text": "To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid." }, { "code": null, "e": 465, "s": 271, "text": "By default, it returns a figure with a single plot. For each axes object i.e plot we can set title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel())." }, { "code": null, "e": 492, "s": 465, "text": "Let’s see how this works " }, { "code": null, "e": 857, "s": 492, "text": "When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots.We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding" }, { "code": null, "e": 977, "s": 857, "text": "When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots." }, { "code": null, "e": 1223, "s": 977, "text": "We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding" }, { "code": null, "e": 1256, "s": 1223, "text": "Example 1: 1-D array of subplots" }, { "code": null, "e": 1264, "s": 1256, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # Some data to displayx = [1, 2, 3]y = [0, 1, 0]z = [1, 0, 1] # Creating 2 subplotsfig, ax = plt.subplots(2) # Accessing each axes object to plot the data through returned arrayax[0].plot(x, y)ax[1].plot(x, z)", "e": 1525, "s": 1264, "text": null }, { "code": null, "e": 1535, "s": 1525, "text": "Output : " }, { "code": null, "e": 1549, "s": 1535, "text": "subplots_fig1" }, { "code": null, "e": 1622, "s": 1549, "text": "Example2: Stacking in two directions returns a 2D array of axes objects." }, { "code": null, "e": 1630, "s": 1622, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as pltimport numpy as np # Data for plottingx = np.arange(0.0, 2.0, 0.01)y = 1 + np.sin(2 * np.pi * x) # Creating 6 subplots and unpacking the output array immediatelyfig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)ax1.plot(x, y, color=\"orange\")ax2.plot(x, y, color=\"green\")ax3.plot(x, y, color=\"blue\")ax4.plot(x, y, color=\"magenta\")ax5.plot(x, y, color=\"black\")ax6.plot(x, y, color=\"red\")", "e": 2078, "s": 1630, "text": null }, { "code": null, "e": 2088, "s": 2078, "text": "Output : " }, { "code": null, "e": 2102, "s": 2088, "text": "Subplots_fig2" }, { "code": null, "e": 2116, "s": 2102, "text": "tejalkadam18m" }, { "code": null, "e": 2134, "s": 2116, "text": "Python-matplotlib" }, { "code": null, "e": 2141, "s": 2134, "text": "Python" } ]
Count of subsequence of an Array having all unique digits
30 Nov, 2021 Given an array A containing N positive integers, the task is to find the number of subsequences of this array such that in each subsequence , no digit is repeated twice, i.e. all the digits of the subsequences must be unique.Examples: Input: A = [1, 12, 23, 34] Output: 7 The subsequences are: {1}, {12}, {23}, {34}, {1, 23}, {1, 34}, {12, 34} Therefore the count of such subsequences = 7 Input: A = [5, 12, 2, 1, 165, 2323, 7] Output: 33 Naive approach: Generate all subsequences of the array and traverse through them to check whether the given condition is satisfied or not. Print the count of such subsequences at the end. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the count// of subsequences of an Array// having all unique digits #include <bits/stdc++.h>using namespace std; // Function to check whether// the subsequences has all unique digitsbool check(vector<int>& v){ // Storing all digits occurred set<int> digits; // Traversing all the numbers of v for (int i = 0; i < v.size(); i++) { // Storing all digits of v[i] set<int> d; while (v[i]) { d.insert(v[i] % 10); v[i] /= 10; } // Checking whether digits of v[i] // have already occurred for (auto it : d) { if (digits.count(it)) return false; } // Inserting digits of v[i] in the set for (auto it : d) digits.insert(it); } return true;} // Function to count the number// subarray with all digits uniqueint numberOfSubarrays(int a[], int n){ int answer = 0; // Traverse through all the subarrays for (int i = 1; i < (1 << n); i++) { // To store elements of this subarray vector<int> temp; // Generate all subarray // and store it in vector for (int j = 0; j < n; j++) { if (i & (1 << j)) temp.push_back(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver codeint main(){ int N = 4; int A[] = { 1, 12, 23, 34 }; cout << numberOfSubarrays(A, N); return 0;} // Java program to find the count// of subarrays of an Array// having all unique digits import java.util.*; class GFG{ // Function to check whether// the subarray has all unique digitsstatic boolean check(Vector<Integer> v){ // Storing all digits occurred HashSet<Integer> digits = new HashSet<Integer>(); // Traversing all the numbers of v for (int i = 0; i < v.size(); i++) { // Storing all digits of v[i] HashSet<Integer> d = new HashSet<Integer>(); while (v.get(i)>0) { d.add(v.get(i) % 10); v.set(i, v.get(i)/10); } // Checking whether digits of v[i] // have already occurred for (int it : d) { if (digits.contains(it)) return false; } // Inserting digits of v[i] in the set for (int it : d) digits.add(it); } return true;} // Function to count the number// subarray with all digits uniquestatic int numberOfSubarrays(int a[], int n){ int answer = 0; // Traverse through all the subarrays for (int i = 1; i < (1 << n); i++) { // To store elements of this subarray Vector<Integer> temp = new Vector<Integer>(); // Generate all subarray // and store it in vector for (int j = 0; j < n; j++) { if ((i & (1 << j))>0) temp.add(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver codepublic static void main(String[] args){ int N = 4; int A[] = { 1, 12, 23, 34 }; System.out.print(numberOfSubarrays(A, N));}} // This code is contributed by 29AjayKumar # Python3 program to find the count# of subarrays of an Array# having all unique digits # Function to check whether# the subarray has all unique digitsdef check(v): # Storing all digits occurred digits = set() # Traversing all the numbers of v for i in range(len(v)): # Storing all digits of v[i] d = set() while (v[i] != 0): d.add(v[i] % 10) v[i] //= 10 # Checking whether digits of v[i] # have already occurred for it in d: if it in digits: return False # Inserting digits of v[i] in the set for it in d: digits.add(it) return True # Function to count the number# subarray with all digits uniquedef numberOfSubarrays(a, n): answer = 0 # Traverse through all the subarrays for i in range(1, 1 << n): # To store elements of this subarray temp = [] # Generate all subarray # and store it in vector for j in range(n): if (i & (1 << j)): temp.append(a[j]) # Check whether this subarray # has all digits unique if (check(temp)): # Increase the count answer += 1 # Return the count return answer # Driver codeif __name__=="__main__": N = 4 A = [ 1, 12, 23, 34 ] print(numberOfSubarrays(A, N)) # This code is contributed by rutvik_56 // C# program to find the count// of subarrays of an Array// having all unique digitsusing System;using System.Collections.Generic; class GFG{ // Function to check whether// the subarray has all unique digitsstatic bool check(List<int> v){ // Storing all digits occurred HashSet<int> digits = new HashSet<int>(); // Traversing all the numbers of v for(int i = 0; i < v.Count; i++) { // Storing all digits of v[i] HashSet<int> d = new HashSet<int>(); while (v[i] > 0) { d.Add(v[i] % 10); v[i] = v[i] / 10; } // Checking whether digits of v[i] // have already occurred foreach(int it in d) { if (digits.Contains(it)) return false; } // Inserting digits of v[i] in the set foreach(int it in d) digits.Add(it); } return true;} // Function to count the number// subarray with all digits uniquestatic int numberOfSubarrays(int []a, int n){ int answer = 0; // Traverse through all the subarrays for(int i = 1; i < (1 << n); i++) { // To store elements of this subarray List<int> temp = new List<int>(); // Generate all subarray // and store it in vector for(int j = 0; j < n; j++) { if ((i & (1 << j)) > 0) temp.Add(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver codepublic static void Main(String[] args){ int N = 4; int []A = { 1, 12, 23, 34 }; Console.Write(numberOfSubarrays(A, N));}} // This code is contributed by sapnasingh4991 <script>// Javascript program to find the count// of subarrays of an Array// having all unique digits // Function to check whether// the subarray has all unique digitsfunction check(v) { // Storing all digits occurred let digits = new Set(); // Traversing all the numbers of v for (let i = 0; i < v.length; i++) { // Storing all digits of v[i] let d = new Set(); while (v[i]) { d.add(v[i] % 10); v[i] = Math.floor(v[i] / 10); } // Checking whether digits of v[i] // have already occurred for (let it of d) { if (digits.has(it)) return false; } // Inserting digits of v[i] in the set for (let it of d) digits.add(it); } return true;} // Function to count the number// subarray with all digits uniquefunction numberOfSubarrays(a, n) { let answer = 0; // Traverse through all the subarrays for (let i = 1; i < (1 << n); i++) { // To store elements of this subarray let temp = new Array(); // Generate all subarray // and store it in vector for (let j = 0; j < n; j++) { if (i & (1 << j)) temp.push(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver code let N = 4;let A = [1, 12, 23, 34]; document.write(numberOfSubarrays(A, N)); // This code is contributed by gfgking</script> 7 Time Complexity: O(N * 2N) Efficient Approach: This approach depends upon the fact that there exist only 10 unique digits in the Decimal number system. Therefore the longest subsequence will have only 10 digits in it, to meet the required condition. We will use Bitmasking and Dynamic Programming to solve the problem. Since there are only 10 digits, consider a 10-bit representation of every number where each bit is 1 if digit corresponding to that bit is present in that number. Let, i be the current array element (elements from 1 to i-1 are already processed). An integer variable ‘mask‘ indicates the digits which have already occurred in the subsequence. If i’th bit is set in the mask, then i’th digit has occurred, else not. At each step of recurrence relation, the element can either be included in the subsequence or not. If the element is not included in the subarray, then simply move to the next index. If it is included, change the mask by setting all the bits corresponding to the current element’s digit, ON in the mask. Note: The current element can only be included if all of its digits have not occurred previously. This condition will be satisfied only if the bits corresponding to the current element’s digits in the mask are OFF. If we draw the complete recursion tree, we can observe that many subproblems are being solved again and again. So we use Dynamic Programming. A table dp[][] is used such that for every index dp[i][j], i is the position of the element in the array and j is the mask. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the count// of subsequences of an Array// having all unique digits #include <bits/stdc++.h>using namespace std; // Dynamic programming tableint dp[5000][(1 << 10) + 5]; // Function to obtain// the mask for any integerint getmask(int val){ int mask = 0; if (val == 0) return 1; while (val) { int d = val % 10; mask |= (1 << d); val /= 10; } return mask;} // Function to count the number of waysint countWays(int pos, int mask, int a[], int n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included int new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos][mask] = count;} // Function to find the count of// subarray with all digits uniqueint numberOfSubarrays(int a[], int n){ // initializing dp memset(dp, -1, sizeof(dp)); return countWays(0, 0, a, n);} // Driver codeint main(){ int N = 4; int A[] = { 1, 12, 23, 34 }; cout << numberOfSubarrays(A, N); return 0;} // Java program to find the count// of subarrays of an Array// having all unique digitsimport java.util.*; class GFG{ // Dynamic programming tablestatic int [][]dp = new int[5000][(1 << 10) + 5]; // Function to obtain// the mask for any integerstatic int getmask(int val){ int mask = 0; if (val == 0) return 1; while (val > 0) { int d = val % 10; mask |= (1 << d); val /= 10; } return mask;} // Function to count the number of waysstatic int countWays(int pos, int mask, int a[], int n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included int new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos][mask] = count;} // Function to find the count of// subarray with all digits uniquestatic int numberOfSubarrays(int a[], int n){ // initializing dp for(int i = 0;i<5000;i++) { for (int j = 0; j < (1 << 10) + 5; j++) { dp[i][j] = -1; } } return countWays(0, 0, a, n);} // Driver codepublic static void main(String[] args){ int N = 4; int A[] = { 1, 12, 23, 34 }; System.out.print(numberOfSubarrays(A, N));}} // This code is contributed by Princi Singh # Python3 program to find the count# of subarrays of an Array having all# unique digits # Function to obtain# the mask for any integerdef getmask(val): mask = 0 if val == 0: return 1 while (val): d = val % 10; mask |= (1 << d) val = val // 10 return mask # Function to count the number of waysdef countWays(pos, mask, a, n): # Subarray must not be empty if pos == n : if mask > 0: return 1 else: return 0 # If subproblem has been solved if dp[pos][mask] != -1: return dp[pos][mask] count = 0 # Excluding this element in the subarray count = (count + countWays(pos + 1, mask, a, n)) # If there are no common digits # then only this element can be included if (getmask(a[pos]) & mask) == 0: # Calculate the new mask # if this element is included new_mask = (mask | (getmask(a[pos]))) count = (count + countWays(pos + 1, new_mask, a, n)) # Store and return the answer dp[pos][mask] = count return count # Function to find the count of# subarray with all digits uniquedef numberOfSubarrays(a, n): return countWays(0, 0, a, n) # Driver CodeN = 4A = [ 1, 12, 23, 34 ] rows = 5000cols = 1100 # Initializing dpdp = [ [ -1 for i in range(cols) ] for j in range(rows) ] print( numberOfSubarrays(A, N)) # This code is contributed by sarthak_eddy. // C# program to find the count// of subarrays of an Array// having all unique digitsusing System; public class GFG{ // Dynamic programming tablestatic int [,]dp = new int[5000, (1 << 10) + 5]; // Function to obtain// the mask for any integerstatic int getmask(int val){ int mask = 0; if (val == 0) return 1; while (val > 0) { int d = val % 10; mask |= (1 << d); val /= 10; } return mask;} // Function to count the number of waysstatic int countWays(int pos, int mask, int []a, int n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos, mask] != -1) return dp[pos, mask]; int count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included int new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos, mask] = count;} // Function to find the count of// subarray with all digits uniquestatic int numberOfSubarrays(int []a, int n){ // initializing dp for(int i = 0; i < 5000; i++) { for (int j = 0; j < (1 << 10) + 5; j++) { dp[i,j] = -1; } } return countWays(0, 0, a, n);} // Driver codepublic static void Main(String[] args){ int N = 4; int []A = { 1, 12, 23, 34 }; Console.Write(numberOfSubarrays(A, N));}}// This code contributed by sapnasingh4991 <script> // Javascript program to find the count// of subarrays of an Array// having all unique digits // Dynamic programming tablevar dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5).fill(-1)); // Function to obtain// the mask for any integerfunction getmask(val){ var mask = 0; if (val == 0) return 1; while (val) { var d = val % 10; mask |= (1 << d); val = parseInt(val/10); } return mask;} // Function to count the number of waysfunction countWays(pos, mask, a, n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; var count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included var new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos][mask] = count;} // Function to find the count of// subarray with all digits uniquefunction numberOfSubarrays(a, n){ // initializing dp dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5).fill(-1)); return countWays(0, 0, a, n);} // Driver codevar N = 4;var A = [1, 12, 23, 34];document.write( numberOfSubarrays(A, N)); </script> 7 Time Complexity: O(N * 210) princi singh 29AjayKumar sapnasingh4991 sarthak_eddy rutvik_56 gfgking noob2000 saurabh1990aror ankit2000bagde Arrays Bit Magic Competitive Programming Dynamic Programming Recursion Arrays Dynamic Programming Recursion Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Nov, 2021" }, { "code": null, "e": 288, "s": 52, "text": "Given an array A containing N positive integers, the task is to find the number of subsequences of this array such that in each subsequence , no digit is repeated twice, i.e. all the digits of the subsequences must be unique.Examples: " }, { "code": null, "e": 442, "s": 288, "text": "Input: A = [1, 12, 23, 34] Output: 7 The subsequences are: {1}, {12}, {23}, {34}, {1, 23}, {1, 34}, {12, 34} Therefore the count of such subsequences = 7" }, { "code": null, "e": 494, "s": 442, "text": "Input: A = [5, 12, 2, 1, 165, 2323, 7] Output: 33 " }, { "code": null, "e": 682, "s": 494, "text": "Naive approach: Generate all subsequences of the array and traverse through them to check whether the given condition is satisfied or not. Print the count of such subsequences at the end." }, { "code": null, "e": 733, "s": 682, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 737, "s": 733, "text": "C++" }, { "code": null, "e": 742, "s": 737, "text": "Java" }, { "code": null, "e": 750, "s": 742, "text": "Python3" }, { "code": null, "e": 753, "s": 750, "text": "C#" }, { "code": null, "e": 764, "s": 753, "text": "Javascript" }, { "code": "// C++ program to find the count// of subsequences of an Array// having all unique digits #include <bits/stdc++.h>using namespace std; // Function to check whether// the subsequences has all unique digitsbool check(vector<int>& v){ // Storing all digits occurred set<int> digits; // Traversing all the numbers of v for (int i = 0; i < v.size(); i++) { // Storing all digits of v[i] set<int> d; while (v[i]) { d.insert(v[i] % 10); v[i] /= 10; } // Checking whether digits of v[i] // have already occurred for (auto it : d) { if (digits.count(it)) return false; } // Inserting digits of v[i] in the set for (auto it : d) digits.insert(it); } return true;} // Function to count the number// subarray with all digits uniqueint numberOfSubarrays(int a[], int n){ int answer = 0; // Traverse through all the subarrays for (int i = 1; i < (1 << n); i++) { // To store elements of this subarray vector<int> temp; // Generate all subarray // and store it in vector for (int j = 0; j < n; j++) { if (i & (1 << j)) temp.push_back(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver codeint main(){ int N = 4; int A[] = { 1, 12, 23, 34 }; cout << numberOfSubarrays(A, N); return 0;}", "e": 2348, "s": 764, "text": null }, { "code": "// Java program to find the count// of subarrays of an Array// having all unique digits import java.util.*; class GFG{ // Function to check whether// the subarray has all unique digitsstatic boolean check(Vector<Integer> v){ // Storing all digits occurred HashSet<Integer> digits = new HashSet<Integer>(); // Traversing all the numbers of v for (int i = 0; i < v.size(); i++) { // Storing all digits of v[i] HashSet<Integer> d = new HashSet<Integer>(); while (v.get(i)>0) { d.add(v.get(i) % 10); v.set(i, v.get(i)/10); } // Checking whether digits of v[i] // have already occurred for (int it : d) { if (digits.contains(it)) return false; } // Inserting digits of v[i] in the set for (int it : d) digits.add(it); } return true;} // Function to count the number// subarray with all digits uniquestatic int numberOfSubarrays(int a[], int n){ int answer = 0; // Traverse through all the subarrays for (int i = 1; i < (1 << n); i++) { // To store elements of this subarray Vector<Integer> temp = new Vector<Integer>(); // Generate all subarray // and store it in vector for (int j = 0; j < n; j++) { if ((i & (1 << j))>0) temp.add(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver codepublic static void main(String[] args){ int N = 4; int A[] = { 1, 12, 23, 34 }; System.out.print(numberOfSubarrays(A, N));}} // This code is contributed by 29AjayKumar", "e": 4125, "s": 2348, "text": null }, { "code": "# Python3 program to find the count# of subarrays of an Array# having all unique digits # Function to check whether# the subarray has all unique digitsdef check(v): # Storing all digits occurred digits = set() # Traversing all the numbers of v for i in range(len(v)): # Storing all digits of v[i] d = set() while (v[i] != 0): d.add(v[i] % 10) v[i] //= 10 # Checking whether digits of v[i] # have already occurred for it in d: if it in digits: return False # Inserting digits of v[i] in the set for it in d: digits.add(it) return True # Function to count the number# subarray with all digits uniquedef numberOfSubarrays(a, n): answer = 0 # Traverse through all the subarrays for i in range(1, 1 << n): # To store elements of this subarray temp = [] # Generate all subarray # and store it in vector for j in range(n): if (i & (1 << j)): temp.append(a[j]) # Check whether this subarray # has all digits unique if (check(temp)): # Increase the count answer += 1 # Return the count return answer # Driver codeif __name__==\"__main__\": N = 4 A = [ 1, 12, 23, 34 ] print(numberOfSubarrays(A, N)) # This code is contributed by rutvik_56", "e": 5576, "s": 4125, "text": null }, { "code": "// C# program to find the count// of subarrays of an Array// having all unique digitsusing System;using System.Collections.Generic; class GFG{ // Function to check whether// the subarray has all unique digitsstatic bool check(List<int> v){ // Storing all digits occurred HashSet<int> digits = new HashSet<int>(); // Traversing all the numbers of v for(int i = 0; i < v.Count; i++) { // Storing all digits of v[i] HashSet<int> d = new HashSet<int>(); while (v[i] > 0) { d.Add(v[i] % 10); v[i] = v[i] / 10; } // Checking whether digits of v[i] // have already occurred foreach(int it in d) { if (digits.Contains(it)) return false; } // Inserting digits of v[i] in the set foreach(int it in d) digits.Add(it); } return true;} // Function to count the number// subarray with all digits uniquestatic int numberOfSubarrays(int []a, int n){ int answer = 0; // Traverse through all the subarrays for(int i = 1; i < (1 << n); i++) { // To store elements of this subarray List<int> temp = new List<int>(); // Generate all subarray // and store it in vector for(int j = 0; j < n; j++) { if ((i & (1 << j)) > 0) temp.Add(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver codepublic static void Main(String[] args){ int N = 4; int []A = { 1, 12, 23, 34 }; Console.Write(numberOfSubarrays(A, N));}} // This code is contributed by sapnasingh4991", "e": 7360, "s": 5576, "text": null }, { "code": "<script>// Javascript program to find the count// of subarrays of an Array// having all unique digits // Function to check whether// the subarray has all unique digitsfunction check(v) { // Storing all digits occurred let digits = new Set(); // Traversing all the numbers of v for (let i = 0; i < v.length; i++) { // Storing all digits of v[i] let d = new Set(); while (v[i]) { d.add(v[i] % 10); v[i] = Math.floor(v[i] / 10); } // Checking whether digits of v[i] // have already occurred for (let it of d) { if (digits.has(it)) return false; } // Inserting digits of v[i] in the set for (let it of d) digits.add(it); } return true;} // Function to count the number// subarray with all digits uniquefunction numberOfSubarrays(a, n) { let answer = 0; // Traverse through all the subarrays for (let i = 1; i < (1 << n); i++) { // To store elements of this subarray let temp = new Array(); // Generate all subarray // and store it in vector for (let j = 0; j < n; j++) { if (i & (1 << j)) temp.push(a[j]); } // Check whether this subarray // has all digits unique if (check(temp)) // Increase the count answer++; } // Return the count return answer;} // Driver code let N = 4;let A = [1, 12, 23, 34]; document.write(numberOfSubarrays(A, N)); // This code is contributed by gfgking</script>", "e": 8934, "s": 7360, "text": null }, { "code": null, "e": 8936, "s": 8934, "text": "7" }, { "code": null, "e": 8965, "s": 8938, "text": "Time Complexity: O(N * 2N)" }, { "code": null, "e": 9189, "s": 8965, "text": "Efficient Approach: This approach depends upon the fact that there exist only 10 unique digits in the Decimal number system. Therefore the longest subsequence will have only 10 digits in it, to meet the required condition. " }, { "code": null, "e": 9258, "s": 9189, "text": "We will use Bitmasking and Dynamic Programming to solve the problem." }, { "code": null, "e": 9421, "s": 9258, "text": "Since there are only 10 digits, consider a 10-bit representation of every number where each bit is 1 if digit corresponding to that bit is present in that number." }, { "code": null, "e": 9673, "s": 9421, "text": "Let, i be the current array element (elements from 1 to i-1 are already processed). An integer variable ‘mask‘ indicates the digits which have already occurred in the subsequence. If i’th bit is set in the mask, then i’th digit has occurred, else not." }, { "code": null, "e": 10075, "s": 9673, "text": "At each step of recurrence relation, the element can either be included in the subsequence or not. If the element is not included in the subarray, then simply move to the next index. If it is included, change the mask by setting all the bits corresponding to the current element’s digit, ON in the mask. Note: The current element can only be included if all of its digits have not occurred previously." }, { "code": null, "e": 10192, "s": 10075, "text": "This condition will be satisfied only if the bits corresponding to the current element’s digits in the mask are OFF." }, { "code": null, "e": 10460, "s": 10192, "text": "If we draw the complete recursion tree, we can observe that many subproblems are being solved again and again. So we use Dynamic Programming. A table dp[][] is used such that for every index dp[i][j], i is the position of the element in the array and j is the mask. " }, { "code": null, "e": 10511, "s": 10460, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 10515, "s": 10511, "text": "C++" }, { "code": null, "e": 10520, "s": 10515, "text": "Java" }, { "code": null, "e": 10528, "s": 10520, "text": "Python3" }, { "code": null, "e": 10531, "s": 10528, "text": "C#" }, { "code": null, "e": 10542, "s": 10531, "text": "Javascript" }, { "code": "// C++ program to find the count// of subsequences of an Array// having all unique digits #include <bits/stdc++.h>using namespace std; // Dynamic programming tableint dp[5000][(1 << 10) + 5]; // Function to obtain// the mask for any integerint getmask(int val){ int mask = 0; if (val == 0) return 1; while (val) { int d = val % 10; mask |= (1 << d); val /= 10; } return mask;} // Function to count the number of waysint countWays(int pos, int mask, int a[], int n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included int new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos][mask] = count;} // Function to find the count of// subarray with all digits uniqueint numberOfSubarrays(int a[], int n){ // initializing dp memset(dp, -1, sizeof(dp)); return countWays(0, 0, a, n);} // Driver codeint main(){ int N = 4; int A[] = { 1, 12, 23, 34 }; cout << numberOfSubarrays(A, N); return 0;}", "e": 12146, "s": 10542, "text": null }, { "code": "// Java program to find the count// of subarrays of an Array// having all unique digitsimport java.util.*; class GFG{ // Dynamic programming tablestatic int [][]dp = new int[5000][(1 << 10) + 5]; // Function to obtain// the mask for any integerstatic int getmask(int val){ int mask = 0; if (val == 0) return 1; while (val > 0) { int d = val % 10; mask |= (1 << d); val /= 10; } return mask;} // Function to count the number of waysstatic int countWays(int pos, int mask, int a[], int n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included int new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos][mask] = count;} // Function to find the count of// subarray with all digits uniquestatic int numberOfSubarrays(int a[], int n){ // initializing dp for(int i = 0;i<5000;i++) { for (int j = 0; j < (1 << 10) + 5; j++) { dp[i][j] = -1; } } return countWays(0, 0, a, n);} // Driver codepublic static void main(String[] args){ int N = 4; int A[] = { 1, 12, 23, 34 }; System.out.print(numberOfSubarrays(A, N));}} // This code is contributed by Princi Singh", "e": 13956, "s": 12146, "text": null }, { "code": "# Python3 program to find the count# of subarrays of an Array having all# unique digits # Function to obtain# the mask for any integerdef getmask(val): mask = 0 if val == 0: return 1 while (val): d = val % 10; mask |= (1 << d) val = val // 10 return mask # Function to count the number of waysdef countWays(pos, mask, a, n): # Subarray must not be empty if pos == n : if mask > 0: return 1 else: return 0 # If subproblem has been solved if dp[pos][mask] != -1: return dp[pos][mask] count = 0 # Excluding this element in the subarray count = (count + countWays(pos + 1, mask, a, n)) # If there are no common digits # then only this element can be included if (getmask(a[pos]) & mask) == 0: # Calculate the new mask # if this element is included new_mask = (mask | (getmask(a[pos]))) count = (count + countWays(pos + 1, new_mask, a, n)) # Store and return the answer dp[pos][mask] = count return count # Function to find the count of# subarray with all digits uniquedef numberOfSubarrays(a, n): return countWays(0, 0, a, n) # Driver CodeN = 4A = [ 1, 12, 23, 34 ] rows = 5000cols = 1100 # Initializing dpdp = [ [ -1 for i in range(cols) ] for j in range(rows) ] print( numberOfSubarrays(A, N)) # This code is contributed by sarthak_eddy.", "e": 15473, "s": 13956, "text": null }, { "code": "// C# program to find the count// of subarrays of an Array// having all unique digitsusing System; public class GFG{ // Dynamic programming tablestatic int [,]dp = new int[5000, (1 << 10) + 5]; // Function to obtain// the mask for any integerstatic int getmask(int val){ int mask = 0; if (val == 0) return 1; while (val > 0) { int d = val % 10; mask |= (1 << d); val /= 10; } return mask;} // Function to count the number of waysstatic int countWays(int pos, int mask, int []a, int n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos, mask] != -1) return dp[pos, mask]; int count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included int new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos, mask] = count;} // Function to find the count of// subarray with all digits uniquestatic int numberOfSubarrays(int []a, int n){ // initializing dp for(int i = 0; i < 5000; i++) { for (int j = 0; j < (1 << 10) + 5; j++) { dp[i,j] = -1; } } return countWays(0, 0, a, n);} // Driver codepublic static void Main(String[] args){ int N = 4; int []A = { 1, 12, 23, 34 }; Console.Write(numberOfSubarrays(A, N));}}// This code contributed by sapnasingh4991", "e": 17210, "s": 15473, "text": null }, { "code": "<script> // Javascript program to find the count// of subarrays of an Array// having all unique digits // Dynamic programming tablevar dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5).fill(-1)); // Function to obtain// the mask for any integerfunction getmask(val){ var mask = 0; if (val == 0) return 1; while (val) { var d = val % 10; mask |= (1 << d); val = parseInt(val/10); } return mask;} // Function to count the number of waysfunction countWays(pos, mask, a, n){ // Subarray must not be empty if (pos == n) return (mask > 0 ? 1 : 0); // If subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; var count = 0; // Excluding this element in the subarray count = count + countWays(pos + 1, mask, a, n); // If there are no common digits // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask // if this element is included var new_mask = (mask | (getmask(a[pos]))); count = count + countWays(pos + 1, new_mask, a, n); } // Store and return the answer return dp[pos][mask] = count;} // Function to find the count of// subarray with all digits uniquefunction numberOfSubarrays(a, n){ // initializing dp dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5).fill(-1)); return countWays(0, 0, a, n);} // Driver codevar N = 4;var A = [1, 12, 23, 34];document.write( numberOfSubarrays(A, N)); </script>", "e": 18818, "s": 17210, "text": null }, { "code": null, "e": 18820, "s": 18818, "text": "7" }, { "code": null, "e": 18851, "s": 18822, "text": "Time Complexity: O(N * 210) " }, { "code": null, "e": 18864, "s": 18851, "text": "princi singh" }, { "code": null, "e": 18876, "s": 18864, "text": "29AjayKumar" }, { "code": null, "e": 18891, "s": 18876, "text": "sapnasingh4991" }, { "code": null, "e": 18904, "s": 18891, "text": "sarthak_eddy" }, { "code": null, "e": 18914, "s": 18904, "text": "rutvik_56" }, { "code": null, "e": 18922, "s": 18914, "text": "gfgking" }, { "code": null, "e": 18931, "s": 18922, "text": "noob2000" }, { "code": null, "e": 18947, "s": 18931, "text": "saurabh1990aror" }, { "code": null, "e": 18962, "s": 18947, "text": "ankit2000bagde" }, { "code": null, "e": 18969, "s": 18962, "text": "Arrays" }, { "code": null, "e": 18979, "s": 18969, "text": "Bit Magic" }, { "code": null, "e": 19003, "s": 18979, "text": "Competitive Programming" }, { "code": null, "e": 19023, "s": 19003, "text": "Dynamic Programming" }, { "code": null, "e": 19033, "s": 19023, "text": "Recursion" }, { "code": null, "e": 19040, "s": 19033, "text": "Arrays" }, { "code": null, "e": 19060, "s": 19040, "text": "Dynamic Programming" }, { "code": null, "e": 19070, "s": 19060, "text": "Recursion" }, { "code": null, "e": 19080, "s": 19070, "text": "Bit Magic" }, { "code": null, "e": 19178, "s": 19080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19210, "s": 19178, "text": "Introduction to Data Structures" }, { "code": null, "e": 19235, "s": 19210, "text": "Window Sliding Technique" }, { "code": null, "e": 19282, "s": 19235, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 19346, "s": 19282, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 19377, "s": 19346, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 19404, "s": 19377, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 19450, "s": 19404, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 19518, "s": 19450, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 19547, "s": 19518, "text": "Count set bits in an integer" } ]
Rust – Strings
01 Jun, 2021 String data type makes a very important part of any programming language. Rust handles strings a bit differently from other languages. The String data type in Rust is of two types: String Literal (&str) String Object (String) String Literal or &str are called ‘string slices’, which always point to a legitimate UTF-8 sequence. It is used when we know the value of a string at compile time. They are a set of characters and static by default. Example 1: Declaring string literals. Rust fn main() { let website:&str="geeksforgeeks.org"; let language:&str = "RUST"; println!("Website is {}",website); println!("Language is {}",language);} Output: Website is geeksforgeeks.org Language is RUST The String Object is provided by the Standard Library in Rust. It is not a part of the core language and String is heap-allocated, growable, and not null-terminated. They are commonly created by converting them from a string slice by using the to_string() method. Example 2: Declaring String Object and converting String Literal to String Object Rust fn main() { // Declaring String Object using from() method let str1 = String::from("Rust Articles"); println!("{}",str1); // Converting String Literal to String Object let str2 = "GeeksforGeeks".to_string(); println!("{}",str2);} Output: Rust Articles GeeksforGeeks Example 3: Creating an empty string and then set its value. Rust fn main() { let mut str1 = String::new(); str1.push_str("GeeksForGeeks"); println!("{}",z);} Output: GeeksForGeeks Rust allows many methods to be used with Strings just as JAVA does. Also, it supports many methods such as indexing, concatenation, and slicing. Picked Rust-basics strings Rust Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rust - Creating a Library Rust - Generic Function Rust - For and Range Rust - Casting Rust - References & Borrowing Rust - Concept of Structures Primitive Compound Datatypes in Rust Rust - While Loop Rust - Box Smart Pointer Rust - Comments
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 165, "s": 28, "text": "String data type makes a very important part of any programming language. Rust handles strings a bit differently from other languages. " }, { "code": null, "e": 211, "s": 165, "text": "The String data type in Rust is of two types:" }, { "code": null, "e": 233, "s": 211, "text": "String Literal (&str)" }, { "code": null, "e": 256, "s": 233, "text": "String Object (String)" }, { "code": null, "e": 473, "s": 256, "text": "String Literal or &str are called ‘string slices’, which always point to a legitimate UTF-8 sequence. It is used when we know the value of a string at compile time. They are a set of characters and static by default." }, { "code": null, "e": 511, "s": 473, "text": "Example 1: Declaring string literals." }, { "code": null, "e": 516, "s": 511, "text": "Rust" }, { "code": "fn main() { let website:&str=\"geeksforgeeks.org\"; let language:&str = \"RUST\"; println!(\"Website is {}\",website); println!(\"Language is {}\",language);}", "e": 675, "s": 516, "text": null }, { "code": null, "e": 683, "s": 675, "text": "Output:" }, { "code": null, "e": 729, "s": 683, "text": "Website is geeksforgeeks.org\nLanguage is RUST" }, { "code": null, "e": 993, "s": 729, "text": "The String Object is provided by the Standard Library in Rust. It is not a part of the core language and String is heap-allocated, growable, and not null-terminated. They are commonly created by converting them from a string slice by using the to_string() method." }, { "code": null, "e": 1075, "s": 993, "text": "Example 2: Declaring String Object and converting String Literal to String Object" }, { "code": null, "e": 1080, "s": 1075, "text": "Rust" }, { "code": "fn main() { // Declaring String Object using from() method let str1 = String::from(\"Rust Articles\"); println!(\"{}\",str1); // Converting String Literal to String Object let str2 = \"GeeksforGeeks\".to_string(); println!(\"{}\",str2);}", "e": 1329, "s": 1080, "text": null }, { "code": null, "e": 1337, "s": 1329, "text": "Output:" }, { "code": null, "e": 1365, "s": 1337, "text": "Rust Articles\nGeeksforGeeks" }, { "code": null, "e": 1425, "s": 1365, "text": "Example 3: Creating an empty string and then set its value." }, { "code": null, "e": 1430, "s": 1425, "text": "Rust" }, { "code": "fn main() { let mut str1 = String::new(); str1.push_str(\"GeeksForGeeks\"); println!(\"{}\",z);}", "e": 1529, "s": 1430, "text": null }, { "code": null, "e": 1537, "s": 1529, "text": "Output:" }, { "code": null, "e": 1551, "s": 1537, "text": "GeeksForGeeks" }, { "code": null, "e": 1696, "s": 1551, "text": "Rust allows many methods to be used with Strings just as JAVA does. Also, it supports many methods such as indexing, concatenation, and slicing." }, { "code": null, "e": 1703, "s": 1696, "text": "Picked" }, { "code": null, "e": 1715, "s": 1703, "text": "Rust-basics" }, { "code": null, "e": 1723, "s": 1715, "text": "strings" }, { "code": null, "e": 1728, "s": 1723, "text": "Rust" }, { "code": null, "e": 1826, "s": 1728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1852, "s": 1826, "text": "Rust - Creating a Library" }, { "code": null, "e": 1876, "s": 1852, "text": "Rust - Generic Function" }, { "code": null, "e": 1897, "s": 1876, "text": "Rust - For and Range" }, { "code": null, "e": 1912, "s": 1897, "text": "Rust - Casting" }, { "code": null, "e": 1942, "s": 1912, "text": "Rust - References & Borrowing" }, { "code": null, "e": 1971, "s": 1942, "text": "Rust - Concept of Structures" }, { "code": null, "e": 2008, "s": 1971, "text": "Primitive Compound Datatypes in Rust" }, { "code": null, "e": 2026, "s": 2008, "text": "Rust - While Loop" }, { "code": null, "e": 2051, "s": 2026, "text": "Rust - Box Smart Pointer" } ]
Scanner hasNextInt() method in Java with Examples
02 Dec, 2021 The hasNextInt() method of java.util.Scanner class returns true if the next token in this scanner’s input can be assumed as a Int value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interpretes the radix to be default radix and functions accordingly. Syntax: public boolean hasNextInt(int radix) or public boolean hasNextInt() Parameters: The function accepts a single parameter radix which is not a mandatory one. It specifies the radix used to interpret the token as a Int value. Return Value: This function returns true if and only if this scanner’s next token is a valid Int value in the default radix. Exceptions: The function throws IllegalStateException if this scanner is closed. Below programs illustrate the above function: Program 1: // Java program to illustrate the// hasNextInt() method of Scanner class in Java// with parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "gfg 2 geeks!"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Ints in a string scanner.useLocale(Locale.US); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Int with a radix 3 System.out.print("" + scanner.hasNextInt(3)); // print what is scanned System.out.print(" -> " + scanner.next() + "\n"); } // close the scanner scanner.close(); }} false -> gfg true -> 2 false -> geeks! Program 2: // Java program to illustrate the// hasNextInt() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "gfg 2 geeks!"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Ints in a string scanner.useLocale(Locale.US); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Int with the default radix System.out.print("" + scanner.hasNextInt()); // print what is scanned System.out.print(" -> " + scanner.next() + "\n"); } // close the scanner scanner.close(); }} false -> gfg true -> 2 false -> geeks! Program 3: Program to demonstrate exception // Java program to illustrate the// hasNextInt() method of Scanner class in Java// Exception case import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "gfg 2 geeks!"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Ints in a string scanner.useLocale(Locale.US); scanner.close(); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Int with the default radix System.out.print("" + scanner.hasNextInt()); // print what is scanned System.out.print(" -> " + scanner.next() + "\n"); } // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println("Exception: " + e); } }} Exception: java.lang.IllegalStateException: Scanner closed Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt() sinhaparty22 Java - util package Java-Functions Java-Scanner Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Dec, 2021" }, { "code": null, "e": 378, "s": 52, "text": "The hasNextInt() method of java.util.Scanner class returns true if the next token in this scanner’s input can be assumed as a Int value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interpretes the radix to be default radix and functions accordingly." }, { "code": null, "e": 386, "s": 378, "text": "Syntax:" }, { "code": null, "e": 466, "s": 386, "text": "public boolean hasNextInt(int radix)\n or\npublic boolean hasNextInt()" }, { "code": null, "e": 621, "s": 466, "text": "Parameters: The function accepts a single parameter radix which is not a mandatory one. It specifies the radix used to interpret the token as a Int value." }, { "code": null, "e": 746, "s": 621, "text": "Return Value: This function returns true if and only if this scanner’s next token is a valid Int value in the default radix." }, { "code": null, "e": 827, "s": 746, "text": "Exceptions: The function throws IllegalStateException if this scanner is closed." }, { "code": null, "e": 873, "s": 827, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 884, "s": 873, "text": "Program 1:" }, { "code": "// Java program to illustrate the// hasNextInt() method of Scanner class in Java// with parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"gfg 2 geeks!\"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Ints in a string scanner.useLocale(Locale.US); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Int with a radix 3 System.out.print(\"\" + scanner.hasNextInt(3)); // print what is scanned System.out.print(\" -> \" + scanner.next() + \"\\n\"); } // close the scanner scanner.close(); }}", "e": 1709, "s": 884, "text": null }, { "code": null, "e": 1749, "s": 1709, "text": "false -> gfg\ntrue -> 2\nfalse -> geeks!\n" }, { "code": null, "e": 1760, "s": 1749, "text": "Program 2:" }, { "code": "// Java program to illustrate the// hasNextInt() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"gfg 2 geeks!\"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Ints in a string scanner.useLocale(Locale.US); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Int with the default radix System.out.print(\"\" + scanner.hasNextInt()); // print what is scanned System.out.print(\" -> \" + scanner.next() + \"\\n\"); } // close the scanner scanner.close(); }}", "e": 2595, "s": 1760, "text": null }, { "code": null, "e": 2635, "s": 2595, "text": "false -> gfg\ntrue -> 2\nfalse -> geeks!\n" }, { "code": null, "e": 2679, "s": 2635, "text": "Program 3: Program to demonstrate exception" }, { "code": "// Java program to illustrate the// hasNextInt() method of Scanner class in Java// Exception case import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"gfg 2 geeks!\"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Ints in a string scanner.useLocale(Locale.US); scanner.close(); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Int with the default radix System.out.print(\"\" + scanner.hasNextInt()); // print what is scanned System.out.print(\" -> \" + scanner.next() + \"\\n\"); } // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println(\"Exception: \" + e); } }}", "e": 3727, "s": 2679, "text": null }, { "code": null, "e": 3787, "s": 3727, "text": "Exception: java.lang.IllegalStateException: Scanner closed\n" }, { "code": null, "e": 3876, "s": 3787, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()" }, { "code": null, "e": 3889, "s": 3876, "text": "sinhaparty22" }, { "code": null, "e": 3909, "s": 3889, "text": "Java - util package" }, { "code": null, "e": 3924, "s": 3909, "text": "Java-Functions" }, { "code": null, "e": 3937, "s": 3924, "text": "Java-Scanner" }, { "code": null, "e": 3942, "s": 3937, "text": "Java" }, { "code": null, "e": 3947, "s": 3942, "text": "Java" } ]
Ruby | Array append() function
07 Jan, 2020 Array#append() is an Array class method which add elements at the end of the array. Syntax: Array.append() Parameter: – Arrays for adding elements.– elements to add Return: Array after adding the elements at the end. Example #1 : # Ruby code for append() method# adding elements at the end # declaring arraya = [18, 22, 33, 4, 5, 6] # declaring arrayb = [5, 4, 22, 1, 88, 9] # declaring arrayc = [18, 22, 33, 40, 50, 6] # appending array or element at the end of the arrayputs "adding elements in a : #{a.append(b)}\n\n" puts "adding elements in b : #{b.append("ratttt")}\n\n" puts "adding elements in c : #{c.append(b)}\n\n" Output : adding elements in a : [18, 22, 33, 4, 5, 6, [5, 4, 22, 1, 88, 9]] adding elements in b : [5, 4, 22, 1, 88, 9, "ratttt"] adding elements in c : [18, 22, 33, 40, 50, 6, [5, 4, 22, 1, 88, 9, "ratttt"]] Example #2 : # Ruby code for append() method# adding elements at the end # declaring arraya = ["abc", "xyz", "dog"] # declaring arrayb = ["cow", "cat", "dog"] # declaring arrayc = ["cat", "1", "dog"] # appending array or element at the end of the arrayputs "adding elements in a : #{a.append(b)}\n\n" puts "adding elements in b : #{b.append("ratttt")}\n\n" puts "adding elements in c : #{c.append(b)}\n\n" Output : adding elements in a : ["abc", "xyz", "dog", ["cow", "cat", "dog"]] adding elements in b : ["cow", "cat", "dog", "ratttt"] adding elements in c : ["cat", "1", "dog", ["cow", "cat", "dog", "ratttt"]] Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Case Statement Ruby Integer abs() function with example Ruby | Hash Class Ruby | unless Statement and unless Modifier Ruby | Array map() function Ruby | String reverse Method Ruby Mixins Ruby | Types of Variables Global Variable in Ruby Hello World in Ruby
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2020" }, { "code": null, "e": 112, "s": 28, "text": "Array#append() is an Array class method which add elements at the end of the array." }, { "code": null, "e": 135, "s": 112, "text": "Syntax: Array.append()" }, { "code": null, "e": 193, "s": 135, "text": "Parameter: – Arrays for adding elements.– elements to add" }, { "code": null, "e": 245, "s": 193, "text": "Return: Array after adding the elements at the end." }, { "code": null, "e": 258, "s": 245, "text": "Example #1 :" }, { "code": "# Ruby code for append() method# adding elements at the end # declaring arraya = [18, 22, 33, 4, 5, 6] # declaring arrayb = [5, 4, 22, 1, 88, 9] # declaring arrayc = [18, 22, 33, 40, 50, 6] # appending array or element at the end of the arrayputs \"adding elements in a : #{a.append(b)}\\n\\n\" puts \"adding elements in b : #{b.append(\"ratttt\")}\\n\\n\" puts \"adding elements in c : #{c.append(b)}\\n\\n\"", "e": 669, "s": 258, "text": null }, { "code": null, "e": 678, "s": 669, "text": "Output :" }, { "code": null, "e": 881, "s": 678, "text": "adding elements in a : [18, 22, 33, 4, 5, 6, [5, 4, 22, 1, 88, 9]]\n\nadding elements in b : [5, 4, 22, 1, 88, 9, \"ratttt\"]\n\nadding elements in c : [18, 22, 33, 40, 50, 6, [5, 4, 22, 1, 88, 9, \"ratttt\"]]\n" }, { "code": null, "e": 894, "s": 881, "text": "Example #2 :" }, { "code": "# Ruby code for append() method# adding elements at the end # declaring arraya = [\"abc\", \"xyz\", \"dog\"] # declaring arrayb = [\"cow\", \"cat\", \"dog\"] # declaring arrayc = [\"cat\", \"1\", \"dog\"] # appending array or element at the end of the arrayputs \"adding elements in a : #{a.append(b)}\\n\\n\" puts \"adding elements in b : #{b.append(\"ratttt\")}\\n\\n\" puts \"adding elements in c : #{c.append(b)}\\n\\n\"", "e": 1302, "s": 894, "text": null }, { "code": null, "e": 1311, "s": 1302, "text": "Output :" }, { "code": null, "e": 1512, "s": 1311, "text": "adding elements in a : [\"abc\", \"xyz\", \"dog\", [\"cow\", \"cat\", \"dog\"]]\n\nadding elements in b : [\"cow\", \"cat\", \"dog\", \"ratttt\"]\n\nadding elements in c : [\"cat\", \"1\", \"dog\", [\"cow\", \"cat\", \"dog\", \"ratttt\"]]" }, { "code": null, "e": 1529, "s": 1512, "text": "Ruby Array-class" }, { "code": null, "e": 1542, "s": 1529, "text": "Ruby-Methods" }, { "code": null, "e": 1547, "s": 1542, "text": "Ruby" }, { "code": null, "e": 1645, "s": 1547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1667, "s": 1645, "text": "Ruby | Case Statement" }, { "code": null, "e": 1708, "s": 1667, "text": "Ruby Integer abs() function with example" }, { "code": null, "e": 1726, "s": 1708, "text": "Ruby | Hash Class" }, { "code": null, "e": 1770, "s": 1726, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1798, "s": 1770, "text": "Ruby | Array map() function" }, { "code": null, "e": 1827, "s": 1798, "text": "Ruby | String reverse Method" }, { "code": null, "e": 1839, "s": 1827, "text": "Ruby Mixins" }, { "code": null, "e": 1865, "s": 1839, "text": "Ruby | Types of Variables" }, { "code": null, "e": 1889, "s": 1865, "text": "Global Variable in Ruby" } ]
Python PIL | BoxBlur() method
14 Sep, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.PIL.ImageFilter.BoxBlur() Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value. Syntax: PIL.ImageFilter.BoxBlur() Partameters: radius: Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total. Image used: Python3 # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(0)) im2.show() Output: Python3 # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(2)) im2.show() Output: Python3 # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(8)) im2.show() Output: gulshankumarar231 Image-Processing Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 575, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.PIL.ImageFilter.BoxBlur() Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value. " }, { "code": null, "e": 784, "s": 575, "text": "Syntax: PIL.ImageFilter.BoxBlur()\n\nPartameters: \nradius: Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total." }, { "code": null, "e": 798, "s": 784, "text": "Image used: " }, { "code": null, "e": 808, "s": 800, "text": "Python3" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(0)) im2.show()", "e": 1080, "s": 808, "text": null }, { "code": null, "e": 1090, "s": 1080, "text": "Output: " }, { "code": null, "e": 1100, "s": 1092, "text": "Python3" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(2)) im2.show()", "e": 1372, "s": 1100, "text": null }, { "code": null, "e": 1382, "s": 1372, "text": "Output: " }, { "code": null, "e": 1392, "s": 1384, "text": "Python3" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(8)) im2.show()", "e": 1664, "s": 1392, "text": null }, { "code": null, "e": 1674, "s": 1664, "text": "Output: " }, { "code": null, "e": 1694, "s": 1676, "text": "gulshankumarar231" }, { "code": null, "e": 1711, "s": 1694, "text": "Image-Processing" }, { "code": null, "e": 1722, "s": 1711, "text": "Python-pil" }, { "code": null, "e": 1729, "s": 1722, "text": "Python" }, { "code": null, "e": 1827, "s": 1729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1845, "s": 1827, "text": "Python Dictionary" }, { "code": null, "e": 1887, "s": 1845, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1909, "s": 1887, "text": "Enumerate() in Python" }, { "code": null, "e": 1944, "s": 1909, "text": "Read a file line by line in Python" }, { "code": null, "e": 1970, "s": 1944, "text": "Python String | replace()" }, { "code": null, "e": 2002, "s": 1970, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2031, "s": 2002, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2058, "s": 2031, "text": "Python Classes and Objects" }, { "code": null, "e": 2079, "s": 2058, "text": "Python OOPs Concepts" } ]
Program to find lowest possible integer that is missing in the array in Python
Suppose we have a list of numbers called nums, we have to find the first missing positive number. In other words, the lowest positive number that does not present in the array. The array can contain duplicates and negative numbers as well. So, if the input is like nums = [0,3,1], then the output will be 2 To solve this, we will follow these steps − nums := a set with all positive numbers present in nums nums := a set with all positive numbers present in nums if nums is null, thenreturn 1 if nums is null, then return 1 return 1 for i in range 1 to size of nums + 2, doif i is not present in nums, thenreturn i for i in range 1 to size of nums + 2, do if i is not present in nums, then if i is not present in nums, then return i return i Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums): nums = set(num for num in nums if num > 0) if not nums: return 1 for i in range(1, len(nums) + 2): if i not in nums: return i ob = Solution() nums = [0,3,1] print(ob.solve(nums)) [0,3,1] 2
[ { "code": null, "e": 1427, "s": 1187, "text": "Suppose we have a list of numbers called nums, we have to find the first missing positive number. In other words, the lowest positive number that does not present in the array. The array can contain duplicates and negative numbers as well." }, { "code": null, "e": 1494, "s": 1427, "text": "So, if the input is like nums = [0,3,1], then the output will be 2" }, { "code": null, "e": 1538, "s": 1494, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1594, "s": 1538, "text": "nums := a set with all positive numbers present in nums" }, { "code": null, "e": 1650, "s": 1594, "text": "nums := a set with all positive numbers present in nums" }, { "code": null, "e": 1680, "s": 1650, "text": "if nums is null, thenreturn 1" }, { "code": null, "e": 1702, "s": 1680, "text": "if nums is null, then" }, { "code": null, "e": 1711, "s": 1702, "text": "return 1" }, { "code": null, "e": 1720, "s": 1711, "text": "return 1" }, { "code": null, "e": 1802, "s": 1720, "text": "for i in range 1 to size of nums + 2, doif i is not present in nums, thenreturn i" }, { "code": null, "e": 1843, "s": 1802, "text": "for i in range 1 to size of nums + 2, do" }, { "code": null, "e": 1877, "s": 1843, "text": "if i is not present in nums, then" }, { "code": null, "e": 1911, "s": 1877, "text": "if i is not present in nums, then" }, { "code": null, "e": 1920, "s": 1911, "text": "return i" }, { "code": null, "e": 1929, "s": 1920, "text": "return i" }, { "code": null, "e": 1999, "s": 1929, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2010, "s": 1999, "text": " Live Demo" }, { "code": null, "e": 2280, "s": 2010, "text": "class Solution:\n def solve(self, nums):\n nums = set(num for num in nums if num > 0)\n\n if not nums:\n return 1\n for i in range(1, len(nums) + 2):\n if i not in nums:\n return i\nob = Solution()\nnums = [0,3,1]\nprint(ob.solve(nums))" }, { "code": null, "e": 2288, "s": 2280, "text": "[0,3,1]" }, { "code": null, "e": 2290, "s": 2288, "text": "2" } ]
Scrapy – Selectors
24 Jun, 2021 Scrapy Selectors as the name suggest are used to select some things. If we talk of CSS, then there are also selectors present that are used to select and apply CSS effects to HTML tags and text. In Scrapy we are using selectors to mention the part of the website which is to be scraped by our spiders. Hence, to scrape the right data from the site, it is very important that we should select the tags which represent data correctly. There are many tools used for that. In Scrapy, there are mainly two types of selectors, i.e. CSS selectors and XPath selectors. Both of them are performing the same function and selecting the same text or data but the format of passing the arguments is different in them. CSS selectors: Since CSS languages are defined in any HTML File, so we can use their selectors as a way to select parts of the HTML file in Scrapy. XPath selectors: It is a language used to select Nodes in XML documents and hence it can be used in HTML Files too since HTML Files can also be represented as XML documents. Let’s have an HTML File (index.html) as given below which we are to Scrap using our Spider and see how selectors are working. We will be working on Scrapy Shell to give commands to select data. HTML <html> <head> <title>Scrapy-Selectors</title> </head> <body> <div id='Selectors'> <h1> This is H1 Tag </h1> <span class="SPAN1"> This is Class Selectors SPAN tag </span> </div> </body></html> Below given is a view of our Scrapy Shell which we will be using: Command to open shell: Scrapy shell file:///C:/Users/Dipak/Desktop/index.html Scrapy Shell activated to Crawl Spiders on Index.html File. Now we will discuss how to use selectors in Scrapy. Since there are mainly two types of it as given below: There are various formats for using CSS selectors under different cases. They are given below: Very Basic Start goes from selecting the basic tags in HTML file such as the <HTML> tag, <HEAD>, <BODY>, etc. So the below given is the basic format to select any tag in the HTML File using Scrapy. Shell Command : response.css('html').get() # Here response object calls CSS selector method to # target HTML tag and get() method # is used to select everything inside the HTML tag. Output:The whole content of the HTML file is selected. So, now it’s time to modify our way of selecting, If we want to select only the inside text of the Tags or just want to select the attribute of any particular tag then we can follow the below-given syntax: # To select the text inside the Tags # excluding tags we have to use (::text) # as our extension. response.css('h1::text').get() # To select the attributes details of # any HTML tag we have to use below # given syntax: response.css('span').attrib['class'] Output of above commands. If there are many same types of tags in the HTML File then we can use .getall() method instead of .get() to select all the tags. It returns a list of selected tags and their data. If the tag which we have to select is not mentioned in the file then CSS selectors return nothing. We can also provide default data to be returned if nothing is found. Selects nothing. The way these selectors work is similar to that how CSS selectors work instead the syntax differs only. The below are the surtaxes which can be written in XPATH for selecting, what we have done earlier. # This is to select the text part of # title tag using XPATH response.xpath('//title/text()') response.xpath('//title/text()').get() # This is how to select attributes response.xpath('//span/@class').get() XPATH selectors. Properties: 1. We can nest selectors within one another. Since if our HTML file can contain elements inside the div tag, so we can nest the selectors to select a particular element in it. To achieve this we first have to select all the elements inside the div tag, and then we can select any particular element from it. div_tag = response.xpath('//div') div_tag.getall() for tags in div_tag: tag = tags.xpath('.//h1').get() print({tag}) Use of Nesting in selectors 2. Next we can use our selectors with the regular expression also. If we don’t know what is the name of the attributes or elements then we can use regular expressions too for selection. For this we have a method named ( .re()). The .re() Method is used to select tags based on the content match. If the content inside the HTML tag matches with the regular expression inputted, then this method returns a list of that content. In the above HTML file, we are having two tags named h1 and span tag inside the DIV tag, and the text in these both tags has the same starting i.e. ” This is “. So to select them based on regex we have to form their regular expression which is given below: regexp = r’This\sis\s*(.*)’ and we have to input this in our .re() method So our code becomes response.css(‘#Selectors *::text’).re(r’This\sis\s*(.*)’) Using Regular expression for selecting the text 3. EXSLT Regular Expressions are also supported by scrapy spiders. We can use its method to select the items based on some new regular expressions. This extension provides two different namespaces to be used in XPath re: Used for making regular expressions.set: Used for set manipulation re: Used for making regular expressions. set: Used for set manipulation We can use these namespaces to modify the select statement specified in our Xpath method. Below is one of the given example: Suppose we had added two h1 tag and name their class in our HTML file so now it looks like : HTML <html> <head> <title>Scrapy-Selectors</title> </head> <body> <div id='Selectors'> <h1 class='FirstH1'> This is H1 Tag </h1> <h1 class='FirstH2'> This is Second H1 Tag </h1> <h1 class='FirstH'> This is Third H1 Tag </h1> <span class="SPAN1"> This is Class Selectors SPAN tag </span> </div> </body></html> Now if we want to select both H1 tags using regexp then we can see that we have to select that tag that has a starting string first in the id part and the end integer doesn’t matter. So the code for this : response.xpath(‘//h1[re:test(@class, “FirstH\d$”)]’).getall() Here we are using re:test method to specify and test our regular expression on the class attribute of our h1 tag and regexp selects only those h1 tags whose class attribute values ends with an integer. This was an example of using EXSLT in selectors in scrapy. 4. If want we can use both selectors merged together to enhance the way of selecting. response.css('span').xpath('@class').get() # CSS is used to select tag and XPATH is # used to select attribute Merging selectors. Note: In XPath when we are using the nesting property of selectors then we should take care of a fact regarding Relative XPaths. Consider we selected a div tag as given below: div_tag = response.xpath(‘//div’) This will select div tag and all the elements inside that tag. Now assume that the div tag contains some <a>tags within it. Now if we want to use nesting selectors and select the <a> tag then we would write for a in div_tag.xpath(‘.//a’): This is a relative path that tells the spider to select tag elements from only the path inside the div tag selected above. If we will write – for a in div_tag(‘//a’): It will select all the tag inside the HTML document. So we should take care of relative paths. We can use Google Chrome Extension named as SelectorGadget which is used to simplify the selecting task. Since all websites today if we inspect them, have very lengthy and hard to understand and search codes. So amidst them, we can use this extension which enables selecting the tags on Frontend only. Picked Python-Scrapy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 223, "s": 28, "text": "Scrapy Selectors as the name suggest are used to select some things. If we talk of CSS, then there are also selectors present that are used to select and apply CSS effects to HTML tags and text." }, { "code": null, "e": 497, "s": 223, "text": "In Scrapy we are using selectors to mention the part of the website which is to be scraped by our spiders. Hence, to scrape the right data from the site, it is very important that we should select the tags which represent data correctly. There are many tools used for that." }, { "code": null, "e": 733, "s": 497, "text": "In Scrapy, there are mainly two types of selectors, i.e. CSS selectors and XPath selectors. Both of them are performing the same function and selecting the same text or data but the format of passing the arguments is different in them." }, { "code": null, "e": 881, "s": 733, "text": "CSS selectors: Since CSS languages are defined in any HTML File, so we can use their selectors as a way to select parts of the HTML file in Scrapy." }, { "code": null, "e": 1055, "s": 881, "text": "XPath selectors: It is a language used to select Nodes in XML documents and hence it can be used in HTML Files too since HTML Files can also be represented as XML documents." }, { "code": null, "e": 1249, "s": 1055, "text": "Let’s have an HTML File (index.html) as given below which we are to Scrap using our Spider and see how selectors are working. We will be working on Scrapy Shell to give commands to select data." }, { "code": null, "e": 1254, "s": 1249, "text": "HTML" }, { "code": "<html> <head> <title>Scrapy-Selectors</title> </head> <body> <div id='Selectors'> <h1> This is H1 Tag </h1> <span class=\"SPAN1\"> This is Class Selectors SPAN tag </span> </div> </body></html>", "e": 1455, "s": 1254, "text": null }, { "code": null, "e": 1521, "s": 1455, "text": "Below given is a view of our Scrapy Shell which we will be using:" }, { "code": null, "e": 1545, "s": 1521, "text": "Command to open shell: " }, { "code": null, "e": 1600, "s": 1545, "text": "Scrapy shell file:///C:/Users/Dipak/Desktop/index.html" }, { "code": null, "e": 1660, "s": 1600, "text": "Scrapy Shell activated to Crawl Spiders on Index.html File." }, { "code": null, "e": 1767, "s": 1660, "text": "Now we will discuss how to use selectors in Scrapy. Since there are mainly two types of it as given below:" }, { "code": null, "e": 1862, "s": 1767, "text": "There are various formats for using CSS selectors under different cases. They are given below:" }, { "code": null, "e": 2060, "s": 1862, "text": "Very Basic Start goes from selecting the basic tags in HTML file such as the <HTML> tag, <HEAD>, <BODY>, etc. So the below given is the basic format to select any tag in the HTML File using Scrapy." }, { "code": null, "e": 2244, "s": 2060, "text": "Shell Command : response.css('html').get()\n \n# Here response object calls CSS selector method to\n# target HTML tag and get() method\n# is used to select everything inside the HTML tag." }, { "code": null, "e": 2299, "s": 2244, "text": "Output:The whole content of the HTML file is selected." }, { "code": null, "e": 2505, "s": 2299, "text": "So, now it’s time to modify our way of selecting, If we want to select only the inside text of the Tags or just want to select the attribute of any particular tag then we can follow the below-given syntax:" }, { "code": null, "e": 2766, "s": 2505, "text": "# To select the text inside the Tags \n# excluding tags we have to use (::text) \n# as our extension.\nresponse.css('h1::text').get()\n\n# To select the attributes details of\n# any HTML tag we have to use below \n# given syntax:\nresponse.css('span').attrib['class']" }, { "code": null, "e": 2792, "s": 2766, "text": "Output of above commands." }, { "code": null, "e": 2972, "s": 2792, "text": "If there are many same types of tags in the HTML File then we can use .getall() method instead of .get() to select all the tags. It returns a list of selected tags and their data." }, { "code": null, "e": 3140, "s": 2972, "text": "If the tag which we have to select is not mentioned in the file then CSS selectors return nothing. We can also provide default data to be returned if nothing is found." }, { "code": null, "e": 3157, "s": 3140, "text": "Selects nothing." }, { "code": null, "e": 3261, "s": 3157, "text": "The way these selectors work is similar to that how CSS selectors work instead the syntax differs only." }, { "code": null, "e": 3360, "s": 3261, "text": "The below are the surtaxes which can be written in XPATH for selecting, what we have done earlier." }, { "code": null, "e": 3568, "s": 3360, "text": "# This is to select the text part of \n# title tag using XPATH\nresponse.xpath('//title/text()')\nresponse.xpath('//title/text()').get()\n\n# This is how to select attributes\nresponse.xpath('//span/@class').get()" }, { "code": null, "e": 3585, "s": 3568, "text": "XPATH selectors." }, { "code": null, "e": 3597, "s": 3585, "text": "Properties:" }, { "code": null, "e": 3905, "s": 3597, "text": "1. We can nest selectors within one another. Since if our HTML file can contain elements inside the div tag, so we can nest the selectors to select a particular element in it. To achieve this we first have to select all the elements inside the div tag, and then we can select any particular element from it." }, { "code": null, "e": 4033, "s": 3905, "text": "div_tag = response.xpath('//div')\ndiv_tag.getall()\n\nfor tags in div_tag:\n tag = tags.xpath('.//h1').get()\n print({tag})" }, { "code": null, "e": 4061, "s": 4033, "text": "Use of Nesting in selectors" }, { "code": null, "e": 4290, "s": 4061, "text": "2. Next we can use our selectors with the regular expression also. If we don’t know what is the name of the attributes or elements then we can use regular expressions too for selection. For this we have a method named ( .re()). " }, { "code": null, "e": 4745, "s": 4290, "text": "The .re() Method is used to select tags based on the content match. If the content inside the HTML tag matches with the regular expression inputted, then this method returns a list of that content. In the above HTML file, we are having two tags named h1 and span tag inside the DIV tag, and the text in these both tags has the same starting i.e. ” This is “. So to select them based on regex we have to form their regular expression which is given below:" }, { "code": null, "e": 4819, "s": 4745, "text": "regexp = r’This\\sis\\s*(.*)’ and we have to input this in our .re() method" }, { "code": null, "e": 4839, "s": 4819, "text": "So our code becomes" }, { "code": null, "e": 4897, "s": 4839, "text": "response.css(‘#Selectors *::text’).re(r’This\\sis\\s*(.*)’)" }, { "code": null, "e": 4945, "s": 4897, "text": "Using Regular expression for selecting the text" }, { "code": null, "e": 5163, "s": 4945, "text": "3. EXSLT Regular Expressions are also supported by scrapy spiders. We can use its method to select the items based on some new regular expressions. This extension provides two different namespaces to be used in XPath " }, { "code": null, "e": 5234, "s": 5163, "text": "re: Used for making regular expressions.set: Used for set manipulation" }, { "code": null, "e": 5275, "s": 5234, "text": "re: Used for making regular expressions." }, { "code": null, "e": 5306, "s": 5275, "text": "set: Used for set manipulation" }, { "code": null, "e": 5396, "s": 5306, "text": "We can use these namespaces to modify the select statement specified in our Xpath method." }, { "code": null, "e": 5431, "s": 5396, "text": "Below is one of the given example:" }, { "code": null, "e": 5524, "s": 5431, "text": "Suppose we had added two h1 tag and name their class in our HTML file so now it looks like :" }, { "code": null, "e": 5529, "s": 5524, "text": "HTML" }, { "code": "<html> <head> <title>Scrapy-Selectors</title> </head> <body> <div id='Selectors'> <h1 class='FirstH1'> This is H1 Tag </h1> <h1 class='FirstH2'> This is Second H1 Tag </h1> <h1 class='FirstH'> This is Third H1 Tag </h1> <span class=\"SPAN1\"> This is Class Selectors SPAN tag </span> </div> </body></html>", "e": 5848, "s": 5529, "text": null }, { "code": null, "e": 6031, "s": 5848, "text": "Now if we want to select both H1 tags using regexp then we can see that we have to select that tag that has a starting string first in the id part and the end integer doesn’t matter." }, { "code": null, "e": 6055, "s": 6031, "text": "So the code for this :" }, { "code": null, "e": 6117, "s": 6055, "text": "response.xpath(‘//h1[re:test(@class, “FirstH\\d$”)]’).getall()" }, { "code": null, "e": 6319, "s": 6117, "text": "Here we are using re:test method to specify and test our regular expression on the class attribute of our h1 tag and regexp selects only those h1 tags whose class attribute values ends with an integer." }, { "code": null, "e": 6378, "s": 6319, "text": "This was an example of using EXSLT in selectors in scrapy." }, { "code": null, "e": 6464, "s": 6378, "text": "4. If want we can use both selectors merged together to enhance the way of selecting." }, { "code": null, "e": 6576, "s": 6464, "text": "response.css('span').xpath('@class').get()\n# CSS is used to select tag and XPATH is \n# used to select attribute" }, { "code": null, "e": 6595, "s": 6576, "text": "Merging selectors." }, { "code": null, "e": 6601, "s": 6595, "text": "Note:" }, { "code": null, "e": 6771, "s": 6601, "text": "In XPath when we are using the nesting property of selectors then we should take care of a fact regarding Relative XPaths. Consider we selected a div tag as given below:" }, { "code": null, "e": 6805, "s": 6771, "text": "div_tag = response.xpath(‘//div’)" }, { "code": null, "e": 7012, "s": 6805, "text": "This will select div tag and all the elements inside that tag. Now assume that the div tag contains some <a>tags within it. Now if we want to use nesting selectors and select the <a> tag then we would write" }, { "code": null, "e": 7045, "s": 7012, "text": "for a in div_tag.xpath(‘.//a’): " }, { "code": null, "e": 7187, "s": 7045, "text": "This is a relative path that tells the spider to select tag elements from only the path inside the div tag selected above. If we will write –" }, { "code": null, "e": 7212, "s": 7187, "text": "for a in div_tag(‘//a’):" }, { "code": null, "e": 7307, "s": 7212, "text": "It will select all the tag inside the HTML document. So we should take care of relative paths." }, { "code": null, "e": 7609, "s": 7307, "text": "We can use Google Chrome Extension named as SelectorGadget which is used to simplify the selecting task. Since all websites today if we inspect them, have very lengthy and hard to understand and search codes. So amidst them, we can use this extension which enables selecting the tags on Frontend only." }, { "code": null, "e": 7616, "s": 7609, "text": "Picked" }, { "code": null, "e": 7630, "s": 7616, "text": "Python-Scrapy" }, { "code": null, "e": 7637, "s": 7630, "text": "Python" }, { "code": null, "e": 7735, "s": 7637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7767, "s": 7735, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7794, "s": 7767, "text": "Python Classes and Objects" }, { "code": null, "e": 7825, "s": 7794, "text": "Python | os.path.join() method" }, { "code": null, "e": 7846, "s": 7825, "text": "Python OOPs Concepts" }, { "code": null, "e": 7902, "s": 7846, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7925, "s": 7902, "text": "Introduction To PYTHON" }, { "code": null, "e": 7967, "s": 7925, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 8009, "s": 7967, "text": "Check if element exists in list in Python" }, { "code": null, "e": 8048, "s": 8009, "text": "Python | datetime.timedelta() function" } ]
Python | os.stat() method
26 May, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.stat() method in Python performs stat() system call on the specified path. This method is used to get status of the specified path. Syntax: os.stat(path) Parameter:path: A string or bytes object representing a valid path Return Type: This method returns a ‘stat_result’ object of class ‘os.stat_result’ which represents the status of specified path. The returned ‘stat-result’ object has following attributes: st_mode: It represents file type and file mode bits (permissions). st_ino: It represents the inode number on Unix and the file index on Windows platform. st_dev: It represents the identifier of the device on which this file resides. st_nlink: It represents the number of hard links. st_uid: It represents the user identifier of the file owner. st_gid: It represents the group identifier of the file owner. st_size: It represents the size of the file in bytes. st_atime: It represents the time of most recent access. It is expressed in seconds. st_mtime: It represents the time of most recent content modification. It is expressed in seconds. st_ctime: It represents the time of most recent metadata change on Unix and creation time on Windows. It is expressed in seconds. st_atime_ns: It is same as st_atime but the time is expressed in nanoseconds as an integer. st_mtime_ns: It is same as st_mtime but the time is expressed in nanoseconds as an integer. st_ctime_ns: It is same as st_ctime but the time is expressed in nanoseconds as an integer. st_blocks: It represents the number of 512-byte blocks allocated for file. st_rdev: It represents the type of device, if an inode device. st_flags: It represents the user defined flags for file. Note: Some attributes are platform dependent and are subject to availability. Code: Use of os.stat() method # Python program to explain os.stat() method # importing os module import os # pathpath = '/home/User/Documents/file.txt' # Get the status of# the specified pathstatus = os.stat(path) # Print the status# of the specified pathprint(status) os.stat_result(st_mode=33188, st_ino=795581, st_dev=2056, st_nlink=1, st_uid=1000, st_gid=1000, st_size=243, st_atime=1531567080, st_mtime=1530346690, st_ctime=1530346690) python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 382, "s": 247, "text": "os.stat() method in Python performs stat() system call on the specified path. This method is used to get status of the specified path." }, { "code": null, "e": 404, "s": 382, "text": "Syntax: os.stat(path)" }, { "code": null, "e": 471, "s": 404, "text": "Parameter:path: A string or bytes object representing a valid path" }, { "code": null, "e": 660, "s": 471, "text": "Return Type: This method returns a ‘stat_result’ object of class ‘os.stat_result’ which represents the status of specified path. The returned ‘stat-result’ object has following attributes:" }, { "code": null, "e": 727, "s": 660, "text": "st_mode: It represents file type and file mode bits (permissions)." }, { "code": null, "e": 814, "s": 727, "text": "st_ino: It represents the inode number on Unix and the file index on Windows platform." }, { "code": null, "e": 893, "s": 814, "text": "st_dev: It represents the identifier of the device on which this file resides." }, { "code": null, "e": 943, "s": 893, "text": "st_nlink: It represents the number of hard links." }, { "code": null, "e": 1004, "s": 943, "text": "st_uid: It represents the user identifier of the file owner." }, { "code": null, "e": 1066, "s": 1004, "text": "st_gid: It represents the group identifier of the file owner." }, { "code": null, "e": 1120, "s": 1066, "text": "st_size: It represents the size of the file in bytes." }, { "code": null, "e": 1204, "s": 1120, "text": "st_atime: It represents the time of most recent access. It is expressed in seconds." }, { "code": null, "e": 1302, "s": 1204, "text": "st_mtime: It represents the time of most recent content modification. It is expressed in seconds." }, { "code": null, "e": 1432, "s": 1302, "text": "st_ctime: It represents the time of most recent metadata change on Unix and creation time on Windows. It is expressed in seconds." }, { "code": null, "e": 1524, "s": 1432, "text": "st_atime_ns: It is same as st_atime but the time is expressed in nanoseconds as an integer." }, { "code": null, "e": 1616, "s": 1524, "text": "st_mtime_ns: It is same as st_mtime but the time is expressed in nanoseconds as an integer." }, { "code": null, "e": 1708, "s": 1616, "text": "st_ctime_ns: It is same as st_ctime but the time is expressed in nanoseconds as an integer." }, { "code": null, "e": 1783, "s": 1708, "text": "st_blocks: It represents the number of 512-byte blocks allocated for file." }, { "code": null, "e": 1846, "s": 1783, "text": "st_rdev: It represents the type of device, if an inode device." }, { "code": null, "e": 1903, "s": 1846, "text": "st_flags: It represents the user defined flags for file." }, { "code": null, "e": 1981, "s": 1903, "text": "Note: Some attributes are platform dependent and are subject to availability." }, { "code": null, "e": 2011, "s": 1981, "text": "Code: Use of os.stat() method" }, { "code": "# Python program to explain os.stat() method # importing os module import os # pathpath = '/home/User/Documents/file.txt' # Get the status of# the specified pathstatus = os.stat(path) # Print the status# of the specified pathprint(status)", "e": 2259, "s": 2011, "text": null }, { "code": null, "e": 2432, "s": 2259, "text": "os.stat_result(st_mode=33188, st_ino=795581, st_dev=2056, st_nlink=1, st_uid=1000,\nst_gid=1000, st_size=243, st_atime=1531567080, st_mtime=1530346690, st_ctime=1530346690)\n" }, { "code": null, "e": 2449, "s": 2432, "text": "python-os-module" }, { "code": null, "e": 2456, "s": 2449, "text": "Python" } ]
Minimum elements to be removed such that sum of adjacent elements is always even
15 Apr, 2021 Given an array of N integers. The task is to eliminate the minimum number of elements such that in the resulting array the sum of any two adjacent values is even. Examples: Input : arr[] = {1, 2, 3} Output : 1 Remove 2 from the array. Input : arr[] = {1, 3, 5, 4, 2} Output : 2 Remove 4 and 2. Approach: The sum of 2 numbers is even if either both of them is odd or both of them is even. This means for every pair of consecutive numbers that have the different parity, eliminate one of them.So, to make the adjacent elements sum even, either all elements should be odd or even. So the following greedy algorithm works: Go through all the elements in order. Count the odd and even elements in the array. Return the minimum count. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum number of eliminations// such that sum of all adjacent elements is evenint min_elimination(int n, int arr[]){ int countOdd = 0; // Stores the new value for (int i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2) countOdd++; // Return the minimum of even and // odd count return min(countOdd, n - countOdd);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << min_elimination(n, arr); return 0;} // Java implementation of the above approachclass GFG{ // Function to find minimum number of// eliminations such that sum of all// adjacent elements is evenstatic int min_elimination(int n, int arr[]){ int countOdd = 0; // Stores the new value for (int i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2 == 1) countOdd++; // Return the minimum of even // and odd count return Math.min(countOdd, n - countOdd);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 7, 9 }; int n = arr.length; System.out.println(min_elimination(n, arr));}} // This code is contributed by Code_Mech # Python 3 implementation of the# above approach # Function to find minimum number of# eliminations such that sum of all# adjacent elements is evendef min_elimination(n, arr): countOdd = 0 # Stores the new value for i in range(n): # Count odd numbers if (arr[i] % 2): countOdd += 1 # Return the minimum of even and # odd count return min(countOdd, n - countOdd) # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 7, 9] n = len(arr) print(min_elimination(n, arr)) # This code is contributed by# Surendra_Gangwar // C# implementation of the above approachusing System; class GFG{ // Function to find minimum number of// eliminations such that sum of all// adjacent elements is evenstatic int min_elimination(int n, int[] arr){ int countOdd = 0; // Stores the new value for (int i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2 == 1) countOdd++; // Return the minimum of even // and odd count return Math.Min(countOdd, n - countOdd);} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3, 7, 9 }; int n = arr.Length; Console.WriteLine(min_elimination(n, arr));}} // This code is contributed by Code_Mech <?php// PHP implementation of the above approach // Function to find minimum number of// eliminations such that sum of all// adjacent elements is evenfunction min_elimination($n, $arr){ $countOdd = 0; // Stores the new value for ($i = 0; $i < $n; $i++) // Count odd numbers if ($arr[$i] % 2 == 1) $countOdd++; // Return the minimum of even // and odd count return min($countOdd, $n - $countOdd);} // Driver code$arr = array(1, 2, 3, 7, 9);$n = sizeof($arr); echo(min_elimination($n, $arr)); // This code is contributed by Code_Mech?> <script> // Function to find minimum number of eliminations// such that sum of all adjacent elements is evenfunction min_elimination(n, arr){ let countOdd = 0; // Stores the new value for (let i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2) countOdd++; // Return the minimum of even and // odd count return Math.min(countOdd, n - countOdd);} // Driver code let arr= [1, 2, 3, 7, 9];let n = arr.length; document.write(min_elimination(n, arr)); </script> 1 Time Complexity: O(N ) Auxiliary Space: O(1) SURENDRA_GANGWAR Code_Mech ujjwalgoel1103 mohit kumar 29 array-traversal-question Marketing Arrays Arrays 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 Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Apr, 2021" }, { "code": null, "e": 216, "s": 53, "text": "Given an array of N integers. The task is to eliminate the minimum number of elements such that in the resulting array the sum of any two adjacent values is even." }, { "code": null, "e": 227, "s": 216, "text": "Examples: " }, { "code": null, "e": 349, "s": 227, "text": "Input : arr[] = {1, 2, 3}\nOutput : 1\nRemove 2 from the array.\n\nInput : arr[] = {1, 3, 5, 4, 2}\nOutput : 2\nRemove 4 and 2." }, { "code": null, "e": 674, "s": 349, "text": "Approach: The sum of 2 numbers is even if either both of them is odd or both of them is even. This means for every pair of consecutive numbers that have the different parity, eliminate one of them.So, to make the adjacent elements sum even, either all elements should be odd or even. So the following greedy algorithm works:" }, { "code": null, "e": 712, "s": 674, "text": "Go through all the elements in order." }, { "code": null, "e": 758, "s": 712, "text": "Count the odd and even elements in the array." }, { "code": null, "e": 784, "s": 758, "text": "Return the minimum count." }, { "code": null, "e": 837, "s": 784, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 841, "s": 837, "text": "C++" }, { "code": null, "e": 846, "s": 841, "text": "Java" }, { "code": null, "e": 854, "s": 846, "text": "Python3" }, { "code": null, "e": 857, "s": 854, "text": "C#" }, { "code": null, "e": 861, "s": 857, "text": "PHP" }, { "code": null, "e": 872, "s": 861, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum number of eliminations// such that sum of all adjacent elements is evenint min_elimination(int n, int arr[]){ int countOdd = 0; // Stores the new value for (int i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2) countOdd++; // Return the minimum of even and // odd count return min(countOdd, n - countOdd);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << min_elimination(n, arr); return 0;}", "e": 1500, "s": 872, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to find minimum number of// eliminations such that sum of all// adjacent elements is evenstatic int min_elimination(int n, int arr[]){ int countOdd = 0; // Stores the new value for (int i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2 == 1) countOdd++; // Return the minimum of even // and odd count return Math.min(countOdd, n - countOdd);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 7, 9 }; int n = arr.length; System.out.println(min_elimination(n, arr));}} // This code is contributed by Code_Mech", "e": 2168, "s": 1500, "text": null }, { "code": "# Python 3 implementation of the# above approach # Function to find minimum number of# eliminations such that sum of all# adjacent elements is evendef min_elimination(n, arr): countOdd = 0 # Stores the new value for i in range(n): # Count odd numbers if (arr[i] % 2): countOdd += 1 # Return the minimum of even and # odd count return min(countOdd, n - countOdd) # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 7, 9] n = len(arr) print(min_elimination(n, arr)) # This code is contributed by# Surendra_Gangwar", "e": 2748, "s": 2168, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to find minimum number of// eliminations such that sum of all// adjacent elements is evenstatic int min_elimination(int n, int[] arr){ int countOdd = 0; // Stores the new value for (int i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2 == 1) countOdd++; // Return the minimum of even // and odd count return Math.Min(countOdd, n - countOdd);} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3, 7, 9 }; int n = arr.Length; Console.WriteLine(min_elimination(n, arr));}} // This code is contributed by Code_Mech", "e": 3414, "s": 2748, "text": null }, { "code": "<?php// PHP implementation of the above approach // Function to find minimum number of// eliminations such that sum of all// adjacent elements is evenfunction min_elimination($n, $arr){ $countOdd = 0; // Stores the new value for ($i = 0; $i < $n; $i++) // Count odd numbers if ($arr[$i] % 2 == 1) $countOdd++; // Return the minimum of even // and odd count return min($countOdd, $n - $countOdd);} // Driver code$arr = array(1, 2, 3, 7, 9);$n = sizeof($arr); echo(min_elimination($n, $arr)); // This code is contributed by Code_Mech?>", "e": 3994, "s": 3414, "text": null }, { "code": "<script> // Function to find minimum number of eliminations// such that sum of all adjacent elements is evenfunction min_elimination(n, arr){ let countOdd = 0; // Stores the new value for (let i = 0; i < n; i++) // Count odd numbers if (arr[i] % 2) countOdd++; // Return the minimum of even and // odd count return Math.min(countOdd, n - countOdd);} // Driver code let arr= [1, 2, 3, 7, 9];let n = arr.length; document.write(min_elimination(n, arr)); </script>", "e": 4502, "s": 3994, "text": null }, { "code": null, "e": 4504, "s": 4502, "text": "1" }, { "code": null, "e": 4529, "s": 4506, "text": "Time Complexity: O(N )" }, { "code": null, "e": 4551, "s": 4529, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4568, "s": 4551, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 4578, "s": 4568, "text": "Code_Mech" }, { "code": null, "e": 4593, "s": 4578, "text": "ujjwalgoel1103" }, { "code": null, "e": 4608, "s": 4593, "text": "mohit kumar 29" }, { "code": null, "e": 4633, "s": 4608, "text": "array-traversal-question" }, { "code": null, "e": 4643, "s": 4633, "text": "Marketing" }, { "code": null, "e": 4650, "s": 4643, "text": "Arrays" }, { "code": null, "e": 4657, "s": 4650, "text": "Arrays" }, { "code": null, "e": 4755, "s": 4657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4823, "s": 4755, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 4867, "s": 4823, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 4899, "s": 4867, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4947, "s": 4899, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 4961, "s": 4947, "text": "Linear Search" }, { "code": null, "e": 5046, "s": 4961, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 5069, "s": 5046, "text": "Introduction to Arrays" }, { "code": null, "e": 5125, "s": 5069, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 5152, "s": 5125, "text": "Subset Sum Problem | DP-25" } ]
Python OpenCV – Smoothing and Blurring
05 Jan, 2022 In this article, we are going to learn about smoothing and blurring with python-OpenCV. When we are dealing with images at some points the images will be crisper and sharper which we need to smoothen or blur to get a clean image, or sometimes the image will be with a really bad edge which also we need to smooth it down to make the image usable. In OpenCV, we got more than one method to smooth or blur an image, let’s discuss them one by one. In this method of smoothing, we have complete flexibility over the filtering process because we will be using our custom-made kernel [a simple 2d matrix of NumPy array which helps us to process the image by convolving with the image pixel by pixel]. A kernel basically will give a specific weight for each pixel in an image and sum up the weighted neighbor pixels to form a pixel, with this method we will be able to compress the pixels in an image and thus we can reduce the clarity of an image, By this method, we can able to smoothen or blur an image easily. Note: By using these kernels [2d matrices] we can perform many functions like sharpening and edge detecting an image. But remember each process has a different kernel i.e., different values of matrices. The kernel we are going to use in this article is a 5 by 5 averaging kernel which is basically a matrix of ones which in whole divided by 25, Which will look like, To smoothen an image with a custom-made kernel we are going to use a function called filter2D() which basically helps us to convolve a custom-made kernel with an image to achieve different image filters like sharpening and blurring and more. Syntax: filter2D(sourceImage, ddepth, kernel) Code: Python3 # Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Creating the kernel with numpykernel2 = np.ones((5, 5), np.float32)/25 # Applying the filterimg = cv2.filter2D(src=image, ddepth=-1, kernel=kernel2) # showing the imagecv2.imshow('Original', image)cv2.imshow('Kernel Blur', img) cv2.waitKey()cv2.destroyAllWindows() Output: OpenCV comes with many prebuilt blurring and smoothing functions let us see them in brief, Syntax: cv2.blur(image, shapeOfTheKernel) Image– The image you need to smoothen shapeOfTheKernel– The shape of the matrix-like 3 by 3 / 5 by 5 The averaging method is very similar to the 2d convolution method as it is following the same rules to smoothen or blur an image and uses the same type of kernel which will basically set the center pixel’s value to the average of the kernel weighted surrounding pixels. And by this, we can greatly reduce the noise of the image by reducing the clarity of an image by replacing the group of pixels with similar values which is basically similar color. We can greatly reduce the noise of the image and smoothen the image. The kernel we are using for this method is the desired shape of a matrix with all the values as “1” and the whole matrix is divided by the number of values in the respective shape of the matrix [which is basically averaging the kernel weighted values in the pixel range]. The kernel we used in this example is, Code: Python3 # Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filteraverageBlur = cv2.blur(image, (5, 5)) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Average blur', averageBlur) cv2.waitKey()cv2.destroyAllWindows() Output: Syntax: cv2. GaussianBlur(image, shapeOfTheKernel, sigmaX ) Image– the image you need to blur shapeOfTheKernel– The shape of the matrix-like 3 by 3 / 5 by 5 sigmaX– The Gaussian kernel standard deviation which is the default set to 0 In a gaussian blur, instead of using a box filter consisting of similar values inside the kernel which is a simple mean we are going to use a weighted mean. In this type of kernel, the values near the center pixel will have a higher weight. With this type of blurs, we will probably get a less blurred image but a natural blurred image which will look more natural because it handles the edge values very well. Instead of averaging the weighted sum of the pixels here, we will divide it with a specific value which is 16 in the case of a 3 by 3 shaped kernel which will look like this. Note: We can achieve the same result when we use this exact same kernel in the filter2D() function but in this case, we don’t need to create the kernel because this function automatically will do it for us. Code: Python3 # Importing the moduleimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filtergaussian = cv2.GaussianBlur(image, (3, 3), 0) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Gaussian blur', gaussian) cv2.waitKey()cv2.destroyAllWindows() Output: Syntax: cv. medianBlur(image, kernel size) Image– The image we need to apply the smoothening KernelSize– the size of the kernel as it always takes a square matrix the value must be a positive integer more than 2. Note: There are no specific kernel values for this method. In this method of smoothing, we will simply take the median of all the pixels inside the kernel window and replace the center value with this value. The one positive of this method over the gaussian and box blur is in these two cases the replaced center value may contain a pixel value that is not even present in the image which will make the image’s color different and weird to look, but in case of a median blur though it takes the median of the values that are already present in the image it will look a lot more natural. Code: Python3 # Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filtermedianBlur = cv2.medianBlur(image, 9) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Median blur', medianBlur) cv2.waitKey()cv2.destroyAllWindows() Output: Syntax: cv2.bilateralFilter(image, diameter, sigmaColor, sigmaSpace) Image– The image we need to apply the smoothening Diameter– similar to the size of the kernel SigmaColor– The number of colors to be considered in the given range of pixels [the higher value represents the increase in the number of colors in the given area of pixels]—Should not keep very high SigmaSpace – the space between the biased pixel and the neighbor pixel higher value means the pixels far out from the pixel will manipulate in the pixel value The smoothening methods we saw earlier are fast but we might end up losing the edges of the image which is not so good. But by using this method, this function concerns more about the edges and smoothens the image by preserving the images. This is achieved by performing two gaussian distributions. This might be very slow while comparing to the other methods we discussed so far. Code: Python3 # Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filterbilateral = cv2.bilateralFilter(image, 9, 75, 75) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Bilateral blur', bilateral) cv2.waitKey()cv2.destroyAllWindows() Output: sumitgumber28 simmytarika5 Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jan, 2022" }, { "code": null, "e": 116, "s": 28, "text": "In this article, we are going to learn about smoothing and blurring with python-OpenCV." }, { "code": null, "e": 473, "s": 116, "text": "When we are dealing with images at some points the images will be crisper and sharper which we need to smoothen or blur to get a clean image, or sometimes the image will be with a really bad edge which also we need to smooth it down to make the image usable. In OpenCV, we got more than one method to smooth or blur an image, let’s discuss them one by one." }, { "code": null, "e": 1037, "s": 473, "text": "In this method of smoothing, we have complete flexibility over the filtering process because we will be using our custom-made kernel [a simple 2d matrix of NumPy array which helps us to process the image by convolving with the image pixel by pixel]. A kernel basically will give a specific weight for each pixel in an image and sum up the weighted neighbor pixels to form a pixel, with this method we will be able to compress the pixels in an image and thus we can reduce the clarity of an image, By this method, we can able to smoothen or blur an image easily. " }, { "code": null, "e": 1404, "s": 1037, "text": "Note: By using these kernels [2d matrices] we can perform many functions like sharpening and edge detecting an image. But remember each process has a different kernel i.e., different values of matrices. The kernel we are going to use in this article is a 5 by 5 averaging kernel which is basically a matrix of ones which in whole divided by 25, Which will look like," }, { "code": null, "e": 1646, "s": 1404, "text": "To smoothen an image with a custom-made kernel we are going to use a function called filter2D() which basically helps us to convolve a custom-made kernel with an image to achieve different image filters like sharpening and blurring and more." }, { "code": null, "e": 1692, "s": 1646, "text": "Syntax: filter2D(sourceImage, ddepth, kernel)" }, { "code": null, "e": 1698, "s": 1692, "text": "Code:" }, { "code": null, "e": 1706, "s": 1698, "text": "Python3" }, { "code": "# Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Creating the kernel with numpykernel2 = np.ones((5, 5), np.float32)/25 # Applying the filterimg = cv2.filter2D(src=image, ddepth=-1, kernel=kernel2) # showing the imagecv2.imshow('Original', image)cv2.imshow('Kernel Blur', img) cv2.waitKey()cv2.destroyAllWindows()", "e": 2076, "s": 1706, "text": null }, { "code": null, "e": 2084, "s": 2076, "text": "Output:" }, { "code": null, "e": 2175, "s": 2084, "text": "OpenCV comes with many prebuilt blurring and smoothing functions let us see them in brief," }, { "code": null, "e": 2217, "s": 2175, "text": "Syntax: cv2.blur(image, shapeOfTheKernel)" }, { "code": null, "e": 2255, "s": 2217, "text": "Image– The image you need to smoothen" }, { "code": null, "e": 2318, "s": 2255, "text": "shapeOfTheKernel– The shape of the matrix-like 3 by 3 / 5 by 5" }, { "code": null, "e": 3150, "s": 2318, "text": "The averaging method is very similar to the 2d convolution method as it is following the same rules to smoothen or blur an image and uses the same type of kernel which will basically set the center pixel’s value to the average of the kernel weighted surrounding pixels. And by this, we can greatly reduce the noise of the image by reducing the clarity of an image by replacing the group of pixels with similar values which is basically similar color. We can greatly reduce the noise of the image and smoothen the image. The kernel we are using for this method is the desired shape of a matrix with all the values as “1” and the whole matrix is divided by the number of values in the respective shape of the matrix [which is basically averaging the kernel weighted values in the pixel range]. The kernel we used in this example is," }, { "code": null, "e": 3156, "s": 3150, "text": "Code:" }, { "code": null, "e": 3164, "s": 3156, "text": "Python3" }, { "code": "# Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filteraverageBlur = cv2.blur(image, (5, 5)) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Average blur', averageBlur) cv2.waitKey()cv2.destroyAllWindows()", "e": 3451, "s": 3164, "text": null }, { "code": null, "e": 3459, "s": 3451, "text": "Output:" }, { "code": null, "e": 3519, "s": 3459, "text": "Syntax: cv2. GaussianBlur(image, shapeOfTheKernel, sigmaX )" }, { "code": null, "e": 3553, "s": 3519, "text": "Image– the image you need to blur" }, { "code": null, "e": 3616, "s": 3553, "text": "shapeOfTheKernel– The shape of the matrix-like 3 by 3 / 5 by 5" }, { "code": null, "e": 3693, "s": 3616, "text": "sigmaX– The Gaussian kernel standard deviation which is the default set to 0" }, { "code": null, "e": 4279, "s": 3693, "text": "In a gaussian blur, instead of using a box filter consisting of similar values inside the kernel which is a simple mean we are going to use a weighted mean. In this type of kernel, the values near the center pixel will have a higher weight. With this type of blurs, we will probably get a less blurred image but a natural blurred image which will look more natural because it handles the edge values very well. Instead of averaging the weighted sum of the pixels here, we will divide it with a specific value which is 16 in the case of a 3 by 3 shaped kernel which will look like this." }, { "code": null, "e": 4486, "s": 4279, "text": "Note: We can achieve the same result when we use this exact same kernel in the filter2D() function but in this case, we don’t need to create the kernel because this function automatically will do it for us." }, { "code": null, "e": 4492, "s": 4486, "text": "Code:" }, { "code": null, "e": 4500, "s": 4492, "text": "Python3" }, { "code": "# Importing the moduleimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filtergaussian = cv2.GaussianBlur(image, (3, 3), 0) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Gaussian blur', gaussian) cv2.waitKey()cv2.destroyAllWindows()", "e": 4792, "s": 4500, "text": null }, { "code": null, "e": 4800, "s": 4792, "text": "Output:" }, { "code": null, "e": 4843, "s": 4800, "text": "Syntax: cv. medianBlur(image, kernel size)" }, { "code": null, "e": 4893, "s": 4843, "text": "Image– The image we need to apply the smoothening" }, { "code": null, "e": 5013, "s": 4893, "text": "KernelSize– the size of the kernel as it always takes a square matrix the value must be a positive integer more than 2." }, { "code": null, "e": 5072, "s": 5013, "text": "Note: There are no specific kernel values for this method." }, { "code": null, "e": 5600, "s": 5072, "text": "In this method of smoothing, we will simply take the median of all the pixels inside the kernel window and replace the center value with this value. The one positive of this method over the gaussian and box blur is in these two cases the replaced center value may contain a pixel value that is not even present in the image which will make the image’s color different and weird to look, but in case of a median blur though it takes the median of the values that are already present in the image it will look a lot more natural." }, { "code": null, "e": 5606, "s": 5600, "text": "Code:" }, { "code": null, "e": 5614, "s": 5606, "text": "Python3" }, { "code": "# Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filtermedianBlur = cv2.medianBlur(image, 9) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Median blur', medianBlur) cv2.waitKey()cv2.destroyAllWindows()", "e": 5899, "s": 5614, "text": null }, { "code": null, "e": 5907, "s": 5899, "text": "Output:" }, { "code": null, "e": 5976, "s": 5907, "text": "Syntax: cv2.bilateralFilter(image, diameter, sigmaColor, sigmaSpace)" }, { "code": null, "e": 6026, "s": 5976, "text": "Image– The image we need to apply the smoothening" }, { "code": null, "e": 6070, "s": 6026, "text": "Diameter– similar to the size of the kernel" }, { "code": null, "e": 6270, "s": 6070, "text": "SigmaColor– The number of colors to be considered in the given range of pixels [the higher value represents the increase in the number of colors in the given area of pixels]—Should not keep very high" }, { "code": null, "e": 6429, "s": 6270, "text": "SigmaSpace – the space between the biased pixel and the neighbor pixel higher value means the pixels far out from the pixel will manipulate in the pixel value" }, { "code": null, "e": 6812, "s": 6429, "text": "The smoothening methods we saw earlier are fast but we might end up losing the edges of the image which is not so good. But by using this method, this function concerns more about the edges and smoothens the image by preserving the images. This is achieved by performing two gaussian distributions. This might be very slow while comparing to the other methods we discussed so far. " }, { "code": null, "e": 6818, "s": 6812, "text": "Code:" }, { "code": null, "e": 6826, "s": 6818, "text": "Python3" }, { "code": "# Importing the modulesimport cv2import numpy as np # Reading the imageimage = cv2.imread('image.png') # Applying the filterbilateral = cv2.bilateralFilter(image, 9, 75, 75) # Showing the imagecv2.imshow('Original', image)cv2.imshow('Bilateral blur', bilateral) cv2.waitKey()cv2.destroyAllWindows()", "e": 7125, "s": 6826, "text": null }, { "code": null, "e": 7133, "s": 7125, "text": "Output:" }, { "code": null, "e": 7147, "s": 7133, "text": "sumitgumber28" }, { "code": null, "e": 7160, "s": 7147, "text": "simmytarika5" }, { "code": null, "e": 7167, "s": 7160, "text": "Picked" }, { "code": null, "e": 7181, "s": 7167, "text": "Python-OpenCV" }, { "code": null, "e": 7188, "s": 7181, "text": "Python" }, { "code": null, "e": 7286, "s": 7188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7318, "s": 7286, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7345, "s": 7318, "text": "Python Classes and Objects" }, { "code": null, "e": 7376, "s": 7345, "text": "Python | os.path.join() method" }, { "code": null, "e": 7397, "s": 7376, "text": "Python OOPs Concepts" }, { "code": null, "e": 7453, "s": 7397, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7476, "s": 7453, "text": "Introduction To PYTHON" }, { "code": null, "e": 7518, "s": 7476, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7560, "s": 7518, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7599, "s": 7560, "text": "Python | datetime.timedelta() function" } ]
Python – tensorflow.constant()
26 Jun, 2020 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. constant() is used to create a Tensor from tensor like objects like list. Syntax: tensorflow.constant( value, dtype, shape, name ) Parameters: value: It is the value that needed to be converted to Tensor. dtype(optional): It defines the type of the output Tensor. shape(optional): It defines the dimension of output Tensor. name(optiona): It defines the name for the operation. Returns: It returns a Tensor. Example 1: From Python list Python3 # Importing the libraryimport tensorflow as tf # Initializing the inputl = [1, 2, 3, 4] # Printing the inputprint('l: ', l) # Calculating resultx = tf.constant(l) # Printing the resultprint('x: ', x) Output: l: [1, 2, 3, 4] x: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32) Example 2: From Python tuple Python3 # Importing the libraryimport tensorflow as tf # Initializing the inputl = (1, 2, 3, 4) # Printing the inputprint('l: ', l) # Calculating resultx = tf.constant(l, dtype = tf.float64) # Printing the resultprint('x: ', x) Output: l: (1, 2, 3, 4) x: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64) Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2020" }, { "code": null, "e": 159, "s": 28, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks." }, { "code": null, "e": 233, "s": 159, "text": "constant() is used to create a Tensor from tensor like objects like list." }, { "code": null, "e": 290, "s": 233, "text": "Syntax: tensorflow.constant( value, dtype, shape, name )" }, { "code": null, "e": 302, "s": 290, "text": "Parameters:" }, { "code": null, "e": 364, "s": 302, "text": "value: It is the value that needed to be converted to Tensor." }, { "code": null, "e": 423, "s": 364, "text": "dtype(optional): It defines the type of the output Tensor." }, { "code": null, "e": 483, "s": 423, "text": "shape(optional): It defines the dimension of output Tensor." }, { "code": null, "e": 537, "s": 483, "text": "name(optiona): It defines the name for the operation." }, { "code": null, "e": 567, "s": 537, "text": "Returns: It returns a Tensor." }, { "code": null, "e": 595, "s": 567, "text": "Example 1: From Python list" }, { "code": null, "e": 603, "s": 595, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the inputl = [1, 2, 3, 4] # Printing the inputprint('l: ', l) # Calculating resultx = tf.constant(l) # Printing the resultprint('x: ', x)", "e": 809, "s": 603, "text": null }, { "code": null, "e": 817, "s": 809, "text": "Output:" }, { "code": null, "e": 887, "s": 817, "text": "l: [1, 2, 3, 4]\nx: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)\n\n" }, { "code": null, "e": 916, "s": 887, "text": "Example 2: From Python tuple" }, { "code": null, "e": 924, "s": 916, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the inputl = (1, 2, 3, 4) # Printing the inputprint('l: ', l) # Calculating resultx = tf.constant(l, dtype = tf.float64) # Printing the resultprint('x: ', x)", "e": 1150, "s": 924, "text": null }, { "code": null, "e": 1158, "s": 1150, "text": "Output:" }, { "code": null, "e": 1235, "s": 1158, "text": "l: (1, 2, 3, 4)\nx: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)\n\n\n" }, { "code": null, "e": 1253, "s": 1235, "text": "Python-Tensorflow" }, { "code": null, "e": 1260, "s": 1253, "text": "Python" }, { "code": null, "e": 1358, "s": 1260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1390, "s": 1358, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1417, "s": 1390, "text": "Python Classes and Objects" }, { "code": null, "e": 1448, "s": 1417, "text": "Python | os.path.join() method" }, { "code": null, "e": 1471, "s": 1448, "text": "Introduction To PYTHON" }, { "code": null, "e": 1492, "s": 1471, "text": "Python OOPs Concepts" }, { "code": null, "e": 1548, "s": 1492, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1590, "s": 1548, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1632, "s": 1590, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1671, "s": 1632, "text": "Python | Get unique values from a list" } ]
Plotly with Pandas and Cufflinks
Pandas is a very popular library in Python for data analysis. It also has its own plot function support. However, Pandas plots don't provide interactivity in visualization. Thankfully, plotly's interactive and dynamic plots can be built using Pandas dataframe objects. We start by building a Dataframe from simple list objects. data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]] df = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float) The dataframe columns are used as data values for x and y properties of graph object traces. Here, we will generate a bar trace using name and marks columns. trace = go.Bar(x = df.name, y = df.marks) fig = go.Figure(data = [trace]) iplot(fig) A simple bar plot will be displayed in Jupyter notebook as below − Plotly is built on top of d3.js and is specifically a charting library which can be used directly with Pandas dataframes using another library named Cufflinks. If not already available, install cufflinks package by using your favourite package manager like pip as given below − pip install cufflinks or conda install -c conda-forge cufflinks-py First, import cufflinks along with other libraries such as Pandas and numpy which can configure it for offline use. import cufflinks as cf cf.go_offline() Now, you can directly use Pandas dataframe to display various kinds of plots without having to use trace and figure objects from graph_objs module as we have been doing previously. df.iplot(kind = 'bar', x = 'name', y = 'marks') Bar plot, very similar to earlier one will be displayed as given below − Instead of using Python lists for constructing dataframe, it can be populated by data in different types of databases. For example, data from a CSV file, SQLite database table or mysql database table can be fetched into a Pandas dataframe, which eventually is subjected to plotly graphs using Figure object or Cufflinks interface. To fetch data from CSV file, we can use read_csv() function from Pandas library. import pandas as pd df = pd.read_csv('sample-data.csv') If data is available in SQLite database table, it can be retrieved using SQLAlchemy library as follows − import pandas as pd from sqlalchemy import create_engine disk_engine = create_engine('sqlite:///mydb.db') df = pd.read_sql_query('SELECT name,age,marks', disk_engine) On the other hand, data from MySQL database is retrieved in a Pandas dataframe as follows − import pymysql import pandas as pd conn = pymysql.connect(host = "localhost", user = "root", passwd = "xxxx", db = "mydb") cursor = conn.cursor() cursor.execute('select name,age,marks') rows = cursor.fetchall() df = pd.DataFrame( [[ij for ij in i] for i in rows] ) df.rename(columns = {0: 'Name', 1: 'age', 2: 'marks'}, inplace = True) 12 Lectures 53 mins Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2629, "s": 2360, "text": "Pandas is a very popular library in Python for data analysis. It also has its own plot function support. However, Pandas plots don't provide interactivity in visualization. Thankfully, plotly's interactive and dynamic plots can be built using Pandas dataframe objects." }, { "code": null, "e": 2688, "s": 2629, "text": "We start by building a Dataframe from simple list objects." }, { "code": null, "e": 2848, "s": 2688, "text": "data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]]\ndf = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float)\n" }, { "code": null, "e": 3006, "s": 2848, "text": "The dataframe columns are used as data values for x and y properties of graph object traces. Here, we will generate a bar trace using name and marks columns." }, { "code": null, "e": 3092, "s": 3006, "text": "trace = go.Bar(x = df.name, y = df.marks)\nfig = go.Figure(data = [trace])\niplot(fig)\n" }, { "code": null, "e": 3159, "s": 3092, "text": "A simple bar plot will be displayed in Jupyter notebook as below −" }, { "code": null, "e": 3319, "s": 3159, "text": "Plotly is built on top of d3.js and is specifically a charting library which can be used directly with Pandas dataframes using another library named Cufflinks." }, { "code": null, "e": 3437, "s": 3319, "text": "If not already available, install cufflinks package by using your favourite package manager like pip as given below −" }, { "code": null, "e": 3505, "s": 3437, "text": "pip install cufflinks\nor\nconda install -c conda-forge cufflinks-py\n" }, { "code": null, "e": 3621, "s": 3505, "text": "First, import cufflinks along with other libraries such as Pandas and numpy which can configure it for offline use." }, { "code": null, "e": 3661, "s": 3621, "text": "import cufflinks as cf\ncf.go_offline()\n" }, { "code": null, "e": 3842, "s": 3661, "text": "Now, you can directly use Pandas dataframe to display various kinds of plots without having to use trace and figure objects from graph_objs module as we have been doing previously." }, { "code": null, "e": 3891, "s": 3842, "text": "df.iplot(kind = 'bar', x = 'name', y = 'marks')\n" }, { "code": null, "e": 3964, "s": 3891, "text": "Bar plot, very similar to earlier one will be displayed as given below −" }, { "code": null, "e": 4295, "s": 3964, "text": "Instead of using Python lists for constructing dataframe, it can be populated by data in different types of databases. For example, data from a CSV file, SQLite database table or mysql database table can be fetched into a Pandas dataframe, which eventually is subjected to plotly graphs using Figure object or Cufflinks interface." }, { "code": null, "e": 4376, "s": 4295, "text": "To fetch data from CSV file, we can use read_csv() function from Pandas library." }, { "code": null, "e": 4432, "s": 4376, "text": "import pandas as pd\ndf = pd.read_csv('sample-data.csv')" }, { "code": null, "e": 4537, "s": 4432, "text": "If data is available in SQLite database table, it can be retrieved using SQLAlchemy library as follows −" }, { "code": null, "e": 4704, "s": 4537, "text": "import pandas as pd\nfrom sqlalchemy import create_engine\ndisk_engine = create_engine('sqlite:///mydb.db')\ndf = pd.read_sql_query('SELECT name,age,marks', disk_engine)" }, { "code": null, "e": 4796, "s": 4704, "text": "On the other hand, data from MySQL database is retrieved in a Pandas dataframe as follows −" }, { "code": null, "e": 5132, "s": 4796, "text": "import pymysql\nimport pandas as pd\nconn = pymysql.connect(host = \"localhost\", user = \"root\", passwd = \"xxxx\", db = \"mydb\")\ncursor = conn.cursor()\ncursor.execute('select name,age,marks')\nrows = cursor.fetchall()\ndf = pd.DataFrame( [[ij for ij in i] for i in rows] )\ndf.rename(columns = {0: 'Name', 1: 'age', 2: 'marks'}, inplace = True)" }, { "code": null, "e": 5164, "s": 5132, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5184, "s": 5164, "text": " Pranjal Srivastava" }, { "code": null, "e": 5191, "s": 5184, "text": " Print" }, { "code": null, "e": 5202, "s": 5191, "text": " Add Notes" } ]
Custom Coloring Dendrogram Ends in R | by Matt Selensky | Towards Data Science
As a graduate student studying microbial community data, most of the projects I work on involve some sort of clustering analysis. For one of them, I wanted to color the ends of a dendrogram by a variable from my metadata, to visualize whether that variable followed the clustering as part of another figure. There exist excellent packages in R like ggdendro that allow you to either plot colored bars under dendrograms to represent how groups cluster or color the terminal segments by the cluster itself. That said, I still haven’t found an easy way to change the color of the terminal ends of the dendrogram itself based on user-defined metadata, which I personally think can be more aesthetically pleasing in some situations. This tutorial describes how I did it and provides reproducible code if you are hoping to do the same thing! Before I start, what is a dendrogram, anyway? A dendrogram is a graphical representation of hierarchical clustering. Clusters can be constructed in different ways (i.e., top-down or bottom-up), most commonly in R through the application of hclust() on a distance matrix. Dendrograms are built by connecting nodes to branches or other nodes, resulting in a tree-like figure that shows how individual things are related to each other based on multiple variables. Let’s say we want to compare how individual irises cluster from the well-known R-core data set. This dataframe contains four numeric vectors (Sepal.Length, Sepal.Width, Petal.Length, and Petal.Width) as well as one character vector (Species). We could easily construct and plot a dendrogram incorporating all these numeric data with base R, but what if we want to color the terminal segments by the species of iris to visualize whether Species follows the clustering determined by hclust()? For this tutorial, you’ll want to load three R packages: tidyverse for data manipulation and visualization, ggdendro to extract dendrogram segment data into a dataframe, and RColorBrewer to make an automatic custom color palette for your dendrogram ends. If you would like to make your dendrogram interactive, be sure to load plotly as well. pacman::p_load(tidyverse, ggdendro, RColorBrewer, plotly) Now we’ll want to load the irisdataframe into our environment. As bioinformaticians, we typically have sample names mapped to each observation, so we will want to create our own (sample_name) right at the start. With microbial community data, My workflow essentially involves two objects: a giant matrix of ASV (amplicon sequence variant; a term used to describe taxonomy based on DNA sequence similarity) abundances by sample_name, and metadata associated with each sample. To simulate this, we will separate iris into numeric_data, from which we will calculate distance and construct a dendrogram, and metadata, which for our purposes will simply consist of the species of iris for each sample_name. For this workflow, it is important to have a sample_name identifier for each observation; it will be the basis of merging everything at the end. # label rows with unique sample_namedat <- iris %>% mutate(sample_name = paste(“iris”, seq(1:nrow(iris)), sep = “_”)) # create unique sample ID# save non-numeric metadata in separate dataframemetadata <- dat %>% select(sample_name, Species)# extract numeric vectors for distance matrixnumeric_data <- dat %>% select(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, sample_name)# check data head(numeric_data) Before we make the dendrogram, we will calculate a distance matrix based on numeric_data using dist(). It is good practice to normalize your data before doing this calculation; I will therefore normalize all values within a vector on a scale from 0 to 1. After we do that, we can create a distance matrix (dist_matrix) and generate a dendrogram from our normalized data. # normalize data to values from 0 to 1 numeric_data_norm <- numeric_data %>% select(sample_name, everything()) %>% pivot_longer(cols = 2:ncol(.), values_to = “value”, names_to = “type”) %>% group_by(type) %>% mutate(value_norm = (value-min(value))/(max(value)-min(value))) %>% # normalize data to values 0–1 select(sample_name, value_norm) %>% pivot_wider(names_from = “type”, values_from = “value_norm”) %>% column_to_rownames(“sample_name”)# create dendrogram from distance matrix of normalized datadist_matrix <- dist(numeric_data_norm, method = “euclidean”)dendrogram <- as.dendrogram(hclust(dist_matrix, method = “complete”)) Now let’s quickly take a look at what our dendrogram looks like using base R: plot(dendrogram) Okay, it’s not very pretty, but bear with me. This is a useful visual to show how we will extract the coordinate data from the dendrogram object with ggdendro::dendro_data() to make a better figure. Every dendrogram is plotted by adding individual segments between points on an x and y grid. When we apply dendro_data() and look at the extracted segment data, we see there are four vectors for every dendrogram: x, y, xend, and yend. Every horizontal or vertical line you see in the base R figure is ultimately constructed from one row of the following dataframe: # extract dendrogram segment datadendrogram_data <- dendro_data(dendrogram)dendrogram_segments <- dendrogram_data$segments # contains all dendrogram segment datahead(dendrogram_segments) We will split these coordinate data into two dataframes: dendrogram_segments, containing all the segments, and dendrogram_ends, containing only the terminal branches of the figure. As the plot above shows, when the value in the y-direction as 0 (i.e., yend == 0), only those single segments at the bottom of the plot are included: # get terminal dendrogram segmentsdendrogram_ends <- dendrogram_segments %>% filter(yend == 0) %>% # filter for terminal dendrogram ends left_join(dendrogram_data$labels, by = “x”) %>% # .$labels contains the row names from dist_matrix (i.e., sample_name) rename(sample_name = label) %>% left_join(metadata, by = “sample_name”) # dataframe now contains only terminal dendrogram segments and merged metadata associated with each iris Looking at dendrogram_ends, we now have a dataframe with vectors containing the dendrogram coordinate data matched to the sample_name andSpecies vectors. We are now ready to start plotting in ggplot2! head(dendrogram_ends) If you want to dynamically create a list of colors based on how many unique variables the metadata vector of interest contains, you can run this code. In this example, our metadata only contains three species of iris, so this could be done manually fairly quickly. However, if the number of unique metadata variables in your dataset is more than that, as is common with microbial community data, chances are you might want to automate this process. # Generate custom color palette for dendrogram ends based on metadata variableunique_vars <- levels(factor(dendrogram_ends$Species)) %>% as.data.frame() %>% rownames_to_column(“row_id”) # count number of unique variablescolor_count <- length(unique(unique_vars$.))# get RColorBrewer paletteget_palette <- colorRampPalette(brewer.pal(n = 8, name = “Set1”))# produce RColorBrewer palette based on number of unique variables in metadata:palette <- get_palette(color_count) %>% as.data.frame() %>% rename(“color” = “.”) %>% rownames_to_column(var = “row_id”)color_list <- left_join(unique_vars, palette, by = “row_id”) %>% select(-row_id)species_color <- as.character(color_list$color)names(species_color) <- color_list$. If you don’t want to bother with the above code for this tutorial, you could just manually create a named character vector as an alternative: # Alternatively, create a custom named vector for iris species color:species_color <- c(“setosa” = “#E41A1C”, “versicolor” = “#CB6651”, “virginica” = “#F781BF”) Now it’s time to plot our dendrogram! You will want to define two geoms for geom_segment: one plotting all the segment data extracted from Step 4, which are uncolored, and one for just the terminal branches of the dendrogram, which is what we will color with species_color from the previous step. If you wrap this plot with plotly (see below), I recommend adding an extra text aesthetic to control which information will display on your output. p <- ggplot() + geom_segment(data = dendrogram_segments, aes(x=x, y=y, xend=xend, yend=yend)) + geom_segment(data = dendrogram_ends, aes(x=x, y=y.x, xend=xend, yend=yend, color = Species, text = paste(‘sample name: ‘, sample_name, ‘<br>’, ‘species: ‘, Species))) + # test aes is for plotly scale_color_manual(values = species_color) + scale_y_reverse() + coord_flip() + theme_bw() + theme(legend.position = “none”) + ylab(“Distance”) + # flipped x and y coordinates for aesthetic reasons ggtitle(“Iris dendrogram”) p If you want to get really fancy, you can wrap your ggplot with plotly to make your dendrogram interactive! Be sure to specify tooltip = “text” to control which information is displayed. ggplotly(p, tooltip = “text”) And there you have it — dendrogram ends dynamically colored by a variable in your metadata! As we can see, the species of iris does seem to follow the hierarchical clustering determined by hclust(), which can inform further tests done in your exploratory analysis pipeline.
[ { "code": null, "e": 677, "s": 172, "text": "As a graduate student studying microbial community data, most of the projects I work on involve some sort of clustering analysis. For one of them, I wanted to color the ends of a dendrogram by a variable from my metadata, to visualize whether that variable followed the clustering as part of another figure. There exist excellent packages in R like ggdendro that allow you to either plot colored bars under dendrograms to represent how groups cluster or color the terminal segments by the cluster itself." }, { "code": null, "e": 1008, "s": 677, "text": "That said, I still haven’t found an easy way to change the color of the terminal ends of the dendrogram itself based on user-defined metadata, which I personally think can be more aesthetically pleasing in some situations. This tutorial describes how I did it and provides reproducible code if you are hoping to do the same thing!" }, { "code": null, "e": 1054, "s": 1008, "text": "Before I start, what is a dendrogram, anyway?" }, { "code": null, "e": 1469, "s": 1054, "text": "A dendrogram is a graphical representation of hierarchical clustering. Clusters can be constructed in different ways (i.e., top-down or bottom-up), most commonly in R through the application of hclust() on a distance matrix. Dendrograms are built by connecting nodes to branches or other nodes, resulting in a tree-like figure that shows how individual things are related to each other based on multiple variables." }, { "code": null, "e": 1960, "s": 1469, "text": "Let’s say we want to compare how individual irises cluster from the well-known R-core data set. This dataframe contains four numeric vectors (Sepal.Length, Sepal.Width, Petal.Length, and Petal.Width) as well as one character vector (Species). We could easily construct and plot a dendrogram incorporating all these numeric data with base R, but what if we want to color the terminal segments by the species of iris to visualize whether Species follows the clustering determined by hclust()?" }, { "code": null, "e": 2302, "s": 1960, "text": "For this tutorial, you’ll want to load three R packages: tidyverse for data manipulation and visualization, ggdendro to extract dendrogram segment data into a dataframe, and RColorBrewer to make an automatic custom color palette for your dendrogram ends. If you would like to make your dendrogram interactive, be sure to load plotly as well." }, { "code": null, "e": 2360, "s": 2302, "text": "pacman::p_load(tidyverse, ggdendro, RColorBrewer, plotly)" }, { "code": null, "e": 2572, "s": 2360, "text": "Now we’ll want to load the irisdataframe into our environment. As bioinformaticians, we typically have sample names mapped to each observation, so we will want to create our own (sample_name) right at the start." }, { "code": null, "e": 3207, "s": 2572, "text": "With microbial community data, My workflow essentially involves two objects: a giant matrix of ASV (amplicon sequence variant; a term used to describe taxonomy based on DNA sequence similarity) abundances by sample_name, and metadata associated with each sample. To simulate this, we will separate iris into numeric_data, from which we will calculate distance and construct a dendrogram, and metadata, which for our purposes will simply consist of the species of iris for each sample_name. For this workflow, it is important to have a sample_name identifier for each observation; it will be the basis of merging everything at the end." }, { "code": null, "e": 3621, "s": 3207, "text": "# label rows with unique sample_namedat <- iris %>% mutate(sample_name = paste(“iris”, seq(1:nrow(iris)), sep = “_”)) # create unique sample ID# save non-numeric metadata in separate dataframemetadata <- dat %>% select(sample_name, Species)# extract numeric vectors for distance matrixnumeric_data <- dat %>% select(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, sample_name)# check data head(numeric_data)" }, { "code": null, "e": 3876, "s": 3621, "text": "Before we make the dendrogram, we will calculate a distance matrix based on numeric_data using dist(). It is good practice to normalize your data before doing this calculation; I will therefore normalize all values within a vector on a scale from 0 to 1." }, { "code": null, "e": 3992, "s": 3876, "text": "After we do that, we can create a distance matrix (dist_matrix) and generate a dendrogram from our normalized data." }, { "code": null, "e": 4623, "s": 3992, "text": "# normalize data to values from 0 to 1 numeric_data_norm <- numeric_data %>% select(sample_name, everything()) %>% pivot_longer(cols = 2:ncol(.), values_to = “value”, names_to = “type”) %>% group_by(type) %>% mutate(value_norm = (value-min(value))/(max(value)-min(value))) %>% # normalize data to values 0–1 select(sample_name, value_norm) %>% pivot_wider(names_from = “type”, values_from = “value_norm”) %>% column_to_rownames(“sample_name”)# create dendrogram from distance matrix of normalized datadist_matrix <- dist(numeric_data_norm, method = “euclidean”)dendrogram <- as.dendrogram(hclust(dist_matrix, method = “complete”))" }, { "code": null, "e": 4701, "s": 4623, "text": "Now let’s quickly take a look at what our dendrogram looks like using base R:" }, { "code": null, "e": 4718, "s": 4701, "text": "plot(dendrogram)" }, { "code": null, "e": 5010, "s": 4718, "text": "Okay, it’s not very pretty, but bear with me. This is a useful visual to show how we will extract the coordinate data from the dendrogram object with ggdendro::dendro_data() to make a better figure. Every dendrogram is plotted by adding individual segments between points on an x and y grid." }, { "code": null, "e": 5282, "s": 5010, "text": "When we apply dendro_data() and look at the extracted segment data, we see there are four vectors for every dendrogram: x, y, xend, and yend. Every horizontal or vertical line you see in the base R figure is ultimately constructed from one row of the following dataframe:" }, { "code": null, "e": 5469, "s": 5282, "text": "# extract dendrogram segment datadendrogram_data <- dendro_data(dendrogram)dendrogram_segments <- dendrogram_data$segments # contains all dendrogram segment datahead(dendrogram_segments)" }, { "code": null, "e": 5800, "s": 5469, "text": "We will split these coordinate data into two dataframes: dendrogram_segments, containing all the segments, and dendrogram_ends, containing only the terminal branches of the figure. As the plot above shows, when the value in the y-direction as 0 (i.e., yend == 0), only those single segments at the bottom of the plot are included:" }, { "code": null, "e": 6233, "s": 5800, "text": "# get terminal dendrogram segmentsdendrogram_ends <- dendrogram_segments %>% filter(yend == 0) %>% # filter for terminal dendrogram ends left_join(dendrogram_data$labels, by = “x”) %>% # .$labels contains the row names from dist_matrix (i.e., sample_name) rename(sample_name = label) %>% left_join(metadata, by = “sample_name”) # dataframe now contains only terminal dendrogram segments and merged metadata associated with each iris" }, { "code": null, "e": 6434, "s": 6233, "text": "Looking at dendrogram_ends, we now have a dataframe with vectors containing the dendrogram coordinate data matched to the sample_name andSpecies vectors. We are now ready to start plotting in ggplot2!" }, { "code": null, "e": 6456, "s": 6434, "text": "head(dendrogram_ends)" }, { "code": null, "e": 6905, "s": 6456, "text": "If you want to dynamically create a list of colors based on how many unique variables the metadata vector of interest contains, you can run this code. In this example, our metadata only contains three species of iris, so this could be done manually fairly quickly. However, if the number of unique metadata variables in your dataset is more than that, as is common with microbial community data, chances are you might want to automate this process." }, { "code": null, "e": 7625, "s": 6905, "text": "# Generate custom color palette for dendrogram ends based on metadata variableunique_vars <- levels(factor(dendrogram_ends$Species)) %>% as.data.frame() %>% rownames_to_column(“row_id”) # count number of unique variablescolor_count <- length(unique(unique_vars$.))# get RColorBrewer paletteget_palette <- colorRampPalette(brewer.pal(n = 8, name = “Set1”))# produce RColorBrewer palette based on number of unique variables in metadata:palette <- get_palette(color_count) %>% as.data.frame() %>% rename(“color” = “.”) %>% rownames_to_column(var = “row_id”)color_list <- left_join(unique_vars, palette, by = “row_id”) %>% select(-row_id)species_color <- as.character(color_list$color)names(species_color) <- color_list$." }, { "code": null, "e": 7767, "s": 7625, "text": "If you don’t want to bother with the above code for this tutorial, you could just manually create a named character vector as an alternative:" }, { "code": null, "e": 7928, "s": 7767, "text": "# Alternatively, create a custom named vector for iris species color:species_color <- c(“setosa” = “#E41A1C”, “versicolor” = “#CB6651”, “virginica” = “#F781BF”)" }, { "code": null, "e": 8373, "s": 7928, "text": "Now it’s time to plot our dendrogram! You will want to define two geoms for geom_segment: one plotting all the segment data extracted from Step 4, which are uncolored, and one for just the terminal branches of the dendrogram, which is what we will color with species_color from the previous step. If you wrap this plot with plotly (see below), I recommend adding an extra text aesthetic to control which information will display on your output." }, { "code": null, "e": 8891, "s": 8373, "text": "p <- ggplot() + geom_segment(data = dendrogram_segments, aes(x=x, y=y, xend=xend, yend=yend)) + geom_segment(data = dendrogram_ends, aes(x=x, y=y.x, xend=xend, yend=yend, color = Species, text = paste(‘sample name: ‘, sample_name, ‘<br>’, ‘species: ‘, Species))) + # test aes is for plotly scale_color_manual(values = species_color) + scale_y_reverse() + coord_flip() + theme_bw() + theme(legend.position = “none”) + ylab(“Distance”) + # flipped x and y coordinates for aesthetic reasons ggtitle(“Iris dendrogram”) p" }, { "code": null, "e": 9077, "s": 8891, "text": "If you want to get really fancy, you can wrap your ggplot with plotly to make your dendrogram interactive! Be sure to specify tooltip = “text” to control which information is displayed." }, { "code": null, "e": 9107, "s": 9077, "text": "ggplotly(p, tooltip = “text”)" } ]
Program to Divide two 8 Bit numbers in 8051 Microprocessor
Here we will see the division operation. This operation will be used to divide two 8-bit numbers using this 8051 microcontroller. The register A and B will be used in this operation. No other registers can be used for division. The result of the division has two parts. The quotient part and the remainder part. Register A will hold Quotient, and register B will hold Remainder. We are taking two number 0EH and 03H at location 20H and 21H, After dividing the result will be stored at location 30H and 31H. MOV R0, #20H ; set source address 20H to R0 MOV R1, #30H ; set destination address 30H to R1 MOV A, @R0 ; take the first operand from source to register A INC R0 ; Point to the next location MOV B, @R0 ; take second operand from source to register B DIV AB ; Divide A by B MOV @R1, A ; Store Quotient to 30H INC R1 ; Increase R1 to point to the next location MOV @R1, B ; Store Remainder to 31H HALT: SJMP HALT ; Stop the program 8051 provides DIV AB instruction. By using this instruction, the division can be done. In some other microprocessors like 8085, there was no DIV instruction. In that microprocessor, we need to use repetitive Subtraction operations to get the result of the division. When the denominator is 00H, the overflow flag OV will be 1. otherwise it is 0 for division.
[ { "code": null, "e": 1441, "s": 1062, "text": "Here we will see the division operation. This operation will be used to divide two 8-bit numbers using this 8051 microcontroller. The register A and B will be used in this operation. No other registers can be used for division. The result of the division has two parts. The quotient part and the remainder part. Register A will hold Quotient, and register B will hold Remainder." }, { "code": null, "e": 1569, "s": 1441, "text": "We are taking two number 0EH and 03H at location 20H and 21H, After dividing the result will be stored at location 30H and 31H." }, { "code": null, "e": 2053, "s": 1569, "text": " MOV R0, #20H ; set source address 20H to R0\n MOV R1, #30H ; set destination address 30H to R1\n MOV A, @R0 ; take the first operand from source to register A\n INC R0 ; Point to the next location\n MOV B, @R0 ; take second operand from source to register B\n DIV AB ; Divide A by B\n MOV @R1, A ; Store Quotient to 30H\n INC R1 ; Increase R1 to point to the next location\n MOV @R1, B ; Store Remainder to 31H\nHALT: SJMP HALT ; Stop the program" }, { "code": null, "e": 2319, "s": 2053, "text": "8051 provides DIV AB instruction. By using this instruction, the division can be done. In some other microprocessors like 8085, there was no DIV instruction. In that microprocessor, we need to use repetitive Subtraction operations to get the result of the division." }, { "code": null, "e": 2412, "s": 2319, "text": "When the denominator is 00H, the overflow flag OV will be 1. otherwise it is 0 for division." } ]
How to interactively validate an Entry widget content in tkinter?
Validating the content is a necessary part of any featured application where we allow only the required data to be processed. An Entry Widget in tkinter is used to display single line text Input. However, we can validate the Entry widget to accept only digits or alphabets. Let us first create an Entry widget that accepts only digits input. So initially, we will create an Entry widget and using register(callback) function, we will call to validate the Entry widget which validates whenever a key is stroked. It returns a string that can be used to call a function. Then, calling the callback function to validate the entry widget as, entrywidget.config(validate="key", validatecommand=(callback,'%d')) Validatecommand supports other values such as, %d, %i, %W, %P, %s, %v, etc. #Import the required library from tkinter import * #Create an instance of tkinter frame or window win = Tk() def callback(input): if input.isdigit(): print(input) return True elif input=="": print(input) return True else: print(input) return False #Create an entry widget entry= Entry(win) fun= win.register(callback) entry.config(validate="key", validatecommand=(fun, '%P')) entry.pack() win.mainloop() Running the above code will display a window that contains an Entry widget which accepts only digits and prints the key strokes on the console. In the output screen, enter any character. You will find that you can enter only digits, thus the entry widget is validated.
[ { "code": null, "e": 1336, "s": 1062, "text": "Validating the content is a necessary part of any featured application where we allow only the required data to be processed. An Entry Widget in tkinter is used to display single line text Input. However, we can validate the Entry widget to accept only digits or alphabets." }, { "code": null, "e": 1699, "s": 1336, "text": "Let us first create an Entry widget that accepts only digits input. So initially, we will create an Entry widget and using register(callback) function, we will call to validate the Entry widget which validates whenever a key is stroked. It returns a string that can be used to call a function. Then, calling the callback function to validate the entry widget as," }, { "code": null, "e": 1767, "s": 1699, "text": "entrywidget.config(validate=\"key\", validatecommand=(callback,'%d'))" }, { "code": null, "e": 1843, "s": 1767, "text": "Validatecommand supports other values such as, %d, %i, %W, %P, %s, %v, etc." }, { "code": null, "e": 2292, "s": 1843, "text": "#Import the required library\nfrom tkinter import *\n#Create an instance of tkinter frame or window\nwin = Tk()\ndef callback(input):\n if input.isdigit():\n print(input)\n return True\n elif input==\"\":\n print(input)\n return True\n else:\n print(input)\n return False\n#Create an entry widget\nentry= Entry(win)\nfun= win.register(callback)\nentry.config(validate=\"key\", validatecommand=(fun, '%P'))\nentry.pack()\nwin.mainloop()" }, { "code": null, "e": 2436, "s": 2292, "text": "Running the above code will display a window that contains an Entry widget which accepts only digits and prints the key strokes on the console." }, { "code": null, "e": 2561, "s": 2436, "text": "In the output screen, enter any character. You will find that you can enter only digits, thus the entry widget is validated." } ]
base64.b85encode() in Python - GeeksforGeeks
26 Mar, 2020 With the help of base64.b85encode() method, we can encode the string by using base85 alphabet into the binary form. Syntax : base64.b85encode(string) Return : Return the encoded string. Example #1 :In this example we can see that by using base64.b85encode() method, we are able to get the encoded string which can be in binary form by using this method. # import base64from base64 import b85encode s = b'GeeksForGeeks'# Using base64.b85encode() methodgfg = b85encode(s) print(gfg) Output : b’M`dMeb4G7+M`dMea{‘ Example #2 : # import base64from base64 import b85encode s = b'I love python'# Using base64.b85encode() methodgfg = b85encode(s) print(gfg) Output : b’Ng!-*c4Z)Nd30!RZU’ Python base64-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24408, "s": 24292, "text": "With the help of base64.b85encode() method, we can encode the string by using base85 alphabet into the binary form." }, { "code": null, "e": 24442, "s": 24408, "text": "Syntax : base64.b85encode(string)" }, { "code": null, "e": 24478, "s": 24442, "text": "Return : Return the encoded string." }, { "code": null, "e": 24646, "s": 24478, "text": "Example #1 :In this example we can see that by using base64.b85encode() method, we are able to get the encoded string which can be in binary form by using this method." }, { "code": "# import base64from base64 import b85encode s = b'GeeksForGeeks'# Using base64.b85encode() methodgfg = b85encode(s) print(gfg)", "e": 24775, "s": 24646, "text": null }, { "code": null, "e": 24784, "s": 24775, "text": "Output :" }, { "code": null, "e": 24805, "s": 24784, "text": "b’M`dMeb4G7+M`dMea{‘" }, { "code": null, "e": 24819, "s": 24805, "text": " Example #2 :" }, { "code": "# import base64from base64 import b85encode s = b'I love python'# Using base64.b85encode() methodgfg = b85encode(s) print(gfg)", "e": 24948, "s": 24819, "text": null }, { "code": null, "e": 24957, "s": 24948, "text": "Output :" }, { "code": null, "e": 24978, "s": 24957, "text": "b’Ng!-*c4Z)Nd30!RZU’" }, { "code": null, "e": 24999, "s": 24978, "text": "Python base64-module" }, { "code": null, "e": 25006, "s": 24999, "text": "Python" }, { "code": null, "e": 25104, "s": 25006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25136, "s": 25104, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25178, "s": 25136, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25234, "s": 25178, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25276, "s": 25234, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25307, "s": 25276, "text": "Python | os.path.join() method" }, { "code": null, "e": 25362, "s": 25307, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25384, "s": 25362, "text": "Defaultdict in Python" }, { "code": null, "e": 25423, "s": 25384, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25452, "s": 25423, "text": "Create a directory in Python" } ]
WPF - Interaction
In WPF, an interaction shows how a view interacts with controls located in that view. The most commonly known interactions are of two types − Behaviors Drag and Drop Behaviors were introduced with Expression Blend 3 which can encapsulate some of the functionality into a reusable component. To add additional behaviors, you can attach these components to the controls. Behaviors provide more flexibility to design complex user interactions easily. Let’s take a look at a simple example in which a ControlStoryBoardAction behavior is attached to controls. Create a new WPF project with the name WPFBehavior. Create a new WPF project with the name WPFBehavior. The following XAML code creates an ellipse and two buttons to control the movement of the ellipse. The following XAML code creates an ellipse and two buttons to control the movement of the ellipse. <Window xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFBehaviors" xmlns:i = "http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei = "http://schemas.microsoft.com/expression/2010/interactions" x:Class = "WPFBehaviors.MainWindow" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Storyboard x:Key = "Storyboard1" RepeatBehavior = "Forever" AutoReverse = "True"> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.X)" Storyboard.TargetName = "ellipse"> <EasingDoubleKeyFrame KeyTime = "0:0:1" Value = "301.524"/> <EasingDoubleKeyFrame KeyTime = "0:0:2" Value = "2.909"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.Y)" Storyboard.TargetName = "ellipse"> <EasingDoubleKeyFrame KeyTime = "0:0:1" Value = "-0.485"/> <EasingDoubleKeyFrame KeyTime = "0:0:2" Value = "0"/> </DoubleAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty = "(ContentControl.Content)" Storyboard.TargetName = "button"> <DiscreteObjectKeyFrame KeyTime = "0" Value = "Play"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty = "(ContentControl.Content)" Storyboard.TargetName = "button1"> <DiscreteObjectKeyFrame KeyTime = "0" Value = "Stop"/> <DiscreteObjectKeyFrame KeyTime = "0:0:2" Value = "Stop"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </Window.Resources> <Window.Triggers> <EventTrigger RoutedEvent = "FrameworkElement.Loaded"> <BeginStoryboard Storyboard = "{StaticResource Storyboard1}"/> </EventTrigger> </Window.Triggers> <Grid> <Ellipse x:Name = "ellipse" Fill = "#FFAAAAC5" HorizontalAlignment = "Left" Height = "50.901" Margin = "49.324,70.922,0,0" Stroke = "Black" VerticalAlignment = "Top" Width = "73.684" RenderTransformOrigin = "0.5,0.5"> <Ellipse.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Ellipse.RenderTransform> </Ellipse> <Button x:Name = "button" Content = "Play" HorizontalAlignment = "Left" Height = "24.238" Margin = "63.867,0,0,92.953" VerticalAlignment = "Bottom" Width = "74.654"> <i:Interaction.Triggers> <i:EventTrigger EventName = "Click"> <ei:ControlStoryboardAction Storyboard = "{StaticResource Storyboard1}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> <Button x:Name = "button1" Content = "Stop" HorizontalAlignment = "Left" Height = "24.239" Margin = "160.82,0,0,93.922" VerticalAlignment = "Bottom" Width = "75.138"> <i:Interaction.Triggers> <i:EventTrigger EventName = "Click"> <ei:ControlStoryboardAction ControlStoryboardOption = "Stop" Storyboard = "{StaticResource Storyboard1}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> </Grid> </Window> When you compile and execute the above code, it will produce the following window which contains an ellipse and two buttons. When you press the play button, it will start moving from left to right and then will return to its original position. The stop button will stop the movement the ellipse. Drag and Drop on user interface can significantly advance the efficiency and productivity of the application. There are very few applications in which drag and drop features are used because people think it is difficult to implement. To an extent, it is difficult to handle a drag and drop feature, but in WPF, you can handle it quite easily. Let’s take a simple example to understand how it works. We will create an application wherein you can drag and drop color from one rectangle to another. Create a new WPF project with the name WPFDragAndDrop. Create a new WPF project with the name WPFDragAndDrop. Drag five rectangles to the design window and set the properties as shown in the following XAML file. Drag five rectangles to the design window and set the properties as shown in the following XAML file. <Window x:Class = "WPFDragAndDrop.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFDragAndDrop" mc:Ignorable = "d" Title = "MainWindow" Height = "402.551" Width = "604"> <Grid> <Rectangle Name = "Target" Fill = "AliceBlue" HorizontalAlignment = "Left" Height = "345" Margin = "10,10,0,0" Stroke = "Black" VerticalAlignment = "Top" Width = "387" AllowDrop = "True" Drop = "Target_Drop"/> <Rectangle Fill = "Beige" HorizontalAlignment = "Left" Height = "65" Margin = "402,10,0,0" Stroke = "Black" VerticalAlignment = "Top" Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> <Rectangle Fill = "LightBlue" HorizontalAlignment = "Left" Height = "65" Margin = "402,80,0,0" Stroke = "Black" VerticalAlignment = "Top" Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> <Rectangle Fill = "LightCoral" HorizontalAlignment = "Left" Height = "65" Margin = "402,150,0,0" Stroke = "Black" VerticalAlignment = "Top" Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> <Rectangle Fill = "LightGray" HorizontalAlignment = "Left" Height = "65" Margin = "402,220,0,0" Stroke = "Black" VerticalAlignment = "Top" Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> <Rectangle Fill = "OliveDrab" HorizontalAlignment = "Left" Height = "65" Margin = "402,290,0,-7" Stroke = "Black" VerticalAlignment = "Top" Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> </Grid> </Window> The first rectangle is the target rectangle, so the user can drag the color from the other rectangle to the target rectangle. The first rectangle is the target rectangle, so the user can drag the color from the other rectangle to the target rectangle. Given below are the events implementation in C# for drag and drop. Given below are the events implementation in C# for drag and drop. using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace WPFDragAndDrop { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Rect_MLButtonDown(object sender, MouseButtonEventArgs e) { Rectangle rc = sender as Rectangle; DataObject data = new DataObject(rc.Fill); DragDrop.DoDragDrop(rc, data,DragDropEffects.Move); } private void Target_Drop(object sender, DragEventArgs e) { SolidColorBrush scb = (SolidColorBrush)e.Data.GetData(typeof(SolidColorBrush)); Target.Fill = scb; } } } When you run your application, it will produce the following window. If you drag a color from the rectangle on the right side and drop it on the large rectangle to the left, you will see its effect immediately. Let’s drag the 4th one from the right side. You can see that the color of the target rectangle has changed. We recommend that you execute the above code and experiment with its features. 31 Lectures 2.5 hours Anadi Sharma 30 Lectures 2.5 hours Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2162, "s": 2020, "text": "In WPF, an interaction shows how a view interacts with controls located in that view. The most commonly known interactions are of two types −" }, { "code": null, "e": 2172, "s": 2162, "text": "Behaviors" }, { "code": null, "e": 2186, "s": 2172, "text": "Drag and Drop" }, { "code": null, "e": 2468, "s": 2186, "text": "Behaviors were introduced with Expression Blend 3 which can encapsulate some of the functionality into a reusable component. To add additional behaviors, you can attach these components to the controls. Behaviors provide more flexibility to design complex user interactions easily." }, { "code": null, "e": 2575, "s": 2468, "text": "Let’s take a look at a simple example in which a ControlStoryBoardAction behavior is attached to controls." }, { "code": null, "e": 2627, "s": 2575, "text": "Create a new WPF project with the name WPFBehavior." }, { "code": null, "e": 2679, "s": 2627, "text": "Create a new WPF project with the name WPFBehavior." }, { "code": null, "e": 2778, "s": 2679, "text": "The following XAML code creates an ellipse and two buttons to control the movement of the ellipse." }, { "code": null, "e": 2877, "s": 2778, "text": "The following XAML code creates an ellipse and two buttons to control the movement of the ellipse." }, { "code": null, "e": 6735, "s": 2877, "text": "<Window \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFBehaviors\" \n xmlns:i = \"http://schemas.microsoft.com/expression/2010/interactivity\" \n xmlns:ei = \"http://schemas.microsoft.com/expression/2010/interactions\" \n x:Class = \"WPFBehaviors.MainWindow\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Window.Resources> \n <Storyboard x:Key = \"Storyboard1\" RepeatBehavior = \"Forever\" AutoReverse = \"True\"> \n\t\t\n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty =\n \"(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.X)\"\n Storyboard.TargetName = \"ellipse\"> \n <EasingDoubleKeyFrame KeyTime = \"0:0:1\" Value = \"301.524\"/> \n <EasingDoubleKeyFrame KeyTime = \"0:0:2\" Value = \"2.909\"/> \n </DoubleAnimationUsingKeyFrames>\n\t\t\t\n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \n \"(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.Y)\"\n Storyboard.TargetName = \"ellipse\"> \n <EasingDoubleKeyFrame KeyTime = \"0:0:1\" Value = \"-0.485\"/> \n <EasingDoubleKeyFrame KeyTime = \"0:0:2\" Value = \"0\"/> \n </DoubleAnimationUsingKeyFrames> \n\t\t\t\n <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty = \"(ContentControl.Content)\"\n Storyboard.TargetName = \"button\"> \n <DiscreteObjectKeyFrame KeyTime = \"0\" Value = \"Play\"/> \n </ObjectAnimationUsingKeyFrames>\n\t\t\t\n <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty = \"(ContentControl.Content)\"\n Storyboard.TargetName = \"button1\"> \n <DiscreteObjectKeyFrame KeyTime = \"0\" Value = \"Stop\"/> \n <DiscreteObjectKeyFrame KeyTime = \"0:0:2\" Value = \"Stop\"/> \n </ObjectAnimationUsingKeyFrames> \n </Storyboard> \n </Window.Resources> \n\t\n <Window.Triggers> \n <EventTrigger RoutedEvent = \"FrameworkElement.Loaded\"> \n <BeginStoryboard Storyboard = \"{StaticResource Storyboard1}\"/> \n </EventTrigger> \n </Window.Triggers> \n\t\n <Grid> \n <Ellipse x:Name = \"ellipse\" Fill = \"#FFAAAAC5\" HorizontalAlignment = \"Left\"\n Height = \"50.901\" Margin = \"49.324,70.922,0,0\" Stroke = \"Black\"\n VerticalAlignment = \"Top\" Width = \"73.684\" RenderTransformOrigin = \"0.5,0.5\"> \n <Ellipse.RenderTransform> \n <TransformGroup> \n <ScaleTransform/> \n <SkewTransform/> \n <RotateTransform/> \n <TranslateTransform/> \n </TransformGroup> \n </Ellipse.RenderTransform> \n </Ellipse>\n\t\t\n <Button x:Name = \"button\" Content = \"Play\" HorizontalAlignment = \"Left\" Height = \"24.238\"\n Margin = \"63.867,0,0,92.953\" VerticalAlignment = \"Bottom\" Width = \"74.654\"> \n <i:Interaction.Triggers> \n <i:EventTrigger EventName = \"Click\"> \n <ei:ControlStoryboardAction Storyboard = \"{StaticResource Storyboard1}\"/> \n </i:EventTrigger> \n </i:Interaction.Triggers> \n </Button>\n\t\t\n <Button x:Name = \"button1\" Content = \"Stop\" HorizontalAlignment = \"Left\" Height = \"24.239\"\n Margin = \"160.82,0,0,93.922\" VerticalAlignment = \"Bottom\" Width = \"75.138\"> \n <i:Interaction.Triggers> \n <i:EventTrigger EventName = \"Click\"> \n <ei:ControlStoryboardAction ControlStoryboardOption = \"Stop\"\n Storyboard = \"{StaticResource Storyboard1}\"/> \n </i:EventTrigger> \n </i:Interaction.Triggers> \n </Button> \n\t\t\n </Grid> \n</Window> \t" }, { "code": null, "e": 6860, "s": 6735, "text": "When you compile and execute the above code, it will produce the following window which contains an ellipse and two buttons." }, { "code": null, "e": 7031, "s": 6860, "text": "When you press the play button, it will start moving from left to right and then will return to its original position. The stop button will stop the movement the ellipse." }, { "code": null, "e": 7374, "s": 7031, "text": "Drag and Drop on user interface can significantly advance the efficiency and productivity of the application. There are very few applications in which drag and drop features are used because people think it is difficult to implement. To an extent, it is difficult to handle a drag and drop feature, but in WPF, you can handle it quite easily." }, { "code": null, "e": 7527, "s": 7374, "text": "Let’s take a simple example to understand how it works. We will create an application wherein you can drag and drop color from one rectangle to another." }, { "code": null, "e": 7582, "s": 7527, "text": "Create a new WPF project with the name WPFDragAndDrop." }, { "code": null, "e": 7637, "s": 7582, "text": "Create a new WPF project with the name WPFDragAndDrop." }, { "code": null, "e": 7739, "s": 7637, "text": "Drag five rectangles to the design window and set the properties as shown in the following XAML file." }, { "code": null, "e": 7841, "s": 7739, "text": "Drag five rectangles to the design window and set the properties as shown in the following XAML file." }, { "code": null, "e": 9716, "s": 7841, "text": "<Window x:Class = \"WPFDragAndDrop.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFDragAndDrop\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"402.551\" Width = \"604\"> \n\t\n <Grid> \n <Rectangle Name = \"Target\" Fill = \"AliceBlue\" HorizontalAlignment = \"Left\" \n Height = \"345\" Margin = \"10,10,0,0\" Stroke = \"Black\" \n VerticalAlignment = \"Top\" Width = \"387\" AllowDrop = \"True\" Drop = \"Target_Drop\"/> \n\t\t\t\n <Rectangle Fill = \"Beige\" HorizontalAlignment = \"Left\" Height = \"65\" \n Margin = \"402,10,0,0\" Stroke = \"Black\" VerticalAlignment = \"Top\" \n Width = \"184\" MouseLeftButtonDown = \"Rect_MLButtonDown\"/> \n\t\t\t\n <Rectangle Fill = \"LightBlue\" HorizontalAlignment = \"Left\" Height = \"65\" \n Margin = \"402,80,0,0\" Stroke = \"Black\" VerticalAlignment = \"Top\" \n Width = \"184\" MouseLeftButtonDown = \"Rect_MLButtonDown\"/> \n\t\t\t\n <Rectangle Fill = \"LightCoral\" HorizontalAlignment = \"Left\" Height = \"65\" \n Margin = \"402,150,0,0\" Stroke = \"Black\" VerticalAlignment = \"Top\" \n Width = \"184\" MouseLeftButtonDown = \"Rect_MLButtonDown\"/> \n\t\t\t\n <Rectangle Fill = \"LightGray\" HorizontalAlignment = \"Left\" Height = \"65\" \n Margin = \"402,220,0,0\" Stroke = \"Black\" VerticalAlignment = \"Top\" \n Width = \"184\" MouseLeftButtonDown = \"Rect_MLButtonDown\"/> \n\t\t\t\n <Rectangle Fill = \"OliveDrab\" HorizontalAlignment = \"Left\" Height = \"65\" \n Margin = \"402,290,0,-7\" Stroke = \"Black\" VerticalAlignment = \"Top\" \n Width = \"184\" MouseLeftButtonDown = \"Rect_MLButtonDown\"/> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 9842, "s": 9716, "text": "The first rectangle is the target rectangle, so the user can drag the color from the other rectangle to the target rectangle." }, { "code": null, "e": 9968, "s": 9842, "text": "The first rectangle is the target rectangle, so the user can drag the color from the other rectangle to the target rectangle." }, { "code": null, "e": 10035, "s": 9968, "text": "Given below are the events implementation in C# for drag and drop." }, { "code": null, "e": 10102, "s": 10035, "text": "Given below are the events implementation in C# for drag and drop." }, { "code": null, "e": 10910, "s": 10102, "text": "using System.Windows; \nusing System.Windows.Input; \nusing System.Windows.Media; \nusing System.Windows.Shapes; \n \nnamespace WPFDragAndDrop { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void Rect_MLButtonDown(object sender, MouseButtonEventArgs e) { \n Rectangle rc = sender as Rectangle; \n DataObject data = new DataObject(rc.Fill); \n DragDrop.DoDragDrop(rc, data,DragDropEffects.Move); \n } \n\t\t\n private void Target_Drop(object sender, DragEventArgs e) { \n SolidColorBrush scb = (SolidColorBrush)e.Data.GetData(typeof(SolidColorBrush)); \n Target.Fill = scb; \n } \n } \n}" }, { "code": null, "e": 10979, "s": 10910, "text": "When you run your application, it will produce the following window." }, { "code": null, "e": 11121, "s": 10979, "text": "If you drag a color from the rectangle on the right side and drop it on the large rectangle to the left, you will see its effect immediately." }, { "code": null, "e": 11165, "s": 11121, "text": "Let’s drag the 4th one from the right side." }, { "code": null, "e": 11308, "s": 11165, "text": "You can see that the color of the target rectangle has changed. We recommend that you execute the above code and experiment with its features." }, { "code": null, "e": 11343, "s": 11308, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11357, "s": 11343, "text": " Anadi Sharma" }, { "code": null, "e": 11392, "s": 11357, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11415, "s": 11392, "text": " Taurius Litvinavicius" }, { "code": null, "e": 11422, "s": 11415, "text": " Print" }, { "code": null, "e": 11433, "s": 11422, "text": " Add Notes" } ]
How to replace a character at a particular index in JavaScript ? - GeeksforGeeks
28 Nov, 2019 To replace a character from a string there are popular methods available, the two most popular methods we are going to describe in this article. The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index. This can be used to extract the parts of the string excluding the character to be replaced. The first part of the string can be extracted by using the starting index parameter as ‘0’ (which denotes the starting of the string) and the length parameter as the index where the character has to be replaced. The second part of the string can be extracted by using the starting index parameter as ‘index + 1’, which denotes the part of the string after the index of the character. The second parameter is omitted to get the whole string after it. The new string created concatenating the two parts of the string with the character to be replaced added in between. This will create a new string with the character replaced at the index. Syntax:function replaceChar(origString, replaceChar, index) { let firstPart = origString.substr(0, index); let lastPart = origString.substr(index + 1); let newString = firstPart + replaceChar + lastPart; return newString; } function replaceChar(origString, replaceChar, index) { let firstPart = origString.substr(0, index); let lastPart = origString.substr(index + 1); let newString = firstPart + replaceChar + lastPart; return newString; } Example:<!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container{ text-align: left; width:500px; padding-left:60px; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <div class="container"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by "M". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class="output"></span> </p> <button onclick="changeText()"> Replace Character </button> </div> </center> <script type="text/javascript"> function replaceChar(origString, replaceChar, index) { let firstPart = origString.substr(0, index); let lastPart = origString.substr(index + 1); let newString = firstPart + replaceChar + lastPart; return newString; } function changeText() { originalText = "GeeksforGeeks"; charReplaced = replaceChar(originalText, "M", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html> <!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container{ text-align: left; width:500px; padding-left:60px; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <div class="container"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by "M". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class="output"></span> </p> <button onclick="changeText()"> Replace Character </button> </div> </center> <script type="text/javascript"> function replaceChar(origString, replaceChar, index) { let firstPart = origString.substr(0, index); let lastPart = origString.substr(index + 1); let newString = firstPart + replaceChar + lastPart; return newString; } function changeText() { originalText = "GeeksforGeeks"; charReplaced = replaceChar(originalText, "M", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html> Output:Before Clicking the button:After Clicking the button: Converting the string to an array and replacing the character at the index: The string is converted to an array using the split() method with the separator as a blank character (“”). This will split the string into an array and make every character accessible as an index of the array. The character which has to replaced can then be simply assigned to the corresponding index of the array. The array is joined back into a string using the join() method with the separator as a blank character (“”). This will create a new string with the character replaced at the index. Syntax:function replaceChar(origString, replaceChar, index) { let newStringArray = origString.split(""); newStringArray[index] = replaceChar; let newString = newStringArray.join(""); return newString; } function replaceChar(origString, replaceChar, index) { let newStringArray = origString.split(""); newStringArray[index] = replaceChar; let newString = newStringArray.join(""); return newString; } Example:<!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container { text-align: left; width: 500px; padding-left: 60px; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <div class="container"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by "M". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class="output"></span> </p> <button onclick="changeText()"> Replace Character </button> </div> </center> <script type="text/javascript"> function replaceChar(origString, replaceChar, index) { let newStringArray = origString.split(""); newStringArray[index] = replaceChar; let newString = newStringArray.join(""); return newString; } function changeText() { originalText = "GeeksforGeeks"; charReplaced = replaceChar(originalText, "M", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html> <!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container { text-align: left; width: 500px; padding-left: 60px; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <div class="container"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by "M". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class="output"></span> </p> <button onclick="changeText()"> Replace Character </button> </div> </center> <script type="text/javascript"> function replaceChar(origString, replaceChar, index) { let newStringArray = origString.split(""); newStringArray[index] = replaceChar; let newString = newStringArray.join(""); return newString; } function changeText() { originalText = "GeeksforGeeks"; charReplaced = replaceChar(originalText, "M", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html> Output:Before Clicking button:After Clicking button: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25111, "s": 25083, "text": "\n28 Nov, 2019" }, { "code": null, "e": 25445, "s": 25111, "text": "To replace a character from a string there are popular methods available, the two most popular methods we are going to describe in this article. The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below:" }, { "code": null, "e": 25662, "s": 25445, "text": "Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index. This can be used to extract the parts of the string excluding the character to be replaced." }, { "code": null, "e": 25874, "s": 25662, "text": "The first part of the string can be extracted by using the starting index parameter as ‘0’ (which denotes the starting of the string) and the length parameter as the index where the character has to be replaced." }, { "code": null, "e": 26112, "s": 25874, "text": "The second part of the string can be extracted by using the starting index parameter as ‘index + 1’, which denotes the part of the string after the index of the character. The second parameter is omitted to get the whole string after it." }, { "code": null, "e": 26301, "s": 26112, "text": "The new string created concatenating the two parts of the string with the character to be replaced added in between. This will create a new string with the character replaced at the index." }, { "code": null, "e": 26549, "s": 26301, "text": "Syntax:function replaceChar(origString, replaceChar, index) {\n let firstPart = origString.substr(0, index);\n let lastPart = origString.substr(index + 1);\n \n let newString = firstPart + replaceChar + lastPart;\n return newString;\n}\n" }, { "code": null, "e": 26790, "s": 26549, "text": "function replaceChar(origString, replaceChar, index) {\n let firstPart = origString.substr(0, index);\n let lastPart = origString.substr(index + 1);\n \n let newString = firstPart + replaceChar + lastPart;\n return newString;\n}\n" }, { "code": null, "e": 28469, "s": 26790, "text": "Example:<!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container{ text-align: left; width:500px; padding-left:60px; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <div class=\"container\"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by \"M\". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"changeText()\"> Replace Character </button> </div> </center> <script type=\"text/javascript\"> function replaceChar(origString, replaceChar, index) { let firstPart = origString.substr(0, index); let lastPart = origString.substr(index + 1); let newString = firstPart + replaceChar + lastPart; return newString; } function changeText() { originalText = \"GeeksforGeeks\"; charReplaced = replaceChar(originalText, \"M\", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container{ text-align: left; width:500px; padding-left:60px; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <div class=\"container\"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by \"M\". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"changeText()\"> Replace Character </button> </div> </center> <script type=\"text/javascript\"> function replaceChar(origString, replaceChar, index) { let firstPart = origString.substr(0, index); let lastPart = origString.substr(index + 1); let newString = firstPart + replaceChar + lastPart; return newString; } function changeText() { originalText = \"GeeksforGeeks\"; charReplaced = replaceChar(originalText, \"M\", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html>", "e": 30140, "s": 28469, "text": null }, { "code": null, "e": 30201, "s": 30140, "text": "Output:Before Clicking the button:After Clicking the button:" }, { "code": null, "e": 30487, "s": 30201, "text": "Converting the string to an array and replacing the character at the index: The string is converted to an array using the split() method with the separator as a blank character (“”). This will split the string into an array and make every character accessible as an index of the array." }, { "code": null, "e": 30773, "s": 30487, "text": "The character which has to replaced can then be simply assigned to the corresponding index of the array. The array is joined back into a string using the join() method with the separator as a blank character (“”). This will create a new string with the character replaced at the index." }, { "code": null, "e": 30995, "s": 30773, "text": "Syntax:function replaceChar(origString, replaceChar, index) {\n let newStringArray = origString.split(\"\");\n\n newStringArray[index] = replaceChar;\n\n let newString = newStringArray.join(\"\");\n\n return newString;\n}" }, { "code": null, "e": 31210, "s": 30995, "text": "function replaceChar(origString, replaceChar, index) {\n let newStringArray = origString.split(\"\");\n\n newStringArray[index] = replaceChar;\n\n let newString = newStringArray.join(\"\");\n\n return newString;\n}" }, { "code": null, "e": 32839, "s": 31210, "text": "Example:<!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container { text-align: left; width: 500px; padding-left: 60px; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <div class=\"container\"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by \"M\". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"changeText()\"> Replace Character </button> </div> </center> <script type=\"text/javascript\"> function replaceChar(origString, replaceChar, index) { let newStringArray = origString.split(\"\"); newStringArray[index] = replaceChar; let newString = newStringArray.join(\"\"); return newString; } function changeText() { originalText = \"GeeksforGeeks\"; charReplaced = replaceChar(originalText, \"M\", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> How to replace a character at a particular index in JavaScript? </title> <style> .container { text-align: left; width: 500px; padding-left: 60px; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <div class=\"container\"> <b> How to replace a character at a particular index in JavaScript? </b> <p> The character at the 8th index would be replaced by \"M\". </p> <p> Original string is: GeeksforGeeks </p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"changeText()\"> Replace Character </button> </div> </center> <script type=\"text/javascript\"> function replaceChar(origString, replaceChar, index) { let newStringArray = origString.split(\"\"); newStringArray[index] = replaceChar; let newString = newStringArray.join(\"\"); return newString; } function changeText() { originalText = \"GeeksforGeeks\"; charReplaced = replaceChar(originalText, \"M\", 8); document.querySelector('.output').textContent = charReplaced; } </script></body> </html>", "e": 34460, "s": 32839, "text": null }, { "code": null, "e": 34513, "s": 34460, "text": "Output:Before Clicking button:After Clicking button:" }, { "code": null, "e": 34529, "s": 34513, "text": "JavaScript-Misc" }, { "code": null, "e": 34536, "s": 34529, "text": "Picked" }, { "code": null, "e": 34547, "s": 34536, "text": "JavaScript" }, { "code": null, "e": 34564, "s": 34547, "text": "Web Technologies" }, { "code": null, "e": 34591, "s": 34564, "text": "Web technologies Questions" }, { "code": null, "e": 34689, "s": 34591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34734, "s": 34689, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34795, "s": 34734, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34867, "s": 34795, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34919, "s": 34867, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 34965, "s": 34919, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 35007, "s": 34965, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 35040, "s": 35007, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35083, "s": 35040, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 35133, "s": 35083, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How do I send a DELETE keystroke to a text field using Selenium with Python?
We can send a DELETE keystroke to a text field using Selenium webdriver with Python. First of all, we have to identify the text field with the help of any locators like xpath, css, id, and so on. We can enter a text in the text field with the send_keys method. The value to be entered is passed as parameter to the method. To delete a key, we can pass Keys.BACKSPACE as a parameter to the send_keys method. l = driver.find_element_by_id("gsc−i−id1") l.send_keys("Sel") l.send_keys(Keys.BACKSPACE) To delete all the keys entered simultaneously, we have to pass CTRL+A and BACKSPACE as parameters to the send_keys method. l = driver.find_element_by_id("gsc−i−id1") l.send_keys("Sel") l.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE) Also, to use the Keys class, we have to add the import statement from selenium.webdriver.common.keys import Keys in our code. from selenium import webdriver from selenium.webdriver.common.keys import Keys import time #set geckodriver.exe path driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify element and enter text l = driver.find_element_by_id("gsc−i−id1") l.send_keys("Sel") #delete a key l.send_keys(Keys.BACKSPACE) print("Value after deleting a single key") print(l.get_attribute('value')) #wait for some time time.sleep(0.8) #delete all keys at once l.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE) print("Value after deleting entire key") print(l.get_attribute('value')) #close driver session driver.quit()
[ { "code": null, "e": 1258, "s": 1062, "text": "We can send a DELETE keystroke to a text field using Selenium webdriver with Python. First of all, we have to identify the text field with the help of any locators like xpath, css, id, and so on." }, { "code": null, "e": 1469, "s": 1258, "text": "We can enter a text in the text field with the send_keys method. The value to be entered is passed as parameter to the method. To delete a key, we can pass Keys.BACKSPACE as a parameter to the send_keys method." }, { "code": null, "e": 1559, "s": 1469, "text": "l = driver.find_element_by_id(\"gsc−i−id1\")\nl.send_keys(\"Sel\")\nl.send_keys(Keys.BACKSPACE)" }, { "code": null, "e": 1682, "s": 1559, "text": "To delete all the keys entered simultaneously, we have to pass CTRL+A and BACKSPACE as parameters to the send_keys method." }, { "code": null, "e": 1792, "s": 1682, "text": "l = driver.find_element_by_id(\"gsc−i−id1\")\nl.send_keys(\"Sel\")\nl.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)" }, { "code": null, "e": 1918, "s": 1792, "text": "Also, to use the Keys class, we have to add the import statement from selenium.webdriver.common.keys import Keys in our code." }, { "code": null, "e": 2628, "s": 1918, "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n#set geckodriver.exe path\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify element and enter text\nl = driver.find_element_by_id(\"gsc−i−id1\")\nl.send_keys(\"Sel\")\n#delete a key\nl.send_keys(Keys.BACKSPACE)\nprint(\"Value after deleting a single key\")\nprint(l.get_attribute('value'))\n#wait for some time\ntime.sleep(0.8)\n#delete all keys at once\nl.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)\nprint(\"Value after deleting entire key\")\nprint(l.get_attribute('value'))\n#close driver session\ndriver.quit()" } ]
Calculating Factorials using Stirling Approximation - GeeksforGeeks
07 Apr, 2021 We are aware of calculating factorials using loops or recursion, but if we are asked to calculate factorial without using any loop or recursion. Yes, this is possible through a well-known approximation algorithm known as Stirling approximation. Examples: Input : n = 6 Output : 720 Input : n = 2 Output : 2 Stirling approximation: is an approximation for calculating factorials. It is also useful for approximating the log of a factorial. n! ~ sqrt(2*pi*n) * pow((n/e), n) Note: This formula will not give the exact value of the factorial because it is just the approximation of the factorial. C++ Java Python3 C# PHP Javascript // CPP program for calculating factorial// of a number using Stirling// Approximation#include<bits/stdc++.h>using namespace std; // function for calculating factoriallong int stirlingFactorial(int n){ if (n == 1) return 1; long int z; float e = 2.71; // value of natural e // evaluating factorial using // stirling approximation z = sqrt(2*3.14*n) * pow((n/e), n); return z;} // driver programint main(){ cout << stirlingFactorial(1) << endl; cout << stirlingFactorial(2) << endl; cout << stirlingFactorial(3) << endl; cout << stirlingFactorial(4) << endl; cout << stirlingFactorial(5) << endl; cout << stirlingFactorial(6) << endl; cout << stirlingFactorial(7) << endl; return 0;} // Java program for calculating// factorial of a number using// Stirling Approximationclass GFG{ // function for// calculating factorialpublic static int stirlingFactorial(double n){ if (n == 1) return 1; double z; double e = 2.71; // value of natural e // evaluating factorial using // stirling approximation z = Math.sqrt(2 * 3.14 * n) * Math.pow((n / e), n); return (int)(z);} // Driver Codepublic static void main(String[] args){ System.out.println(stirlingFactorial(1)); System.out.println(stirlingFactorial(2)); System.out.println(stirlingFactorial(3)); System.out.println(stirlingFactorial(4)); System.out.println(stirlingFactorial(5)); System.out.println(stirlingFactorial(6)); System.out.println(stirlingFactorial(7));}} // This code is contributed by mits. # Python3 program for calculating# factorial of a number using# Stirling Approximationimport math # Function for calculating factorialdef stirlingFactorial(n): if (n == 1): return 1 # value of natural e e = 2.71 # evaluating factorial using # stirling approximation z = (math.sqrt(2 * 3.14 * n) * math.pow((n / e), n)) return math.floor(z) # Driver Codeprint(stirlingFactorial(1))print(stirlingFactorial(2))print(stirlingFactorial(3))print(stirlingFactorial(4))print(stirlingFactorial(5))print(stirlingFactorial(6))print(stirlingFactorial(7)) # This code is contributed by mits // C# program for calculating// factorial of a number using// Stirling Approximation class GFG{ // function for// calculating factorialpublic static int stirlingFactorial(double n){ if (n == 1) return 1; double z; double e = 2.71; // value of natural e // evaluating factorial using // stirling approximation z = System.Math.Sqrt(2 * 3.14 * n) * System.Math.Pow((n / e), n); return (int)(z);} // Driver Codepublic static void Main(){ System.Console.WriteLine(stirlingFactorial(1)); System.Console.WriteLine(stirlingFactorial(2)); System.Console.WriteLine(stirlingFactorial(3)); System.Console.WriteLine(stirlingFactorial(4)); System.Console.WriteLine(stirlingFactorial(5)); System.Console.WriteLine(stirlingFactorial(6)); System.Console.WriteLine(stirlingFactorial(7));}} // This code is contributed by mits. <?php// PHP program for calculating factorial// of a number using Stirling// Approximation // Function for calculating factorialfunction stirlingFactorial($n){ if ($n == 1) return 1; $z; // value of natural e $e = 2.71; // evaluating factorial using // stirling approximation $z = sqrt(2 * 3.14 * $n) * pow(($n / $e), $n); return floor($z);} // Driver Code echo stirlingFactorial(1),"\n"; echo stirlingFactorial(2) ,"\n"; echo stirlingFactorial(3) ,"\n"; echo stirlingFactorial(4), "\n" ; echo stirlingFactorial(5) ,"\n"; echo stirlingFactorial(6) ," \n"; echo stirlingFactorial(7) ," \n"; // This code is contributed by anuj_67.?> <script>// Javascript program for calculating factorial// of a number using Stirling// Approximation // Function for calculating factorialfunction stirlingFactorial(n){ if (n == 1) return 1; let z; // value of natural e let e = 2.71; // evaluating factorial using // stirling approximation z = Math.sqrt(2 * 3.14 * n) * Math.pow((n / e), n); return Math.floor(z);} // Driver Code document.write( stirlingFactorial(1) + "<br>"); document.write( stirlingFactorial(2) + "<br>"); document.write( stirlingFactorial(3) + "<br>"); document.write( stirlingFactorial(4) + "<br>"); document.write( stirlingFactorial(5) + "<br>"); document.write( stirlingFactorial(6) + "<br>"); document.write( stirlingFactorial(7) + "<br>"); // This code is contributed by _saurabh_jaiswal.</script> Output: 1 1 5 23 119 723 5086 This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. vt_m Mithun Kumar BournThing _saurabh_jaiswal factorial Mathematical Mathematical factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Count ways to reach the n'th stair Find first and last digits of a number Find Union and Intersection of two unsorted arrays Program to convert a given number to words
[ { "code": null, "e": 24718, "s": 24690, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24975, "s": 24718, "text": "We are aware of calculating factorials using loops or recursion, but if we are asked to calculate factorial without using any loop or recursion. Yes, this is possible through a well-known approximation algorithm known as Stirling approximation. Examples: " }, { "code": null, "e": 25028, "s": 24975, "text": "Input : n = 6\nOutput : 720\n\nInput : n = 2\nOutput : 2" }, { "code": null, "e": 25318, "s": 25030, "text": "Stirling approximation: is an approximation for calculating factorials. It is also useful for approximating the log of a factorial. n! ~ sqrt(2*pi*n) * pow((n/e), n) Note: This formula will not give the exact value of the factorial because it is just the approximation of the factorial. " }, { "code": null, "e": 25322, "s": 25318, "text": "C++" }, { "code": null, "e": 25327, "s": 25322, "text": "Java" }, { "code": null, "e": 25335, "s": 25327, "text": "Python3" }, { "code": null, "e": 25338, "s": 25335, "text": "C#" }, { "code": null, "e": 25342, "s": 25338, "text": "PHP" }, { "code": null, "e": 25353, "s": 25342, "text": "Javascript" }, { "code": "// CPP program for calculating factorial// of a number using Stirling// Approximation#include<bits/stdc++.h>using namespace std; // function for calculating factoriallong int stirlingFactorial(int n){ if (n == 1) return 1; long int z; float e = 2.71; // value of natural e // evaluating factorial using // stirling approximation z = sqrt(2*3.14*n) * pow((n/e), n); return z;} // driver programint main(){ cout << stirlingFactorial(1) << endl; cout << stirlingFactorial(2) << endl; cout << stirlingFactorial(3) << endl; cout << stirlingFactorial(4) << endl; cout << stirlingFactorial(5) << endl; cout << stirlingFactorial(6) << endl; cout << stirlingFactorial(7) << endl; return 0;}", "e": 26092, "s": 25353, "text": null }, { "code": "// Java program for calculating// factorial of a number using// Stirling Approximationclass GFG{ // function for// calculating factorialpublic static int stirlingFactorial(double n){ if (n == 1) return 1; double z; double e = 2.71; // value of natural e // evaluating factorial using // stirling approximation z = Math.sqrt(2 * 3.14 * n) * Math.pow((n / e), n); return (int)(z);} // Driver Codepublic static void main(String[] args){ System.out.println(stirlingFactorial(1)); System.out.println(stirlingFactorial(2)); System.out.println(stirlingFactorial(3)); System.out.println(stirlingFactorial(4)); System.out.println(stirlingFactorial(5)); System.out.println(stirlingFactorial(6)); System.out.println(stirlingFactorial(7));}} // This code is contributed by mits.", "e": 26924, "s": 26092, "text": null }, { "code": "# Python3 program for calculating# factorial of a number using# Stirling Approximationimport math # Function for calculating factorialdef stirlingFactorial(n): if (n == 1): return 1 # value of natural e e = 2.71 # evaluating factorial using # stirling approximation z = (math.sqrt(2 * 3.14 * n) * math.pow((n / e), n)) return math.floor(z) # Driver Codeprint(stirlingFactorial(1))print(stirlingFactorial(2))print(stirlingFactorial(3))print(stirlingFactorial(4))print(stirlingFactorial(5))print(stirlingFactorial(6))print(stirlingFactorial(7)) # This code is contributed by mits", "e": 27540, "s": 26924, "text": null }, { "code": "// C# program for calculating// factorial of a number using// Stirling Approximation class GFG{ // function for// calculating factorialpublic static int stirlingFactorial(double n){ if (n == 1) return 1; double z; double e = 2.71; // value of natural e // evaluating factorial using // stirling approximation z = System.Math.Sqrt(2 * 3.14 * n) * System.Math.Pow((n / e), n); return (int)(z);} // Driver Codepublic static void Main(){ System.Console.WriteLine(stirlingFactorial(1)); System.Console.WriteLine(stirlingFactorial(2)); System.Console.WriteLine(stirlingFactorial(3)); System.Console.WriteLine(stirlingFactorial(4)); System.Console.WriteLine(stirlingFactorial(5)); System.Console.WriteLine(stirlingFactorial(6)); System.Console.WriteLine(stirlingFactorial(7));}} // This code is contributed by mits.", "e": 28414, "s": 27540, "text": null }, { "code": "<?php// PHP program for calculating factorial// of a number using Stirling// Approximation // Function for calculating factorialfunction stirlingFactorial($n){ if ($n == 1) return 1; $z; // value of natural e $e = 2.71; // evaluating factorial using // stirling approximation $z = sqrt(2 * 3.14 * $n) * pow(($n / $e), $n); return floor($z);} // Driver Code echo stirlingFactorial(1),\"\\n\"; echo stirlingFactorial(2) ,\"\\n\"; echo stirlingFactorial(3) ,\"\\n\"; echo stirlingFactorial(4), \"\\n\" ; echo stirlingFactorial(5) ,\"\\n\"; echo stirlingFactorial(6) ,\" \\n\"; echo stirlingFactorial(7) ,\" \\n\"; // This code is contributed by anuj_67.?>", "e": 29120, "s": 28414, "text": null }, { "code": "<script>// Javascript program for calculating factorial// of a number using Stirling// Approximation // Function for calculating factorialfunction stirlingFactorial(n){ if (n == 1) return 1; let z; // value of natural e let e = 2.71; // evaluating factorial using // stirling approximation z = Math.sqrt(2 * 3.14 * n) * Math.pow((n / e), n); return Math.floor(z);} // Driver Code document.write( stirlingFactorial(1) + \"<br>\"); document.write( stirlingFactorial(2) + \"<br>\"); document.write( stirlingFactorial(3) + \"<br>\"); document.write( stirlingFactorial(4) + \"<br>\"); document.write( stirlingFactorial(5) + \"<br>\"); document.write( stirlingFactorial(6) + \"<br>\"); document.write( stirlingFactorial(7) + \"<br>\"); // This code is contributed by _saurabh_jaiswal.</script>", "e": 29968, "s": 29120, "text": null }, { "code": null, "e": 29978, "s": 29968, "text": "Output: " }, { "code": null, "e": 30000, "s": 29978, "text": "1\n1\n5\n23\n119\n723\n5086" }, { "code": null, "e": 30440, "s": 30000, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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": 30445, "s": 30440, "text": "vt_m" }, { "code": null, "e": 30458, "s": 30445, "text": "Mithun Kumar" }, { "code": null, "e": 30469, "s": 30458, "text": "BournThing" }, { "code": null, "e": 30486, "s": 30469, "text": "_saurabh_jaiswal" }, { "code": null, "e": 30496, "s": 30486, "text": "factorial" }, { "code": null, "e": 30509, "s": 30496, "text": "Mathematical" }, { "code": null, "e": 30522, "s": 30509, "text": "Mathematical" }, { "code": null, "e": 30532, "s": 30522, "text": "factorial" }, { "code": null, "e": 30630, "s": 30532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30662, "s": 30630, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 30706, "s": 30662, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30731, "s": 30706, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 30764, "s": 30731, "text": "Program to multiply two matrices" }, { "code": null, "e": 30795, "s": 30764, "text": "Modular multiplicative inverse" }, { "code": null, "e": 30827, "s": 30795, "text": "Check if a number is Palindrome" }, { "code": null, "e": 30862, "s": 30827, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 30901, "s": 30862, "text": "Find first and last digits of a number" }, { "code": null, "e": 30952, "s": 30901, "text": "Find Union and Intersection of two unsorted arrays" } ]
Difference Between Running and Runnable States of a Thread in Java - GeeksforGeeks
22 Nov, 2021 Thread is the backbone of multithreading in java. Multithreading is a feature that allows concurrent execution of two or more parts of the program for the maximum utilization of CPU. Each part of such a program is called a thread. So threads are light-weighted processes within a process. A thread can have multiple states in Java and lies in any one of the following states at any time of execution New Runnable Running Waiting/Blocked Terminated/Dead The runnable state of a thread is a state in which the thread is ready to run is said to be in a Runnable state or in other words waiting for other threads (currently executing) to complete its execution and execute itself. Running State of a thread where the currently executing in the processor is said to in a Running state. It is the responsibility of the thread scheduler to give the thread, time to run. A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other threads can get a chance to run. Here we will be discussing the differences between Runnable and Running states as most of the learning programmers get confused in both these states. Below is the program been provided for the better’s sake of clarity and internal working. Example: Java // java Program to illustrate Difference between// Running and Runnable states of Thread // Importing input output classesimport java.io.*; // Class 1// Helper Class (extending main Thread class)// Defining Thread1class Thread1 extends Thread { // run() method for Thread1 public void run() { // Display message only when thread1 starts System.out.println("Thread 1 started "); // Iterations for (int i = 101; i < 200; i++) System.out.print(i + " "); // Display message only when thread1 ended System.out.println("\nThread 1 completed"); }} // Class 2// Helper Class (extending main Thread class)// Defining Thread2class Thread2 extends Thread { // run() method for Thread 2 public void run() { // Display message only when thread 2 starts System.out.println("Thread 2 started "); // Iterations for (int i = 201; i < 300; i++) System.out.print(i + " "); // Display message only when thread 2 ended System.out.println("\nThread 2 completed"); }} // Class 3// Helper Class (extending main Thread class)// Defining Thread3class Thread3 extends Thread { // run() method for Thread 3 public void run() { // Display message only when thread 3 starts System.out.println("Thread 3 started "); // Iterations for (int i = 301; i < 400; i++) System.out.print(i + " "); // Display message only when thread 3 starts System.out.println("\nThread 3 completed"); }} // Class 4// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of each of the threads // defined Thread1 thread1 = new Thread1(); Thread2 thread2 = new Thread2(); Thread3 thread3 = new Thread3(); // Instructing thread to start the execution // using the start() method thread1.start(); thread2.start(); thread3.start(); } // Catch block to handle the exceptions catch (Exception e) { // Print the line number where exception // occured e.printStackTrace(); } }} Output: Thread 1 started Thread 2 started Thread 3 started 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 Thread 3 completed 101 102 103 104 201 105 202 106 107 203 108 204 109 205 110 206 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 Thread 2 completed 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 Thread 1 completed Note: The Output of the above code is not necessarily the same for every time we execute, since it depends on the CPU ( thread scheduler) which thread is allocated with the processor and for how much time. Output Explanation: In order to understand this in the context of the above program consider when the 301 statement is being printed it means thread3 is in running state, but what is the state of thread1 and thread2, the answer is, in the meanwhile when thread3 is being executed in the processor, thread2 and thread1 are waiting for their turn to be processed or executed, i.e. they currently are in Runnable state (or ready to run). akshaysingh98088 sooda367 Java-Multithreading Difference Between Java Java 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24858, "s": 24830, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25148, "s": 24858, "text": "Thread is the backbone of multithreading in java. Multithreading is a feature that allows concurrent execution of two or more parts of the program for the maximum utilization of CPU. Each part of such a program is called a thread. So threads are light-weighted processes within a process." }, { "code": null, "e": 25259, "s": 25148, "text": "A thread can have multiple states in Java and lies in any one of the following states at any time of execution" }, { "code": null, "e": 25263, "s": 25259, "text": "New" }, { "code": null, "e": 25272, "s": 25263, "text": "Runnable" }, { "code": null, "e": 25280, "s": 25272, "text": "Running" }, { "code": null, "e": 25296, "s": 25280, "text": "Waiting/Blocked" }, { "code": null, "e": 25312, "s": 25296, "text": "Terminated/Dead" }, { "code": null, "e": 25722, "s": 25312, "text": "The runnable state of a thread is a state in which the thread is ready to run is said to be in a Runnable state or in other words waiting for other threads (currently executing) to complete its execution and execute itself. Running State of a thread where the currently executing in the processor is said to in a Running state. It is the responsibility of the thread scheduler to give the thread, time to run." }, { "code": null, "e": 25958, "s": 25722, "text": "A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other threads can get a chance to run." }, { "code": null, "e": 26198, "s": 25958, "text": "Here we will be discussing the differences between Runnable and Running states as most of the learning programmers get confused in both these states. Below is the program been provided for the better’s sake of clarity and internal working." }, { "code": null, "e": 26207, "s": 26198, "text": "Example:" }, { "code": null, "e": 26212, "s": 26207, "text": "Java" }, { "code": "// java Program to illustrate Difference between// Running and Runnable states of Thread // Importing input output classesimport java.io.*; // Class 1// Helper Class (extending main Thread class)// Defining Thread1class Thread1 extends Thread { // run() method for Thread1 public void run() { // Display message only when thread1 starts System.out.println(\"Thread 1 started \"); // Iterations for (int i = 101; i < 200; i++) System.out.print(i + \" \"); // Display message only when thread1 ended System.out.println(\"\\nThread 1 completed\"); }} // Class 2// Helper Class (extending main Thread class)// Defining Thread2class Thread2 extends Thread { // run() method for Thread 2 public void run() { // Display message only when thread 2 starts System.out.println(\"Thread 2 started \"); // Iterations for (int i = 201; i < 300; i++) System.out.print(i + \" \"); // Display message only when thread 2 ended System.out.println(\"\\nThread 2 completed\"); }} // Class 3// Helper Class (extending main Thread class)// Defining Thread3class Thread3 extends Thread { // run() method for Thread 3 public void run() { // Display message only when thread 3 starts System.out.println(\"Thread 3 started \"); // Iterations for (int i = 301; i < 400; i++) System.out.print(i + \" \"); // Display message only when thread 3 starts System.out.println(\"\\nThread 3 completed\"); }} // Class 4// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of each of the threads // defined Thread1 thread1 = new Thread1(); Thread2 thread2 = new Thread2(); Thread3 thread3 = new Thread3(); // Instructing thread to start the execution // using the start() method thread1.start(); thread2.start(); thread3.start(); } // Catch block to handle the exceptions catch (Exception e) { // Print the line number where exception // occured e.printStackTrace(); } }}", "e": 28531, "s": 26212, "text": null }, { "code": null, "e": 28539, "s": 28531, "text": "Output:" }, { "code": null, "e": 29835, "s": 28539, "text": "Thread 1 started Thread 2 started Thread 3 started 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 Thread 3 completed 101 102 103 104 201 105 202 106 107 203 108 204 109 205 110 206 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 Thread 2 completed 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 Thread 1 completed" }, { "code": null, "e": 30041, "s": 29835, "text": "Note: The Output of the above code is not necessarily the same for every time we execute, since it depends on the CPU ( thread scheduler) which thread is allocated with the processor and for how much time." }, { "code": null, "e": 30061, "s": 30041, "text": "Output Explanation:" }, { "code": null, "e": 30476, "s": 30061, "text": "In order to understand this in the context of the above program consider when the 301 statement is being printed it means thread3 is in running state, but what is the state of thread1 and thread2, the answer is, in the meanwhile when thread3 is being executed in the processor, thread2 and thread1 are waiting for their turn to be processed or executed, i.e. they currently are in Runnable state (or ready to run)." }, { "code": null, "e": 30495, "s": 30478, "text": "akshaysingh98088" }, { "code": null, "e": 30504, "s": 30495, "text": "sooda367" }, { "code": null, "e": 30524, "s": 30504, "text": "Java-Multithreading" }, { "code": null, "e": 30543, "s": 30524, "text": "Difference Between" }, { "code": null, "e": 30548, "s": 30543, "text": "Java" }, { "code": null, "e": 30553, "s": 30548, "text": "Java" }, { "code": null, "e": 30651, "s": 30553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30712, "s": 30651, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30780, "s": 30712, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 30838, "s": 30780, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 30893, "s": 30838, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 30967, "s": 30893, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 30982, "s": 30967, "text": "Arrays in Java" }, { "code": null, "e": 31026, "s": 30982, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31048, "s": 31026, "text": "For-each loop in Java" }, { "code": null, "e": 31084, "s": 31048, "text": "Arrays.sort() in Java with examples" } ]
Gerrit - Quick Guide
Gerrit is a web based code review tool which is integrated with Git and built on top of Git version control system (helps developers to work together and maintain the history of their work). It allows to merge changes to Git repository when you are done with the code reviews. Gerrit was developed by Shawn Pearce at Google which is written in Java, Servlet, GWT(Google Web Toolkit). The stable release of Gerrit is 2.12.2 and published on March 11, 2016 licensed under Apache License v2. Following are certain reasons, why you should use Gerrit. You can easily find the error in the source code using Gerrit. You can easily find the error in the source code using Gerrit. You can work with Gerrit, if you have regular Git client; no need to install any Gerrit client. You can work with Gerrit, if you have regular Git client; no need to install any Gerrit client. Gerrit can be used as an intermediate between developers and git repositories. Gerrit can be used as an intermediate between developers and git repositories. Gerrit is a free and an open source Git version control system. Gerrit is a free and an open source Git version control system. The user interface of Gerrit is formed on Google Web Toolkit. The user interface of Gerrit is formed on Google Web Toolkit. It is a lightweight framework for reviewing every commit. It is a lightweight framework for reviewing every commit. Gerrit acts as a repository, which allows pushing the code and creates the review for your commit. Gerrit acts as a repository, which allows pushing the code and creates the review for your commit. Gerrit provides access control for Git repositories and web frontend for code review. Gerrit provides access control for Git repositories and web frontend for code review. You can push the code without using additional command line tools. You can push the code without using additional command line tools. Gerrit can allow or decline the permission on the repository level and down to the branch level. Gerrit can allow or decline the permission on the repository level and down to the branch level. Gerrit is supported by Eclipse. Gerrit is supported by Eclipse. Reviewing, verifying and resubmitting the code commits slows down the time to market. Reviewing, verifying and resubmitting the code commits slows down the time to market. Gerrit can work only with Git. Gerrit can work only with Git. Gerrit is slow and it's not possible to change the sort order in which changes are listed. Gerrit is slow and it's not possible to change the sort order in which changes are listed. You need administrator rights to add repository on Gerrit. You need administrator rights to add repository on Gerrit. Before you can use Gerrit, you have to install Git and perform some basic configuration changes. Following are the steps to install Git client on different platforms. You can install the Git on Linux by using the software package management tool. For instance, if you are using Fedora, you can use as − sudo yum install git If you are using Debian-based distribution such as Ubuntu, then use the following command − sudo apt-get install git You can install Git on Windows by downloading it from the Git website. Just go to msysgit.github.io link and click on the download button. Git can be installed on Mac using the following command − brew install git Another way of installing Git is, by downloading it from Git website. Just go to Git install on Mac link, which will install Git for Mac platform. Once you have installed Git, you need to customize the configuration variables to add your personal information. You can get and set the configuration variables by using Git tool called git config along with the -l option (this option provides the current configuration). git config -l When you run the above command, you will get the configuration variables as shown in the following image You can change the customized information any time by using the commands again. In the next chapter, you will learn how to configure the user name and user Email by using git config command. You can track each commit by setting name and email variables. The name variable specifies the name, while the email variable identifies the email address associated with Git commits. You can set these using the following commands − git config --global user.email "your_email@mail.com" git config --global user.name "your_name" When you run the above commands, you will get the user name and email address as shown in the following image. SSH stands for Secure Shell or sometimes Secure Socket Shell protocol used for accessing network services securely from a remote computer. You can set the SSH keys to provide a reliable connection between the computer and Gerrit. You can check the existing SSH key on your local computer using the following command in Git Bash − $ ls ~/.ssh After clicking the enter button, you will see the existing SSH key as shown in the following image − If you don't find any existing SSH key, then you need to create a new SSH key. You can generate a new SSH key for authentication using the following command in Git Bash − $ ssh-keygen -t rsa -C "your_email@mail.com" If you already have a SSH key, then don't a generate new key, as they will be overwritten. You can use ssh-keygen command, only if you have installed Git with Git Bash. When you run the above command, it will create 2 files in the ~/.ssh directory. ~/.ssh/id_rsa − It is private key or identification key. ~/.ssh/id_rsa − It is private key or identification key. ~/.ssh/id_rsa.pub − It is a public tv. ~/.ssh/id_rsa.pub − It is a public tv. You can add SSH key to the ssh-agent on different platforms discussed further. Use the following command on Linux system to add SSH key cat /home/<local-user>/.ssh/id_rsa.pub Open the GIT GUI and go to Help → Show SSH Key as shown in the following image. Then, click the Copy To Clipboard button, to copy the key to the clipboard. In Mac OS X, you can copy id_rsa.pub contents to the clipboard using the following command. $ pbcopy < ~/.ssh/id_rsa.pub SSH key can be added to the Gerrit account using the following steps − Step 1 − First create an account at wmflabs.org services. Step 1 − First create an account at wmflabs.org services. Step 2 − Next sign in to the web interface for Gerrit. Step 2 − Next sign in to the web interface for Gerrit. Step 3 − Then in the top right corner, click your username and select the Settings option. Here, we have created an account with the name John to make use of Gerrit Step 3 − Then in the top right corner, click your username and select the Settings option. Here, we have created an account with the name John to make use of Gerrit Step 4 − Click the "SSH Public keys" option on the left-side menu and paste the SSH Public key in the field. Step 4 − Click the "SSH Public keys" option on the left-side menu and paste the SSH Public key in the field. You can add SSH key to Git using the following commands − Step 1 − Open Git Bash and get the ssh-agent using the following command. Step 1 − Open Git Bash and get the ssh-agent using the following command. $ eval 'ssh-agent' Step 2 − Next, add the SSH key to the ssh-agent using the following command Step 2 − Next, add the SSH key to the ssh-agent using the following command $ ssh-add ~/.ssh/id_rsa Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time. Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time. $ ssh -p 29418 <user_name>@gerrit.wikimedia.org In the above screenshot, you can see that xyz123 is a instance shell account name, which is used while creating Gerrit account and Abc123 is a user name of your Gerrit account. You can download the example using Git along with the source code of any project organized at gerrit.wikimedia.org using the following Git Bash command. $ git clone ssh://<user_name>@gerrit.wikimedia.org:29418/mediawiki/extensions/examples The git clone command clones a directory into a new directory; in other words gets a copy of an existing repository. When you run the above command, you will get a screenshot similar to the following. The above command clones the 'examples' repository and receives the objects, files, etc. from that repository and stores it in your local branch. You can work with Gerrit by installing git-review on different platforms as discussed in this chapter. In Windows, you can install the git-review as listed in the following steps. Step 1 − First install Python for installing git-review. Step 2 − Keep the Python installation in the default directory (like C:\Python27) instead of installing in any other directory. Step 3 − Next, set the environment variables for Python scripts directory using the path as C:\Python27\;C:\Python27\Scripts\; git_review_install Step 4 − With version 2.7, Python will install pip automatically. For older version of Python 2.7, you can install pip as described in this link. Step 5 − Run open Git Bash and install the git-review using the following command. $ pip install git-review In Linux, you can install git-review as described in the following steps − Step 1 Users of Linux platform do not have root access on shared host. Hence, without root access, you can install git-review locally in user directory using the following commands − virtualenv --python=/usr/bin/python2.6 virtualenv virtualenv/bin/pip install git-review==1.21 Step 2 − You can extend the path to the local binaries using two ways − PATH=$PATH:~/virtualenv/bin/ PATH=~/virtualenv/bin/:$PATH Step 3 − Now, use the following command to set up the work with Gerrit. git review -s or ~/virtualenv/bin/git-review -s Step 4 − With root access, git-review can be installed using the following command. sudo apt-get install git-review Step 5 − If there is no apt-get after installing Python, then use the following commands. $ sudo easy_install pip $ sudo pip install git-review==1.21 Step 6 − Run the following command to work with Gerrit. git review -s In Mac, you can install the git-review using the following steps. Step 1 − Install the Homebrew from this link. Step 2 − Next, install the git-review using the following command. brew install git-review Gerrit is built on top of Git version control system, which extracts the code from other host, pushing changes to the code, submitting the code for review, etc. The default remote name of Git is origin and we tell git-review to use this name 'origin' by using the following command. $ git config --global gitreview.remote origin Git-review can be used to send git branches to Gerrit for reviewing. You can set up gitreview using the following command in the project directory. $ git review -s Git-review can be used as the command line tool for configuring Git clone, submitting the branches to Gerrit, fetching the existing files, etc. Git-review looks for the remote named gerrit for working with Gerrit by default. If git-review finds the Gerrit remote, then it will submit the branch to HEAD:refs/for/master at the remote location and if there is no Gerrit remote access, then git-review looks for the .gitreview file at the root of the repository along with the gerrit remote information. Git-review processes the following internally − It will check whether the remote repository works or not for submitting the branches. It will check whether the remote repository works or not for submitting the branches. If there is no Gerrit remote access, then it will ask for the username and try to access the repository again. If there is no Gerrit remote access, then it will ask for the username and try to access the repository again. It will create a remote access called gerrit that points to Gerrit. It will create a remote access called gerrit that points to Gerrit. It will install the commit-msg hook. It will install the commit-msg hook. You can make the master branch up-to-date using the following command. The git-pull command fetches from another local branch or integrates with another repository. git pull origin master The command will pull changes from the origin remote (URL of remote to fetch from), master branch and merge the changes to local checked-out branch. The command will pull changes from the origin remote (URL of remote to fetch from), master branch and merge the changes to local checked-out branch. The origin master is a cached copy of the last pulled from the origin. The origin master is a cached copy of the last pulled from the origin. Git pull is a combination of git fetch (fetches new commits from the remote repository) and git merge (integrates new commits into local branch). Git pull is a combination of git fetch (fetches new commits from the remote repository) and git merge (integrates new commits into local branch). Git pull merges the local branch with the remote branch by default. Git pull merges the local branch with the remote branch by default. You can create a branch on the local machine using the following command. $ git checkout -b name_of_branch origin/master The above command creates a new branch as shown in the following screenshot. Here, we have used branch123 as the new local branch. You can show the new branch from the 'master' using the following command. $ git branch The above command produces the result as shown in the following screenshot. Git checkout navigates between the branch, updates the files in the working directory, and informs Git to record the commits on that branch. When you modify the code in the local file system, you can check for the changes within the directory using the following command. $ git diff In the project directory, we will modify some changes in the file called Example/Example.hooks.php and run the above command. We will get the result as shown in the following screenshot. You can check the changes made to the files or the directory using the following command. $ git status The above command allows to see which changes have been staged, which have not, and which files are not tracked by Git. Next, you can add the changes in the working directory and update the file in the next commit using following command. $ git add Example/Example.hooks.php After adding the file, again run the git status command to review the changes added to the staging area as shown in the following screenshot. You can see the difference between the index and your last commit, and what contents have been staged, using the following command. $ git diff --cached You can push the changes to the remote directory from the local repository using the following command. $ git commit When you run the above command, it will ask to add the commit message for your changes. This message will be seen by other people when you push the commit to the other repository. Add the commit message and run the command again as git commit, which will display the commit message as shown in the following screenshot. You need to review the changes in Gerrit before merging them into the master. The changes can be synchronized that have occurred in the master. Use the following command within the branch that you have been working on. $ git pull --rebase origin master The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master. The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master. When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review. When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review. Git pull --rebase is often used when changes do not deserve a separate branch. Git pull --rebase is often used when changes do not deserve a separate branch. Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase. Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase. First, run the command as git pull origin master as shown in the following screenshot. Now use the command as git rebase master to rebase the commits as shown in the following screenshot. You can submit the patches for review by using the git-review command. The change set can be pushed to Gerrit, by running the git review -R command as shown in the following screenshot. The -R option informs git-review not to complete rebase before submitting git changes to Gerrit. You can submit the code to other branch rather than the master, using the following command. git review name_of_branch It is also possible to submit the code to a different remote, using the following command. git review -r name_of_remote The changes can be viewed in Gerrit dashboard by clicking in this link. Click the modified author name link, and you will get the following screenshot. Click the diffusion link to see the changed files with other details as shown in the following screenshot. You can edit the project via the web interface after logging in to the Gerrit account as shown in the following steps. Step 1 − Go to Gerrit dashboard by clicking this link. You will get the following screenshot. Step 2 − Next click the mediawiki/extensions/examples link specified under Project column. Step 3 − Click the General link in the toolbar as shown in the following screenshot. Step 4 − When you open the General link, it will show a screenshot as the following. Step 5 − Click the Create Change button and it will open a popup window with some details as shown in the following screenshot. Step 6 − Enter the information and click the Create button. After creating the change, it will display the information as shown in the following screenshot. Step 7 − Click Edit and then click Add. Now select the file you want to edit. Here we have selected the file Example/i18n/en.json. When you open the file, it will show the json data as specified in the following screenshot. Step 8 − Click Save and then click the Close button. Step 9 − Finally click the Publish button to publish the edited file Step 10 − You can change commit message by clicking the Commit Message link as shown in the following screenshot. Step 11 − Press e on the keyboard and add some extra information, if you wish to Click Save and then click the Close button. Code review is an important part of the workflow in Gerrit. The basic concept is that the code must be reviewed before being merged. The workflow of the code for MediaWiki can be reviewed before merging it and also extensions can be reviewed which customizes the MediaWiki looks and works. There is one special case in which you can push the internationalization and localization commits. You can push all the commits to a remote branch when you finish the development. Someone will fetch the changes into local and merge those fetched changes into the local master by creating merge commit. You can push these changes to refs/for/master. Project owner means that the project belongs to the person mentioned. Project owners is a virtual group in which you cannot add members or other groups in it. The project owner provides access rights to allow permission on the project to different groups. You can view the access rights of your project using the following steps. Step 1 − Open Gerrit dashboard by clicking this link. Step 2 − Click Projects → List option. Search the project in your project list and click it as shown in the following screenshot. Step 3 − When you open your project, click the Access option as shown in the following screenshot. Step 4 − Click the edit option. You can change the access rights by clicking the dropdown menu. Click the Save Changes button as shown in the following screenshot. Anyone can review the code and comment on the code in Gerrit. Consider the following steps − Step 1 − Login to Gerrit to open the Gerrit dashboard as specified in the previous chapter. Step 2 − Now, click any subject which contains Gerrit project, branch, updated date, etc. as shown in the following screenshot. Step 3 − Next, it will display a screen. Click the Commit Message option as shown in the following screenshot. The important fields of the change set are like Reviewers, Add Reviewer, Side-by-side off, etc. Comparing patch sets includes selecting the old version history list, expanding the newer patch set details, etc. Reviewing and merging or rejecting the code includes abandon change button, submitting patch button, etc. which are not present in the current version of Gerrit. Print Add Notes Bookmark this page
[ { "code": null, "e": 2515, "s": 2238, "text": "Gerrit is a web based code review tool which is integrated with Git and built on top of Git version control system (helps developers to work together and maintain the history of their work). It allows to merge changes to Git repository when you are done with the code reviews." }, { "code": null, "e": 2728, "s": 2515, "text": "Gerrit was developed by Shawn Pearce at Google which is written in Java, Servlet, GWT(Google Web Toolkit). The stable release of Gerrit is 2.12.2 and published on March 11, 2016 licensed under Apache License v2." }, { "code": null, "e": 2786, "s": 2728, "text": "Following are certain reasons, why you should use Gerrit." }, { "code": null, "e": 2849, "s": 2786, "text": "You can easily find the error in the source code using Gerrit." }, { "code": null, "e": 2912, "s": 2849, "text": "You can easily find the error in the source code using Gerrit." }, { "code": null, "e": 3008, "s": 2912, "text": "You can work with Gerrit, if you have regular Git client; no need to install any Gerrit\nclient." }, { "code": null, "e": 3104, "s": 3008, "text": "You can work with Gerrit, if you have regular Git client; no need to install any Gerrit\nclient." }, { "code": null, "e": 3184, "s": 3104, "text": "Gerrit can be used as an intermediate between developers and git repositories.\n" }, { "code": null, "e": 3264, "s": 3184, "text": "Gerrit can be used as an intermediate between developers and git repositories.\n" }, { "code": null, "e": 3328, "s": 3264, "text": "Gerrit is a free and an open source Git version control system." }, { "code": null, "e": 3392, "s": 3328, "text": "Gerrit is a free and an open source Git version control system." }, { "code": null, "e": 3454, "s": 3392, "text": "The user interface of Gerrit is formed on Google Web Toolkit." }, { "code": null, "e": 3516, "s": 3454, "text": "The user interface of Gerrit is formed on Google Web Toolkit." }, { "code": null, "e": 3574, "s": 3516, "text": "It is a lightweight framework for reviewing every commit." }, { "code": null, "e": 3632, "s": 3574, "text": "It is a lightweight framework for reviewing every commit." }, { "code": null, "e": 3731, "s": 3632, "text": "Gerrit acts as a repository, which allows pushing the code and creates the review for your commit." }, { "code": null, "e": 3830, "s": 3731, "text": "Gerrit acts as a repository, which allows pushing the code and creates the review for your commit." }, { "code": null, "e": 3916, "s": 3830, "text": "Gerrit provides access control for Git repositories and web frontend for code review." }, { "code": null, "e": 4002, "s": 3916, "text": "Gerrit provides access control for Git repositories and web frontend for code review." }, { "code": null, "e": 4070, "s": 4002, "text": "You can push the code without using additional command line tools.\n" }, { "code": null, "e": 4138, "s": 4070, "text": "You can push the code without using additional command line tools.\n" }, { "code": null, "e": 4235, "s": 4138, "text": "Gerrit can allow or decline the permission on the repository level and down to the\nbranch level." }, { "code": null, "e": 4332, "s": 4235, "text": "Gerrit can allow or decline the permission on the repository level and down to the\nbranch level." }, { "code": null, "e": 4364, "s": 4332, "text": "Gerrit is supported by Eclipse." }, { "code": null, "e": 4396, "s": 4364, "text": "Gerrit is supported by Eclipse." }, { "code": null, "e": 4482, "s": 4396, "text": "Reviewing, verifying and resubmitting the code commits slows down the time to market." }, { "code": null, "e": 4568, "s": 4482, "text": "Reviewing, verifying and resubmitting the code commits slows down the time to market." }, { "code": null, "e": 4599, "s": 4568, "text": "Gerrit can work only with Git." }, { "code": null, "e": 4630, "s": 4599, "text": "Gerrit can work only with Git." }, { "code": null, "e": 4721, "s": 4630, "text": "Gerrit is slow and it's not possible to change the sort order in which changes are\nlisted." }, { "code": null, "e": 4812, "s": 4721, "text": "Gerrit is slow and it's not possible to change the sort order in which changes are\nlisted." }, { "code": null, "e": 4871, "s": 4812, "text": "You need administrator rights to add repository on Gerrit." }, { "code": null, "e": 4930, "s": 4871, "text": "You need administrator rights to add repository on Gerrit." }, { "code": null, "e": 5097, "s": 4930, "text": "Before you can use Gerrit, you have to install Git and perform some basic configuration changes. Following are the steps to install Git client on different platforms." }, { "code": null, "e": 5233, "s": 5097, "text": "You can install the Git on Linux by using the software package management tool. For instance, if you are using Fedora, you can use as −" }, { "code": null, "e": 5255, "s": 5233, "text": "sudo yum install git\n" }, { "code": null, "e": 5347, "s": 5255, "text": "If you are using Debian-based distribution such as Ubuntu, then use the following command −" }, { "code": null, "e": 5373, "s": 5347, "text": "sudo apt-get install git\n" }, { "code": null, "e": 5513, "s": 5373, "text": "You can install Git on Windows by downloading it from the Git website. Just go to msysgit.github.io link and click on the download button." }, { "code": null, "e": 5571, "s": 5513, "text": "Git can be installed on Mac using the following command −" }, { "code": null, "e": 5589, "s": 5571, "text": "brew install git\n" }, { "code": null, "e": 5736, "s": 5589, "text": "Another way of installing Git is, by downloading it from Git website. Just go to Git install on Mac link, which will install Git for Mac platform." }, { "code": null, "e": 6008, "s": 5736, "text": "Once you have installed Git, you need to customize the configuration variables to add your personal information. You can get and set the configuration variables by using Git tool called git config along with the -l option (this option provides the current configuration)." }, { "code": null, "e": 6023, "s": 6008, "text": "git config -l\n" }, { "code": null, "e": 6128, "s": 6023, "text": "When you run the above command, you will get the configuration variables as shown in the following image" }, { "code": null, "e": 6319, "s": 6128, "text": "You can change the customized information any time by using the commands again. In the next chapter, you will learn how to configure the user name and user Email by using git config command." }, { "code": null, "e": 6552, "s": 6319, "text": "You can track each commit by setting name and email variables. The name variable specifies the name, while the email variable identifies the email address associated with Git commits. You can set these using the following commands −" }, { "code": null, "e": 6648, "s": 6552, "text": "git config --global user.email \"your_email@mail.com\"\ngit config --global user.name \"your_name\"\n" }, { "code": null, "e": 6759, "s": 6648, "text": "When you run the above commands, you will get the user name and email address as shown in the following image." }, { "code": null, "e": 6989, "s": 6759, "text": "SSH stands for Secure Shell or sometimes Secure Socket Shell protocol used for accessing network services securely from a remote computer. You can set the SSH keys to provide a reliable connection between the computer and Gerrit." }, { "code": null, "e": 7089, "s": 6989, "text": "You can check the existing SSH key on your local computer using the following command in Git Bash −" }, { "code": null, "e": 7102, "s": 7089, "text": "$ ls ~/.ssh\n" }, { "code": null, "e": 7203, "s": 7102, "text": "After clicking the enter button, you will see the existing SSH key as shown in the following image −" }, { "code": null, "e": 7282, "s": 7203, "text": "If you don't find any existing SSH key, then you need to create a new SSH key." }, { "code": null, "e": 7374, "s": 7282, "text": "You can generate a new SSH key for authentication using the following command in Git Bash −" }, { "code": null, "e": 7420, "s": 7374, "text": "$ ssh-keygen -t rsa -C \"your_email@mail.com\"\n" }, { "code": null, "e": 7589, "s": 7420, "text": "If you already have a SSH key, then don't a generate new key, as they will be overwritten. You can use ssh-keygen command, only if you have installed Git with Git Bash." }, { "code": null, "e": 7669, "s": 7589, "text": "When you run the above command, it will create 2 files in the ~/.ssh directory." }, { "code": null, "e": 7726, "s": 7669, "text": "~/.ssh/id_rsa − It is private key or identification key." }, { "code": null, "e": 7783, "s": 7726, "text": "~/.ssh/id_rsa − It is private key or identification key." }, { "code": null, "e": 7822, "s": 7783, "text": "~/.ssh/id_rsa.pub − It is a public tv." }, { "code": null, "e": 7861, "s": 7822, "text": "~/.ssh/id_rsa.pub − It is a public tv." }, { "code": null, "e": 7940, "s": 7861, "text": "You can add SSH key to the ssh-agent on different platforms discussed further." }, { "code": null, "e": 7997, "s": 7940, "text": "Use the following command on Linux system to add SSH key" }, { "code": null, "e": 8037, "s": 7997, "text": "cat /home/<local-user>/.ssh/id_rsa.pub\n" }, { "code": null, "e": 8117, "s": 8037, "text": "Open the GIT GUI and go to Help → Show SSH Key as shown in the following image." }, { "code": null, "e": 8193, "s": 8117, "text": "Then, click the Copy To Clipboard button, to copy the key to the clipboard." }, { "code": null, "e": 8285, "s": 8193, "text": "In Mac OS X, you can copy id_rsa.pub contents to the clipboard using the following command." }, { "code": null, "e": 8315, "s": 8285, "text": "$ pbcopy < ~/.ssh/id_rsa.pub\n" }, { "code": null, "e": 8386, "s": 8315, "text": "SSH key can be added to the Gerrit account using the following steps −" }, { "code": null, "e": 8445, "s": 8386, "text": "Step 1 − First create an account at wmflabs.org services.\n" }, { "code": null, "e": 8503, "s": 8445, "text": "Step 1 − First create an account at wmflabs.org services." }, { "code": null, "e": 8559, "s": 8503, "text": "Step 2 − Next sign in to the web interface for Gerrit.\n" }, { "code": null, "e": 8614, "s": 8559, "text": "Step 2 − Next sign in to the web interface for Gerrit." }, { "code": null, "e": 8780, "s": 8614, "text": "Step 3 − Then in the top right corner, click your username and select the Settings option.\n\nHere, we have created an account with the name John to make use of Gerrit" }, { "code": null, "e": 8871, "s": 8780, "text": "Step 3 − Then in the top right corner, click your username and select the Settings option." }, { "code": null, "e": 8945, "s": 8871, "text": "Here, we have created an account with the name John to make use of Gerrit" }, { "code": null, "e": 9055, "s": 8945, "text": "Step 4 − Click the \"SSH Public keys\" option on the left-side menu and paste the SSH Public key in the field.\n" }, { "code": null, "e": 9164, "s": 9055, "text": "Step 4 − Click the \"SSH Public keys\" option on the left-side menu and paste the SSH Public key in the field." }, { "code": null, "e": 9222, "s": 9164, "text": "You can add SSH key to Git using the following commands −" }, { "code": null, "e": 9296, "s": 9222, "text": "Step 1 − Open Git Bash and get the ssh-agent using the following command." }, { "code": null, "e": 9370, "s": 9296, "text": "Step 1 − Open Git Bash and get the ssh-agent using the following command." }, { "code": null, "e": 9390, "s": 9370, "text": "$ eval 'ssh-agent'\n" }, { "code": null, "e": 9466, "s": 9390, "text": "Step 2 − Next, add the SSH key to the ssh-agent using the following command" }, { "code": null, "e": 9542, "s": 9466, "text": "Step 2 − Next, add the SSH key to the ssh-agent using the following command" }, { "code": null, "e": 9567, "s": 9542, "text": "$ ssh-add ~/.ssh/id_rsa\n" }, { "code": null, "e": 9694, "s": 9567, "text": "Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time." }, { "code": null, "e": 9821, "s": 9694, "text": "Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time." }, { "code": null, "e": 9870, "s": 9821, "text": "$ ssh -p 29418 <user_name>@gerrit.wikimedia.org\n" }, { "code": null, "e": 10047, "s": 9870, "text": "In the above screenshot, you can see that xyz123 is a instance shell account name, which is used while creating Gerrit account and Abc123 is a user name of your Gerrit account." }, { "code": null, "e": 10200, "s": 10047, "text": "You can download the example using Git along with the source code of any project organized at gerrit.wikimedia.org using the following Git Bash command." }, { "code": null, "e": 10289, "s": 10200, "text": "$ git clone \nssh://<user_name>@gerrit.wikimedia.org:29418/mediawiki/extensions/examples\n" }, { "code": null, "e": 10490, "s": 10289, "text": "The git clone command clones a directory into a new directory; in other words gets a copy of an existing repository. When you run the above command, you will get a screenshot similar to the following." }, { "code": null, "e": 10636, "s": 10490, "text": "The above command clones the 'examples' repository and receives the objects, files, etc. from that repository and stores it in your local branch." }, { "code": null, "e": 10739, "s": 10636, "text": "You can work with Gerrit by installing git-review on different platforms as discussed in this chapter." }, { "code": null, "e": 10816, "s": 10739, "text": "In Windows, you can install the git-review as listed in the following steps." }, { "code": null, "e": 10873, "s": 10816, "text": "Step 1 − First install Python for installing git-review." }, { "code": null, "e": 11001, "s": 10873, "text": "Step 2 − Keep the Python installation in the default directory (like C:\\Python27) instead of installing in any other directory." }, { "code": null, "e": 11128, "s": 11001, "text": "Step 3 − Next, set the environment variables for Python scripts directory using the path as C:\\Python27\\;C:\\Python27\\Scripts\\;" }, { "code": null, "e": 11148, "s": 11128, "text": "git_review_install\n" }, { "code": null, "e": 11294, "s": 11148, "text": "Step 4 − With version 2.7, Python will install pip automatically. For older version of Python 2.7, you can install pip as described in this link." }, { "code": null, "e": 11377, "s": 11294, "text": "Step 5 − Run open Git Bash and install the git-review using the following command." }, { "code": null, "e": 11403, "s": 11377, "text": "$ pip install git-review\n" }, { "code": null, "e": 11478, "s": 11403, "text": "In Linux, you can install git-review as described in the following steps −" }, { "code": null, "e": 11661, "s": 11478, "text": "Step 1 Users of Linux platform do not have root access on shared host. Hence, without root access, you can install git-review locally in user directory using the following commands −" }, { "code": null, "e": 11756, "s": 11661, "text": "virtualenv --python=/usr/bin/python2.6 virtualenv\nvirtualenv/bin/pip install git-review==1.21\n" }, { "code": null, "e": 11828, "s": 11756, "text": "Step 2 − You can extend the path to the local binaries using two ways −" }, { "code": null, "e": 11887, "s": 11828, "text": "PATH=$PATH:~/virtualenv/bin/\nPATH=~/virtualenv/bin/:$PATH\n" }, { "code": null, "e": 11959, "s": 11887, "text": "Step 3 − Now, use the following command to set up the work with Gerrit." }, { "code": null, "e": 12009, "s": 11959, "text": "git review -s\n or\n~/virtualenv/bin/git-review -s\n" }, { "code": null, "e": 12093, "s": 12009, "text": "Step 4 − With root access, git-review can be installed using the following command." }, { "code": null, "e": 12126, "s": 12093, "text": "sudo apt-get install git-review\n" }, { "code": null, "e": 12216, "s": 12126, "text": "Step 5 − If there is no apt-get after installing Python, then use the following commands." }, { "code": null, "e": 12277, "s": 12216, "text": "$ sudo easy_install pip\n$ sudo pip install git-review==1.21\n" }, { "code": null, "e": 12333, "s": 12277, "text": "Step 6 − Run the following command to work with Gerrit." }, { "code": null, "e": 12348, "s": 12333, "text": "git review -s\n" }, { "code": null, "e": 12414, "s": 12348, "text": "In Mac, you can install the git-review using the following steps." }, { "code": null, "e": 12461, "s": 12414, "text": "Step 1 − Install the Homebrew from this link.\n" }, { "code": null, "e": 12528, "s": 12461, "text": "Step 2 − Next, install the git-review using the following command." }, { "code": null, "e": 12553, "s": 12528, "text": "brew install git-review\n" }, { "code": null, "e": 12836, "s": 12553, "text": "Gerrit is built on top of Git version control system, which extracts the code from other host, pushing changes to the code, submitting the code for review, etc. The default remote name of Git is origin and we tell git-review to use this name 'origin' by using the following command." }, { "code": null, "e": 12883, "s": 12836, "text": "$ git config --global gitreview.remote origin\n" }, { "code": null, "e": 13031, "s": 12883, "text": "Git-review can be used to send git branches to Gerrit for reviewing. You can set up gitreview using the following command in the project directory." }, { "code": null, "e": 13048, "s": 13031, "text": "$ git review -s\n" }, { "code": null, "e": 13273, "s": 13048, "text": "Git-review can be used as the command line tool for configuring Git clone, submitting the branches to Gerrit, fetching the existing files, etc. Git-review looks for the remote named gerrit for working with Gerrit by default." }, { "code": null, "e": 13549, "s": 13273, "text": "If git-review finds the Gerrit remote, then it will submit the branch to HEAD:refs/for/master at the remote location and if there is no Gerrit remote access, then git-review looks for the .gitreview file at the root of the repository along with the gerrit remote information." }, { "code": null, "e": 13597, "s": 13549, "text": "Git-review processes the following internally −" }, { "code": null, "e": 13683, "s": 13597, "text": "It will check whether the remote repository works or not for submitting the branches." }, { "code": null, "e": 13769, "s": 13683, "text": "It will check whether the remote repository works or not for submitting the branches." }, { "code": null, "e": 13880, "s": 13769, "text": "If there is no Gerrit remote access, then it will ask for the username and try to access the repository again." }, { "code": null, "e": 13991, "s": 13880, "text": "If there is no Gerrit remote access, then it will ask for the username and try to access the repository again." }, { "code": null, "e": 14059, "s": 13991, "text": "It will create a remote access called gerrit that points to Gerrit." }, { "code": null, "e": 14127, "s": 14059, "text": "It will create a remote access called gerrit that points to Gerrit." }, { "code": null, "e": 14164, "s": 14127, "text": "It will install the commit-msg hook." }, { "code": null, "e": 14201, "s": 14164, "text": "It will install the commit-msg hook." }, { "code": null, "e": 14366, "s": 14201, "text": "You can make the master branch up-to-date using the following command. The git-pull command fetches from another local branch or integrates with another repository." }, { "code": null, "e": 14390, "s": 14366, "text": "git pull origin master\n" }, { "code": null, "e": 14539, "s": 14390, "text": "The command will pull changes from the origin remote (URL of remote to fetch from), master branch and merge the changes to local checked-out branch." }, { "code": null, "e": 14688, "s": 14539, "text": "The command will pull changes from the origin remote (URL of remote to fetch from), master branch and merge the changes to local checked-out branch." }, { "code": null, "e": 14759, "s": 14688, "text": "The origin master is a cached copy of the last pulled from the origin." }, { "code": null, "e": 14830, "s": 14759, "text": "The origin master is a cached copy of the last pulled from the origin." }, { "code": null, "e": 14976, "s": 14830, "text": "Git pull is a combination of git fetch (fetches new commits from the remote repository) and git merge (integrates new commits into local branch)." }, { "code": null, "e": 15122, "s": 14976, "text": "Git pull is a combination of git fetch (fetches new commits from the remote repository) and git merge (integrates new commits into local branch)." }, { "code": null, "e": 15190, "s": 15122, "text": "Git pull merges the local branch with the remote branch by default." }, { "code": null, "e": 15258, "s": 15190, "text": "Git pull merges the local branch with the remote branch by default." }, { "code": null, "e": 15332, "s": 15258, "text": "You can create a branch on the local machine using the following command." }, { "code": null, "e": 15380, "s": 15332, "text": "$ git checkout -b name_of_branch origin/master\n" }, { "code": null, "e": 15457, "s": 15380, "text": "The above command creates a new branch as shown in the following screenshot." }, { "code": null, "e": 15586, "s": 15457, "text": "Here, we have used branch123 as the new local branch. You can show the new branch from the 'master' using the following command." }, { "code": null, "e": 15600, "s": 15586, "text": "$ git branch\n" }, { "code": null, "e": 15676, "s": 15600, "text": "The above command produces the result as shown in the following screenshot." }, { "code": null, "e": 15817, "s": 15676, "text": "Git checkout navigates between the branch, updates the files in the working directory, and informs Git to record the commits on that branch." }, { "code": null, "e": 15948, "s": 15817, "text": "When you modify the code in the local file system, you can check for the changes within the directory using the following command." }, { "code": null, "e": 15960, "s": 15948, "text": "$ git diff\n" }, { "code": null, "e": 16147, "s": 15960, "text": "In the project directory, we will modify some changes in the file called Example/Example.hooks.php and run the above command. We will get the result as shown in the following screenshot." }, { "code": null, "e": 16237, "s": 16147, "text": "You can check the changes made to the files or the directory using the following command." }, { "code": null, "e": 16251, "s": 16237, "text": "$ git status\n" }, { "code": null, "e": 16371, "s": 16251, "text": "The above command allows to see which changes have been staged, which have not, and which files are not tracked by Git." }, { "code": null, "e": 16490, "s": 16371, "text": "Next, you can add the changes in the working directory and update the file in the next commit using following command." }, { "code": null, "e": 16527, "s": 16490, "text": "$ git add Example/Example.hooks.php\n" }, { "code": null, "e": 16669, "s": 16527, "text": "After adding the file, again run the git status command to review the changes added to the staging area as shown in the following screenshot." }, { "code": null, "e": 16801, "s": 16669, "text": "You can see the difference between the index and your last commit, and what contents have been staged, using the following command." }, { "code": null, "e": 16822, "s": 16801, "text": "$ git diff --cached\n" }, { "code": null, "e": 16926, "s": 16822, "text": "You can push the changes to the remote directory from the local repository using the following command." }, { "code": null, "e": 16940, "s": 16926, "text": "$ git commit\n" }, { "code": null, "e": 17120, "s": 16940, "text": "When you run the above command, it will ask to add the commit message for your changes. This message will be seen by other people when you push the commit to the other repository." }, { "code": null, "e": 17260, "s": 17120, "text": "Add the commit message and run the command again as git commit, which will display the commit message as shown in the following screenshot." }, { "code": null, "e": 17479, "s": 17260, "text": "You need to review the changes in Gerrit before merging them into the master. The changes can be synchronized that have occurred in the master. Use the following command within the branch that you have been working on." }, { "code": null, "e": 17514, "s": 17479, "text": "$ git pull --rebase origin master\n" }, { "code": null, "e": 17634, "s": 17514, "text": "The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master." }, { "code": null, "e": 17754, "s": 17634, "text": "The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master." }, { "code": null, "e": 17865, "s": 17754, "text": "When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review." }, { "code": null, "e": 17976, "s": 17865, "text": "When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review." }, { "code": null, "e": 18055, "s": 17976, "text": "Git pull --rebase is often used when changes do not deserve a separate branch." }, { "code": null, "e": 18134, "s": 18055, "text": "Git pull --rebase is often used when changes do not deserve a separate branch." }, { "code": null, "e": 18261, "s": 18134, "text": "Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase." }, { "code": null, "e": 18388, "s": 18261, "text": "Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase." }, { "code": null, "e": 18475, "s": 18388, "text": "First, run the command as git pull origin master as shown in the following screenshot." }, { "code": null, "e": 18576, "s": 18475, "text": "Now use the command as git rebase master to rebase the commits as shown in the following screenshot." }, { "code": null, "e": 18762, "s": 18576, "text": "You can submit the patches for review by using the git-review command. The change set can be pushed to Gerrit, by running the git review -R command as shown in the following screenshot." }, { "code": null, "e": 18859, "s": 18762, "text": "The -R option informs git-review not to complete rebase before submitting git changes to Gerrit." }, { "code": null, "e": 18952, "s": 18859, "text": "You can submit the code to other branch rather than the master, using the following command." }, { "code": null, "e": 18979, "s": 18952, "text": "git review name_of_branch\n" }, { "code": null, "e": 19070, "s": 18979, "text": "It is also possible to submit the code to a different remote, using the following command." }, { "code": null, "e": 19100, "s": 19070, "text": "git review -r name_of_remote\n" }, { "code": null, "e": 19173, "s": 19100, "text": "The changes can be viewed in Gerrit dashboard by clicking in this link." }, { "code": null, "e": 19253, "s": 19173, "text": "Click the modified author name link, and you will get the following screenshot." }, { "code": null, "e": 19360, "s": 19253, "text": "Click the diffusion link to see the changed files with other details as shown in the following screenshot." }, { "code": null, "e": 19479, "s": 19360, "text": "You can edit the project via the web interface after logging in to the Gerrit account as shown in the following steps." }, { "code": null, "e": 19574, "s": 19479, "text": "Step 1 − Go to Gerrit dashboard by clicking this link. You will get the following screenshot." }, { "code": null, "e": 19665, "s": 19574, "text": "Step 2 − Next click the mediawiki/extensions/examples link specified under Project column." }, { "code": null, "e": 19750, "s": 19665, "text": "Step 3 − Click the General link in the toolbar as shown in the following screenshot." }, { "code": null, "e": 19835, "s": 19750, "text": "Step 4 − When you open the General link, it will show a screenshot as the following." }, { "code": null, "e": 19963, "s": 19835, "text": "Step 5 − Click the Create Change button and it will open a popup window with some details as shown in the following screenshot." }, { "code": null, "e": 20023, "s": 19963, "text": "Step 6 − Enter the information and click the Create button." }, { "code": null, "e": 20120, "s": 20023, "text": "After creating the change, it will display the information as shown in the following screenshot." }, { "code": null, "e": 20251, "s": 20120, "text": "Step 7 − Click Edit and then click Add. Now select the file you want to edit. Here we have selected the file Example/i18n/en.json." }, { "code": null, "e": 20344, "s": 20251, "text": "When you open the file, it will show the json data as specified in the following screenshot." }, { "code": null, "e": 20397, "s": 20344, "text": "Step 8 − Click Save and then click the Close button." }, { "code": null, "e": 20466, "s": 20397, "text": "Step 9 − Finally click the Publish button to publish the edited file" }, { "code": null, "e": 20580, "s": 20466, "text": "Step 10 − You can change commit message by clicking the Commit Message link as shown in the following screenshot." }, { "code": null, "e": 20705, "s": 20580, "text": "Step 11 − Press e on the keyboard and add some extra information, if you wish to Click Save and then click the Close button." }, { "code": null, "e": 20838, "s": 20705, "text": "Code review is an important part of the workflow in Gerrit. The basic concept is that the code must be reviewed before being merged." }, { "code": null, "e": 21094, "s": 20838, "text": "The workflow of the code for MediaWiki can be reviewed before merging it and also extensions can be reviewed which customizes the MediaWiki looks and works. There is one special case in which you can push the internationalization and localization commits." }, { "code": null, "e": 21344, "s": 21094, "text": "You can push all the commits to a remote branch when you finish the development. Someone will fetch the changes into local and merge those fetched changes into the local master by creating merge commit. You can push these changes to refs/for/master." }, { "code": null, "e": 21600, "s": 21344, "text": "Project owner means that the project belongs to the person mentioned. Project owners is a virtual group in which you cannot add members or other groups in it. The project owner provides access rights to allow permission on the project to different groups." }, { "code": null, "e": 21674, "s": 21600, "text": "You can view the access rights of your project using the following steps." }, { "code": null, "e": 21729, "s": 21674, "text": "Step 1 − Open Gerrit dashboard by clicking this link." }, { "code": null, "e": 21859, "s": 21729, "text": "Step 2 − Click Projects → List option. Search the project in your project list and click it as shown in the following screenshot." }, { "code": null, "e": 21958, "s": 21859, "text": "Step 3 − When you open your project, click the Access option as shown in the following screenshot." }, { "code": null, "e": 22122, "s": 21958, "text": "Step 4 − Click the edit option. You can change the access rights by clicking the dropdown menu. Click the Save Changes button as shown in the following screenshot." }, { "code": null, "e": 22215, "s": 22122, "text": "Anyone can review the code and comment on the code in Gerrit. Consider the following steps −" }, { "code": null, "e": 22307, "s": 22215, "text": "Step 1 − Login to Gerrit to open the Gerrit dashboard as specified in the previous chapter." }, { "code": null, "e": 22435, "s": 22307, "text": "Step 2 − Now, click any subject which contains Gerrit project, branch, updated date, etc. as shown in the following screenshot." }, { "code": null, "e": 22546, "s": 22435, "text": "Step 3 − Next, it will display a screen. Click the Commit Message option as shown in the following screenshot." }, { "code": null, "e": 22918, "s": 22546, "text": "The important fields of the change set are like Reviewers, Add Reviewer, Side-by-side off, etc. Comparing patch sets includes selecting the old version history list, expanding the newer patch set details, etc. Reviewing and merging or rejecting the code includes abandon change button, submitting patch button, etc. which are not present in the current version of Gerrit." }, { "code": null, "e": 22925, "s": 22918, "text": " Print" }, { "code": null, "e": 22936, "s": 22925, "text": " Add Notes" } ]